text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import {
FaaSContext,
FaaSMiddleware,
IFaaSConfigurationOptions,
IMidwayFaaSApplication,
IWebMiddleware,
} from './interface';
import {
BaseFramework,
extractKoaLikeValue,
IMiddleware,
IMidwayBootstrapOptions,
MidwayFrameworkType,
REQUEST_OBJ_CTX_KEY,
RouterInfo,
ServerlessTriggerCollector,
} from '@midwayjs/core';
import { dirname, resolve } from 'path';
import {
LOGGER_KEY,
PLUGIN_KEY,
WEB_RESPONSE_HTTP_CODE,
WEB_RESPONSE_HEADER,
WEB_RESPONSE_CONTENT_TYPE,
WEB_RESPONSE_REDIRECT,
} from '@midwayjs/decorator';
import SimpleLock from '@midwayjs/simple-lock';
import * as compose from 'koa-compose';
import { MidwayHooks } from './hooks';
import { createConsoleLogger, LoggerOptions, loggers } from '@midwayjs/logger';
const LOCK_KEY = '_faas_starter_start_key';
// const MIDWAY_FAAS_KEY = '__midway_faas__';
export class MidwayFaaSFramework extends BaseFramework<
IMidwayFaaSApplication,
FaaSContext,
IFaaSConfigurationOptions
> {
protected defaultHandlerMethod = 'handler';
private globalMiddleware: string[];
protected funMappingStore: Map<string, RouterInfo> = new Map();
protected logger;
private lock = new SimpleLock();
public app: IMidwayFaaSApplication;
private isReplaceLogger =
process.env['MIDWAY_SERVERLESS_REPLACE_LOGGER'] === 'true';
async applicationInitialize(options: IMidwayBootstrapOptions) {
this.globalMiddleware = this.configurationOptions.middleware || [];
this.app =
this.configurationOptions.applicationAdapter?.getApplication() ||
({} as IMidwayFaaSApplication);
this.defineApplicationProperties({
/**
* return init context value such as aliyun fc
*/
getInitializeContext: () => {
return this.configurationOptions.initializeContext;
},
useMiddleware: async middlewares => {
if (middlewares.length) {
const newMiddlewares = await this.loadMiddleware(middlewares);
for (const mw of newMiddlewares) {
this.app.use(mw);
}
}
},
generateMiddleware: async (middlewareId: string) => {
return this.generateMiddleware(middlewareId);
},
getFunctionName: () => {
return this.configurationOptions.applicationAdapter?.getFunctionName();
},
getFunctionServiceName: () => {
return this.configurationOptions.applicationAdapter?.getFunctionServiceName();
},
});
}
protected async initializeLogger(options: IMidwayBootstrapOptions) {
if (!this.logger) {
this.logger =
options.logger ||
createConsoleLogger('midwayServerlessLogger', {
printFormat: info => {
const requestId =
info.ctx?.['originContext']?.['requestId'] ??
info.ctx?.['originContext']?.['request_id'] ??
'';
return `${new Date().toISOString()} ${requestId} [${info.level}] ${
info.message
}`;
},
});
this.appLogger = this.logger;
loggers.addLogger('coreLogger', this.logger, false);
loggers.addLogger('appLogger', this.logger, false);
loggers.addLogger('logger', this.logger, false);
}
}
protected async afterContainerReady(
options: Partial<IMidwayBootstrapOptions>
) {
this.registerDecorator();
}
public async run() {
return this.lock.sureOnce(async () => {
// attach global middleware from user config
if (this.app?.use) {
const middlewares = this.app.getConfig('middleware') || [];
await this.app.useMiddleware(middlewares);
this.globalMiddleware = this.globalMiddleware.concat(
this.app['middleware']
);
}
// set app keys
this.app['keys'] = this.app.getConfig('keys') || '';
// store all http function entry
const collector = new ServerlessTriggerCollector(this.getBaseDir());
const functionList = await collector.getFunctionList();
for (const funcInfo of functionList) {
this.funMappingStore.set(funcInfo.funcHandlerName, funcInfo);
}
}, LOCK_KEY);
}
public getFrameworkType(): MidwayFrameworkType {
return MidwayFrameworkType.FAAS;
}
public handleInvokeWrapper(handlerMapping: string) {
const funOptions: RouterInfo = this.funMappingStore.get(handlerMapping);
return async (...args) => {
if (args.length === 0) {
throw new Error('first parameter must be function context');
}
const context: FaaSContext = this.getContext(args.shift());
if (funOptions) {
let fnMiddlewere = [];
// invoke middleware, just for http
if (context.headers && context.get) {
fnMiddlewere = fnMiddlewere
.concat(this.globalMiddleware)
.concat(funOptions.controllerMiddleware);
}
fnMiddlewere = fnMiddlewere.concat(funOptions.middleware);
if (fnMiddlewere.length) {
const mw: any[] = await this.loadMiddleware(fnMiddlewere);
mw.push(async (ctx, next) => {
// invoke handler
const result = await this.invokeHandler(
funOptions,
ctx,
next,
args
);
if (result !== undefined) {
ctx.body = result;
}
return next();
});
return compose(mw)(context).then(() => {
return context.body;
});
} else {
// invoke handler
return this.invokeHandler(funOptions, context, null, args);
}
}
throw new Error(`function handler = ${handlerMapping} not found`);
};
}
public async generateMiddleware(
middlewareId: string
): Promise<FaaSMiddleware> {
const mwIns = await this.getApplicationContext().getAsync<IWebMiddleware>(
middlewareId
);
return mwIns.resolve();
}
public getContext(context) {
if (!context.env) {
context.env = this.getApplicationContext()
.getEnvironmentService()
.getCurrentEnvironment();
}
if (!context.hooks) {
context.hooks = new MidwayHooks(context, this.app);
}
if (this.isReplaceLogger || !context.logger) {
context._serverlessLogger = this.createContextLogger(context);
/**
* 由于 fc 的 logger 有 bug,FC公有云环境我们会默认替换掉,其他平台后续视情况而定
*/
Object.defineProperty(context, 'logger', {
get() {
return context._serverlessLogger;
},
});
}
this.app.createAnonymousContext(context);
return context;
}
private async invokeHandler(routerInfo: RouterInfo, context, next, args) {
if (
Array.isArray(routerInfo.requestMetadata) &&
routerInfo.requestMetadata.length
) {
await Promise.all(
routerInfo.requestMetadata.map(
async ({ index, type, propertyData }) => {
args[index] = await extractKoaLikeValue(type, propertyData)(
context,
next
);
}
)
);
}
const funModule = await context.requestContext.getAsync(
routerInfo.controllerId
);
const handlerName =
this.getFunctionHandler(context, args, funModule, routerInfo.method) ||
this.defaultHandlerMethod;
if (funModule[handlerName]) {
// invoke real method
const result = await funModule[handlerName](...args);
// implement response decorator
const routerResponseData = routerInfo.responseMetadata;
if (context.headers && routerResponseData.length) {
for (const routerRes of routerResponseData) {
switch (routerRes.type) {
case WEB_RESPONSE_HTTP_CODE:
context.status = routerRes.code;
break;
case WEB_RESPONSE_HEADER:
for (const key in routerRes?.setHeaders || {}) {
context.set(key, routerRes.setHeaders[key]);
}
break;
case WEB_RESPONSE_CONTENT_TYPE:
context.type = routerRes.contentType;
break;
case WEB_RESPONSE_REDIRECT:
context.status = routerRes.code;
context.redirect(routerRes.url);
return;
}
}
}
return result;
}
}
protected getFunctionHandler(ctx, args, target, method): string {
if (method && typeof target[method] !== 'undefined') {
return method;
}
const handlerMethod = this.defaultHandlerMethod;
if (handlerMethod && typeof target[handlerMethod] !== 'undefined') {
return handlerMethod;
}
throw new Error(
`no handler setup on ${target.name}#${
method || this.defaultHandlerMethod
}`
);
}
protected addConfiguration(
filePath: string,
fileDir?: string,
namespace?: string
) {
if (!fileDir) {
fileDir = dirname(resolve(filePath));
}
const container = this.getApplicationContext();
const cfg = container.createConfiguration();
cfg.namespace = namespace;
cfg.loadConfiguration(require(filePath), fileDir);
}
/**
* @deprecated
* use this.addConfiguration
*/
protected initConfiguration(filePath: string, fileDir?: string) {
this.addConfiguration(filePath, fileDir);
}
private registerDecorator() {
this.getApplicationContext().registerDataHandler(
PLUGIN_KEY,
(key, meta, target) => {
return target?.[REQUEST_OBJ_CTX_KEY]?.[key] || this.app[key];
}
);
this.getApplicationContext().registerDataHandler(
LOGGER_KEY,
(key, meta, target) => {
return (
target?.[REQUEST_OBJ_CTX_KEY]?.['logger'] || this.app.getLogger()
);
}
);
}
private async loadMiddleware(middlewares) {
const newMiddlewares = [];
for (const middleware of middlewares) {
if (typeof middleware === 'function') {
newMiddlewares.push(middleware);
} else {
const middlewareImpl: IMiddleware<FaaSContext> =
await this.getApplicationContext().getAsync(middleware);
if (middlewareImpl && typeof middlewareImpl.resolve === 'function') {
newMiddlewares.push(middlewareImpl.resolve() as any);
}
}
}
return newMiddlewares;
}
public createLogger(name: string, option: LoggerOptions = {}) {
// 覆盖基类的创建日志对象,函数场景下的日志,即使自定义,也只启用控制台输出
return createConsoleLogger(name, option);
}
public getFrameworkName() {
return 'midway:faas';
}
} | the_stack |
import 'chrome://resources/cr_elements/cr_expand_button/cr_expand_button.m.js';
import 'chrome://resources/cr_elements/shared_vars_css.m.js';
import 'chrome://resources/cr_elements/mwb_element_shared_style.js';
import 'chrome://resources/cr_elements/mwb_shared_style.js';
import 'chrome://resources/cr_elements/mwb_shared_vars.js';
import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js';
import 'chrome://resources/polymer/v3_0/iron-iconset-svg/iron-iconset-svg.js';
import './infinite_list.js';
import './tab_search_group_item.js';
import './tab_search_item.js';
import './tab_search_search_field.js';
import './title_item.js';
import './strings.m.js';
import {assert} from 'chrome://resources/js/assert.m.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {listenOnce} from 'chrome://resources/js/util.m.js';
import {Token} from 'chrome://resources/mojo/mojo/public/mojom/base/token.mojom-webui.js';
import {IronA11yAnnouncer} from 'chrome://resources/polymer/v3_0/iron-a11y-announcer/iron-a11y-announcer.js';
import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {fuzzySearch, FuzzySearchOptions} from './fuzzy_search.js';
import {InfiniteList, NO_SELECTION, selectorNavigationKeys} from './infinite_list.js';
import {ariaLabel, ItemData, TabData, TabGroupData, TabItemType, tokenEquals, tokenToString} from './tab_data.js';
import {ProfileData, RecentlyClosedTab, RecentlyClosedTabGroup, Tab, TabGroup, TabsRemovedInfo, TabUpdateInfo} from './tab_search.mojom-webui.js';
import {TabSearchApiProxy, TabSearchApiProxyImpl} from './tab_search_api_proxy.js';
import {TabSearchSearchField} from './tab_search_search_field.js';
import {tabHasMediaAlerts} from './tab_search_utils.js';
import {TitleItem} from './title_item.js';
// The minimum number of list items we allow viewing regardless of browser
// height. Includes a half row that hints to the user the capability to scroll.
const MINIMUM_AVAILABLE_HEIGHT_LIST_ITEM_COUNT: number = 5.5;
interface RepeaterEvent<T> extends Event {
model: {
item: T,
index: number,
};
}
interface RepeaterCustomEvent<M, P> extends CustomEvent<P> {
model: {
item: M,
index: number,
};
}
interface RepeaterKeyboardEvent<T> extends KeyboardEvent {
model: {
item: T,
index: number,
};
}
export interface TabSearchAppElement {
$: {
searchField: TabSearchSearchField,
tabsList: InfiniteList,
};
}
export class TabSearchAppElement extends PolymerElement {
static get is() {
return 'tab-search-app';
}
static get properties() {
return {
searchText_: {
type: String,
value: '',
},
availableHeight_: Number,
filteredItems_: {
type: Array,
value: [],
},
/**
* Options for fuzzy search. Controls how heavily weighted fields are
* relative to each other in the scoring via field weights.
*/
fuzzySearchOptions_: {
type: Object,
value: {
includeScore: true,
includeMatches: true,
ignoreLocation: false,
threshold: 0.0,
distance: 200,
keys: [
{
name: 'tab.title',
weight: 2,
},
{
name: 'hostname',
weight: 1,
},
{
name: 'tabGroup.title',
weight: 1.5,
},
],
},
},
moveActiveTabToBottom_: {
type: Boolean,
value: () => loadTimeData.getBoolean('moveActiveTabToBottom'),
},
recentlyClosedDefaultItemDisplayCount_: {
type: Number,
value: () =>
loadTimeData.getValue('recentlyClosedDefaultItemDisplayCount'),
},
searchResultText_: {type: String, value: ''}
};
}
private searchText_: string;
private availableHeight_: number;
filteredItems_: Array<TitleItem|TabData|TabGroupData>;
private fuzzySearchOptions_: FuzzySearchOptions<TabData|TabGroupData>;
private moveActiveTabToBottom_: boolean;
private recentlyClosedDefaultItemDisplayCount_: number;
private searchResultText_: string;
private apiProxy_: TabSearchApiProxy = TabSearchApiProxyImpl.getInstance();
private listenerIds_: Array<number> = [];
private tabGroupsMap_: Map<string, TabGroup> = new Map();
private recentlyClosedTabGroups_: Array<TabGroupData> = [];
private openTabs_: Array<TabData> = [];
private recentlyClosedTabs_: Array<TabData> = [];
private windowShownTimestamp_: number = Date.now();
private mediaTabsTitleItem_: TitleItem;
private openTabsTitleItem_: TitleItem;
private recentlyClosedTitleItem_: TitleItem;
private filteredOpenTabsCount_: number = 0;
private visibilityChangedListener_: () => void;
constructor() {
super();
this.visibilityChangedListener_ = () => {
// Refresh Tab Search's tab data when transitioning into a visible state.
if (document.visibilityState === 'visible') {
this.windowShownTimestamp_ = Date.now();
this.updateTabs_();
} else {
this.onDocumentHidden_();
}
};
this.mediaTabsTitleItem_ =
new TitleItem(loadTimeData.getString('mediaTabs'));
this.openTabsTitleItem_ = new TitleItem(loadTimeData.getString('openTabs'));
this.recentlyClosedTitleItem_ = new TitleItem(
loadTimeData.getString('recentlyClosed'), true /*expandable*/,
true /*expanded*/);
}
ready() {
super.ready();
// Update option values for fuzzy search from feature params.
this.fuzzySearchOptions_ = Object.assign({}, this.fuzzySearchOptions_, {
useFuzzySearch: loadTimeData.getBoolean('useFuzzySearch'),
ignoreLocation: loadTimeData.getBoolean('searchIgnoreLocation'),
threshold: loadTimeData.getValue('searchThreshold'),
distance: loadTimeData.getInteger('searchDistance'),
keys: [
{
name: 'tab.title',
weight: loadTimeData.getValue('searchTitleWeight'),
},
{
name: 'hostname',
weight: loadTimeData.getValue('searchHostnameWeight'),
},
{
name: 'tabGroup.title',
weight: loadTimeData.getValue('searchGroupTitleWeight'),
},
],
});
}
connectedCallback() {
super.connectedCallback();
document.addEventListener(
'visibilitychange', this.visibilityChangedListener_);
const callbackRouter = this.apiProxy_.getCallbackRouter();
this.listenerIds_.push(
callbackRouter.tabsChanged.addListener(this.tabsChanged_.bind(this)),
callbackRouter.tabUpdated.addListener(this.onTabUpdated_.bind(this)),
callbackRouter.tabsRemoved.addListener(this.onTabsRemoved_.bind(this)));
// If added in a visible state update current tabs.
if (document.visibilityState === 'visible') {
this.updateTabs_();
}
}
disconnectedCallback() {
super.disconnectedCallback();
this.listenerIds_.forEach(
id => this.apiProxy_.getCallbackRouter().removeListener(id));
document.removeEventListener(
'visibilitychange', this.visibilityChangedListener_);
}
/**
* @param name A property whose value is specified in pixels.
*/
private getStylePropertyPixelValue_(name: string): number {
const pxValue = getComputedStyle(this).getPropertyValue(name);
assert(pxValue);
return Number.parseInt(pxValue.trim().slice(0, -2), 10);
}
/**
* Calculate the list's available height by subtracting the height used by
* the search and feedback fields.
*/
private listMaxHeight_(height: number): number {
return Math.max(
height - this.$.searchField.offsetHeight,
Math.round(
MINIMUM_AVAILABLE_HEIGHT_LIST_ITEM_COUNT *
this.getStylePropertyPixelValue_('--mwb-item-height')));
}
private onDocumentHidden_() {
this.filteredItems_ = [];
this.$.searchField.setValue('');
this.$.searchField.getSearchInput().focus();
}
private updateTabs_() {
const getTabsStartTimestamp = Date.now();
this.apiProxy_.getProfileData().then(({profileData}) => {
chrome.metricsPrivate.recordTime(
'Tabs.TabSearch.WebUI.TabListDataReceived',
Math.round(Date.now() - getTabsStartTimestamp));
// The infinite-list produces viewport-filled events whenever a data or
// scroll position change triggers the the viewport fill logic.
listenOnce(this.$.tabsList, 'viewport-filled', () => {
// Push showUI() to the event loop to allow reflow to occur following
// the DOM update.
setTimeout(() => this.apiProxy_.showUI(), 0);
});
this.availableHeight_ = profileData.windows.find((t) => t.active)!.height;
this.tabsChanged_(profileData);
});
}
private onTabUpdated_(tabUpdateInfo: TabUpdateInfo) {
const {tab, inActiveWindow} = tabUpdateInfo;
const tabData = this.tabData_(
tab, inActiveWindow, TabItemType.OPEN_TAB, this.tabGroupsMap_);
// Replace the tab with the same tabId and trigger rerender.
for (let i = 0; i < this.openTabs_.length; ++i) {
if (this.openTabs_[i]!.tab.tabId === tab.tabId) {
this.openTabs_[i] = tabData;
this.updateFilteredTabs_();
return;
}
}
// If the updated tab's id is not found in the existing open tabs, add it
// to the list.
this.openTabs_.push(tabData);
this.updateFilteredTabs_();
}
private onTabsRemoved_(tabsRemovedInfo: TabsRemovedInfo) {
if (this.openTabs_.length === 0) {
return;
}
const ids = new Set(tabsRemovedInfo.tabIds);
// Splicing in descending index order to avoid affecting preceding indices
// that are to be removed.
for (let i = this.openTabs_.length - 1; i >= 0; i--) {
if (ids.has(this.openTabs_[i]!.tab.tabId)) {
this.openTabs_.splice(i, 1);
}
}
tabsRemovedInfo.recentlyClosedTabs.forEach(tab => {
this.recentlyClosedTabs_.unshift(this.tabData_(
tab, false, TabItemType.RECENTLY_CLOSED_TAB, this.tabGroupsMap_));
});
this.updateFilteredTabs_();
}
/**
* The seleted item's index, or -1 if no item selected.
*/
getSelectedIndex(): number {
return this.$.tabsList.selected;
}
private onSearchChanged_(e: CustomEvent<string>) {
this.searchText_ = e.detail;
this.updateFilteredTabs_();
// Reset the selected item whenever a search query is provided.
this.$.tabsList.selected =
this.selectableItemCount_() > 0 ? 0 : NO_SELECTION;
this.$.searchField.announce(this.getA11ySearchResultText_());
}
private getA11ySearchResultText_(): string {
// TODO(romanarora): Screen readers' list item number announcement will
// not match as it counts the title items too. Investigate how to
// programmatically control announcements to avoid this.
const itemCount = this.selectableItemCount_();
let text;
if (this.searchText_.length > 0) {
text = loadTimeData.getStringF(
itemCount == 1 ? 'a11yFoundTabFor' : 'a11yFoundTabsFor', itemCount,
this.searchText_);
} else {
text = loadTimeData.getStringF(
itemCount == 1 ? 'a11yFoundTab' : 'a11yFoundTabs', itemCount);
}
return text;
}
/**
* @return The number of selectable list items, excludes non
* selectable items such as section title items.
*/
private selectableItemCount_(): number {
return this.filteredItems_.reduce((acc, item) => {
return acc + (item instanceof TitleItem ? 0 : 1);
}, 0);
}
private onItemClick_(e: RepeaterEvent<ItemData>) {
const tabItem = e.model.item;
this.tabItemAction_(tabItem, e.model.index);
}
/**
* Trigger the click/press action associated with the given Tab item type.
*/
private tabItemAction_(itemData: ItemData, tabIndex: number) {
const state = this.searchText_ ? 'Filtered' : 'Unfiltered';
let action;
switch (itemData.type) {
case TabItemType.OPEN_TAB:
this.apiProxy_.switchToTab(
{tabId: (itemData as TabData).tab.tabId}, !!this.searchText_,
tabIndex);
action = 'SwitchTab';
break;
case TabItemType.RECENTLY_CLOSED_TAB:
this.apiProxy_.openRecentlyClosedEntry(
(itemData as TabData).tab.tabId, !!this.searchText_, true,
tabIndex - this.filteredOpenTabsCount_);
action = 'OpenRecentlyClosedEntry';
break;
case TabItemType.RECENTLY_CLOSED_TAB_GROUP:
this.apiProxy_.openRecentlyClosedEntry(
((itemData as TabGroupData).tabGroup as RecentlyClosedTabGroup)
.sessionId,
!!this.searchText_, false, tabIndex - this.filteredOpenTabsCount_);
action = 'OpenRecentlyClosedEntry';
break;
default:
throw new Error('ItemData is of invalid type.');
}
chrome.metricsPrivate.recordTime(
`Tabs.TabSearch.WebUI.TimeTo${action}In${state}List`,
Math.round(Date.now() - this.windowShownTimestamp_));
}
private onItemClose_(e: RepeaterEvent<TabData>) {
performance.mark('tab_search:close_tab:metric_begin');
const tabId = e.model.item.tab.tabId;
this.apiProxy_.closeTab(tabId, !!this.searchText_, e.model.index);
this.announceA11y_(loadTimeData.getString('a11yTabClosed'));
listenOnce(this.$.tabsList, 'iron-items-changed', () => {
performance.mark('tab_search:close_tab:metric_end');
});
}
private onItemKeyDown_(e: RepeaterKeyboardEvent<ItemData>) {
if (e.key !== 'Enter' && e.key !== ' ') {
return;
}
e.stopPropagation();
e.preventDefault();
const itemData = e.model.item;
this.tabItemAction_(itemData, e.model.index);
}
private tabsChanged_(profileData: ProfileData) {
this.tabGroupsMap_ = profileData.tabGroups.reduce((map, tabGroup) => {
map.set(tokenToString(tabGroup.id), tabGroup);
return map;
}, new Map());
this.openTabs_ = profileData.windows.reduce(
(acc, {active, tabs}) => acc.concat(tabs.map(
tab => this.tabData_(
tab, active, TabItemType.OPEN_TAB, this.tabGroupsMap_))),
[] as Array<TabData>);
this.recentlyClosedTabs_ = profileData.recentlyClosedTabs.map(
tab => this.tabData_(
tab, false, TabItemType.RECENTLY_CLOSED_TAB, this.tabGroupsMap_));
this.recentlyClosedTabGroups_ =
profileData.recentlyClosedTabGroups.map(tabGroup => {
const tabGroupData = new TabGroupData(tabGroup);
tabGroupData.a11yTypeText =
loadTimeData.getString('a11yRecentlyClosedTabGroup');
return tabGroupData;
});
this.recentlyClosedTitleItem_.expanded =
profileData.recentlyClosedSectionExpanded;
this.updateFilteredTabs_();
// If there was no previously selected index, set the first item as
// selected; else retain the currently selected index. If the list
// shrunk above the selected index, select the last index in the list.
// If there are no matching results, set the selected index value to none.
const tabsList = this.$.tabsList;
tabsList.selected = Math.min(
Math.max(this.getSelectedIndex(), 0), this.selectableItemCount_() - 1);
}
private onItemFocus_(e: RepeaterEvent<TabData|TabGroupData>) {
// Ensure that when a TabSearchItem receives focus, it becomes the selected
// item in the list.
this.$.tabsList.selected = e.model.index;
}
private onTitleExpandChanged_(
e: RepeaterCustomEvent<TitleItem, {value: boolean}>) {
// Instead of relying on two-way binding to update the `expanded` property,
// we update the value directly as the `expanded-changed` event takes place
// before a two way bound property update and we need the TitleItem
// instance to reflect the updated state prior to calling the
// updateFilteredTabs_ function.
const expanded = e.detail.value;
const titleItem = e.model.item;
titleItem.expanded = expanded;
this.apiProxy_.saveRecentlyClosedExpandedPref(expanded);
this.updateFilteredTabs_();
e.stopPropagation();
}
private onSearchFocus_() {
const tabsList = this.$.tabsList;
if (tabsList.selected === NO_SELECTION && this.selectableItemCount_() > 0) {
tabsList.selected = 0;
}
}
/**
* Handles key events when the search field has focus.
*/
private onSearchKeyDown_(e: KeyboardEvent) {
// In the event the search field has focus and the first item in the list is
// selected and we receive a Shift+Tab navigation event, ensure All DOM
// items are available so that the focus can transfer to the last item in
// the list.
if (e.shiftKey && e.key === 'Tab' && this.$.tabsList.selected === 0) {
this.$.tabsList.ensureAllDomItemsAvailable();
return;
}
// Do not interfere with the search field's management of text selection
// that relies on the Shift key.
if (e.shiftKey) {
return;
}
if (this.getSelectedIndex() === -1) {
// No tabs matching the search text criteria.
return;
}
if (selectorNavigationKeys.includes(e.key)) {
this.$.tabsList.navigate(e.key);
e.stopPropagation();
e.preventDefault();
// TODO(tluk): Fix this to use aria-activedescendant when it's updated to
// work with Shadow DOM elements.
this.$.searchField.announce(
ariaLabel(this.$.tabsList.selectedItem as ItemData));
} else if (e.key === 'Enter') {
const itemData = this.$.tabsList.selectedItem as ItemData;
this.tabItemAction_(itemData, this.getSelectedIndex());
e.stopPropagation();
}
}
announceA11y_(text: string) {
IronA11yAnnouncer.requestAvailability();
this.dispatchEvent(new CustomEvent(
'iron-announce', {bubbles: true, composed: true, detail: {text}}));
}
private ariaLabel_(tabData: TabData): string {
return ariaLabel(tabData);
}
private tabData_(
tab: Tab|RecentlyClosedTab, inActiveWindow: boolean, type: TabItemType,
tabGroupsMap: Map<string, TabGroup>): TabData {
const tabData = new TabData(tab, type, new URL(tab.url.url).hostname);
if (tab.groupId) {
tabData.tabGroup = tabGroupsMap.get(tokenToString(tab.groupId));
}
if (type === TabItemType.OPEN_TAB) {
tabData.inActiveWindow = inActiveWindow;
}
tabData.a11yTypeText = loadTimeData.getString(
type === TabItemType.OPEN_TAB ? 'a11yOpenTab' :
'a11yRecentlyClosedTab');
return tabData;
}
private getRecentlyClosedItemLastActiveTime_(itemData: ItemData) {
if (itemData.type === TabItemType.RECENTLY_CLOSED_TAB &&
itemData instanceof TabData) {
return (itemData.tab as RecentlyClosedTab).lastActiveTime;
}
if (itemData.type === TabItemType.RECENTLY_CLOSED_TAB_GROUP &&
itemData instanceof TabGroupData) {
return (itemData.tabGroup as RecentlyClosedTabGroup).lastActiveTime;
}
throw new Error('ItemData provided is invalid.');
}
private updateFilteredTabs_() {
this.openTabs_.sort((a, b) => {
const tabA = a.tab as Tab;
const tabB = b.tab as Tab;
// Move the active tab to the bottom of the list
// because it's not likely users want to click on it.
if (this.moveActiveTabToBottom_) {
if (a.inActiveWindow && tabA.active) {
return 1;
}
if (b.inActiveWindow && tabB.active) {
return -1;
}
}
return (tabB.lastActiveTimeTicks && tabA.lastActiveTimeTicks) ?
Number(
tabB.lastActiveTimeTicks.internalValue -
tabA.lastActiveTimeTicks.internalValue) :
0;
});
let mediaTabs: Array<TabData> = [];
// Audio & Video section will not be added when search criteria is applied
// if media tabs are also shown in Open Tabs section.
if (this.searchText_.length == 0 ||
!loadTimeData.getBoolean('alsoShowMediaTabsinOpenTabsSection')) {
mediaTabs = this.openTabs_.filter(
tabData => tabHasMediaAlerts(tabData.tab as Tab));
}
const filteredMediaTabs =
fuzzySearch(this.searchText_, mediaTabs, this.fuzzySearchOptions_);
let filteredOpenTabs =
fuzzySearch(this.searchText_, this.openTabs_, this.fuzzySearchOptions_);
if (!loadTimeData.getBoolean('alsoShowMediaTabsinOpenTabsSection')) {
filteredOpenTabs = filteredOpenTabs.filter(
tabData => !tabHasMediaAlerts(tabData.tab as Tab));
}
this.filteredOpenTabsCount_ =
filteredOpenTabs.length + filteredMediaTabs.length;
const recentlyClosedItems: Array<TabData|TabGroupData> =
[...this.recentlyClosedTabs_, ...this.recentlyClosedTabGroups_];
recentlyClosedItems.sort((a, b) => {
const aTime = this.getRecentlyClosedItemLastActiveTime_(a);
const bTime = this.getRecentlyClosedItemLastActiveTime_(b);
return (bTime && aTime) ?
Number(bTime.internalValue - aTime.internalValue) :
0;
});
let filteredRecentlyClosedItems = fuzzySearch(
this.searchText_, recentlyClosedItems, this.fuzzySearchOptions_);
// Limit the number of recently closed items to the default display count
// when no search text has been specified. Filter out recently closed tabs
// that belong to a recently closed tab group by default.
const recentlyClosedTabGroupIds = this.recentlyClosedTabGroups_.reduce(
(acc, tabGroupData) => acc.concat(tabGroupData.tabGroup!.id),
[] as Token[]);
if (!this.searchText_.length) {
filteredRecentlyClosedItems =
filteredRecentlyClosedItems
.filter(recentlyClosedItem => {
if (recentlyClosedItem instanceof TabGroupData) {
return true;
}
const recentlyClosedTab =
(recentlyClosedItem as TabData).tab as RecentlyClosedTab;
return (
!recentlyClosedTab.groupId ||
!recentlyClosedTabGroupIds.some(
groupId =>
tokenEquals(groupId, recentlyClosedTab.groupId!)));
})
.slice(0, this.recentlyClosedDefaultItemDisplayCount_);
}
this.filteredItems_ =
([
[this.mediaTabsTitleItem_, filteredMediaTabs],
[this.openTabsTitleItem_, filteredOpenTabs],
[this.recentlyClosedTitleItem_, filteredRecentlyClosedItems],
] as Array<[TitleItem, Array<TabData|TabGroupData>]>)
.reduce((acc, [sectionTitle, sectionItems]) => {
if (sectionItems!.length !== 0) {
acc.push(sectionTitle);
if (!sectionTitle.expandable ||
sectionTitle.expandable && sectionTitle.expanded) {
acc.push(...sectionItems);
}
}
return acc;
}, [] as Array<TitleItem|TabData|TabGroupData>);
this.searchResultText_ = this.getA11ySearchResultText_();
}
getSearchTextForTesting(): string {
return this.searchText_;
}
static get template() {
return html`{__html_template__}`;
}
}
declare global {
interface HTMLElementTagNameMap {
'tab-search-app': TabSearchAppElement;
}
}
customElements.define(TabSearchAppElement.is, TabSearchAppElement); | the_stack |
import { UndoHistoryState } from 'redux-undo-redo';
import { DiagramMakerComponentsType } from 'diagramMaker/service/ui/types';
import { DiagramMakerAction } from 'diagramMaker/state/actions';
export interface Position {
x: number;
y: number;
}
export interface Size {
width: number;
height: number;
}
export enum EditorModeType {
/**
* Allows the workspace to be dragged to pan the visible area across the window.
*/
DRAG = 'Drag',
/**
* Prevents UI interactions other than panning and zooming the workspace.
*/
READ_ONLY = 'ReadOnly',
/**
* Allows selection of multiple nodes with a rectangular marquee.
*/
SELECT = 'Select'
}
export const EditorMode = {
...EditorModeType
};
export interface Rectangle {
position: Position;
size: Size;
}
export type ShowConnectorsType = 'Input' | 'Output' | 'Both' | 'None';
export const ShowConnectors: { [type: string]: ShowConnectorsType } = {
BOTH: 'Both',
INPUT_ONLY: 'Input',
NONE: 'None',
OUTPUT_ONLY: 'Output'
};
/** Interface for storing the state of the diagram maker workspace */
export interface DiagramMakerWorkspace {
/**
* Denotes the pixel values that the workspace has been translated by on x & y axis
*/
readonly position: Position;
/**
* Denotes the scale of the workspace, where 1 denotes natural scale.
* Smaller than 1 denotes that the workspace has been zoomed out.
* Greater than 1 denotes that the workspace has been zoomed in.
*/
readonly scale: number;
/**
* Denotes the size of the workspace that the customer can move nodes around in.
* Every object within the workspace, i.e. nodes, edges, potential nodes stays within these bounds.
*/
readonly canvasSize: Size;
/**
* Denotes the size of the container diagram maker is rendered in.
* To update due to window resizing, or panels outside diagram maker shifting content,
* call the `updateContainer` API.
*/
readonly viewContainerSize: Size;
}
export enum PositionAnchorType {
/** Top Left edge of the container that diagram maker renders in */
TOP_LEFT = 'TopLeft',
/** Top Right edge of the container that diagram maker renders in */
TOP_RIGHT = 'TopRight',
/** Bottom Left edge of the container that diagram maker renders in */
BOTTOM_LEFT = 'BottomLeft',
/** Bottom Right edge of the container that diagram maker renders in */
BOTTOM_RIGHT = 'BottomRight'
}
export const PositionAnchor = {
...PositionAnchorType
};
/**
* Interface for storing the state of a given diagram maker node.
* @template NodeType - The type of data stored per node by the consumer.
*/
export interface DiagramMakerNode<NodeType> {
/**
* Unique identifier for the node.
* Autogenerated for nodes newly created.
* Supplied for nodes already present when diagram maker initializes.
* In the case it is supplied, please ensure that this is unique.
*/
readonly id: string;
/**
* Type of the node. Optional.
* References to the id present on the potential node when it was dragged in.
* Also useful to specify override connector placements, hiding specific connectors
* or providing the shape for boundary connector placements.
*/
readonly typeId?: string;
/**
* Contains node data managed by diagram maker.
*/
readonly diagramMakerData: {
/**
* Current position of the node w.r.t the workspace
*/
readonly position: Position;
/**
* Current size of the node
*/
readonly size: Size;
/**
* Denotes whether the node is currently selected.
*/
readonly selected?: boolean;
/**
* Denotes whether the node is currently being dragged.
*/
readonly dragging?: boolean;
};
/** Contains data managed by the consumer */
readonly consumerData?: NodeType;
}
/**
* Interface for storing state of several diagram maker nodes.
* @template NodeType - The type of data stored per node by the consumer.
*/
export interface DiagramMakerNodes<NodeType> {
readonly [id: string]: DiagramMakerNode<NodeType>;
}
/** Interface for storing state of diagram maker potential node i.e. a new node being dragged onto the workspace */
export interface DiagramMakerPotentialNode {
/** Type of the node. Mandatory for providing context during node creation */
readonly typeId: string;
/** Current position of the potential node w.r.t the workspace */
readonly position: Position;
/** Size of the potential node as detected via tha data attrs on the drag target or via the type config */
readonly size: Size;
}
/**
* Interface for storing state of a given diagram maker edge.
* @template EdgeType - The type of data stored per edge by the consumer
*/
export interface DiagramMakerEdge<EdgeType> {
/**
* Unique identifier for the edge.
* Autogenerated for edges newly created.
* Supplied for edges already present when diagram maker initializes.
* In the case it is supplied, please ensure that this is unique.
*/
readonly id: string;
/**
* References the id for the node where this edge originates.
* Leads to inconsistencies if this refers to a node that doesnt exist.
*/
readonly src: string;
/**
* References the id for the node where this edge ends.
* Leads to inconsistencies if this refers to a node that doesnt exist.
*/
readonly dest: string;
/** Contains edge data managed by diagram maker */
readonly diagramMakerData: {
/** Denotes whether the edge is selected */
readonly selected?: boolean;
};
/** Contains data managed by the consumer */
readonly consumerData?: EdgeType;
}
/**
* Interface for storing state of several diagram maker edges.
* @template EdgeType - The type of data stored per edge by the consumer
*/
export interface DiagramMakerEdges<EdgeType> {
readonly [id: string]: DiagramMakerEdge<EdgeType>;
}
/** Interface for storing state of diagram maker potential edge i.e. a new edge being drawn on the workspace */
export interface DiagramMakerPotentialEdge {
/**
* References the id for the node where this edge originates.
* Leads to inconsistencies if this refers to a node that doesnt exist.
*/
readonly src: string;
/**
* Current position where the potential edge is pointing.
* Usually refers to the cursor position relative to the workspace scale & position.
*/
readonly position: Position;
}
/** Interface for storing state of a diagram maker panel */
export interface DiagramMakerPanel {
/**
* Unique identifier for the panel.
* Provided by the consumer.
* Used for referencing the render callback.
*/
readonly id: string;
/**
* Current position of the panel in the view container.
* Please note that panels remain outside the workspace
* so are not affected by its scale & panning.
*/
readonly position: Position;
/**
* Current size for the panel.
* Used for providing a container to render the panel content in.
*/
readonly size: Size;
/**
* Position Anchor. Optional. Used for docking panels.
* When not specified, panels are assumed to be relative to Top Left corner of view container.
* When specified, position is assumed to be relative to the anchor.
*/
readonly positionAnchor?: PositionAnchorType;
/**
* Denoted whether the panel is in undocking mode.
* Panel is in undocking mode when it was previously docked,
* is currently being dragged and is within the docking bounds.
*/
readonly undocking?: boolean;
}
/** Interface for storing state for several diagram maker panels */
export interface DiagramMakerPanels {
readonly [id: string]: DiagramMakerPanel;
}
/** Interface for storing state for a diagram maker plugin */
export interface DiagramMakerPlugin {
readonly data: any;
}
/** Interface for storing state for several diagram maker plugins */
export interface DiagramMakerPlugins {
readonly [id: string]: DiagramMakerPlugin;
}
/** Interface for storing state for diagram maker context menu */
export interface DiagramMakerContextMenu {
/**
* Current position of the context menu in the view container.
* Please note context menus are not part of the workspace
* so not affected by its scale & panning.
*/
readonly position: Position;
/**
* Type of the object that the context menu is being displayed for.
* For example, node, edge, panel, workspace, etc.
*/
readonly targetType: DiagramMakerComponentsType;
/**
* Unique identifier to identify the specific node or edge or panel.
* Absent for the workspace.
*/
readonly targetId?: string;
}
/** Interface for storing state for diagram maker selection marquee */
export interface DiagramMakerSelectionMarquee {
/**
* Position where the user clicked to start the selection.
* This remains one of the 4 corners of the selections marquee
*/
readonly anchor: Position;
/**
* Current position of the cursor.
*/
readonly position: Position;
}
/** Interface for storing state for diagram maker editor */
export interface DiagramMakerEditor {
/**
* Current context menu state if one needs to be rendered currently.
*/
readonly contextMenu?: DiagramMakerContextMenu;
/**
* Current mode of the editor.
*/
readonly mode: EditorModeType;
/**
* Current selection marquee state if one needs to be rendered currently.
*/
readonly selectionMarquee?: DiagramMakerSelectionMarquee;
}
export interface DiagramMakerData<NodeType, EdgeType> {
/** Current state for all nodes */
readonly nodes: DiagramMakerNodes<NodeType>;
/** Current state for all edges */
readonly edges: DiagramMakerEdges<EdgeType>;
/** Current state for all panels */
readonly panels: DiagramMakerPanels;
/** Current state for all plugins */
readonly plugins?: DiagramMakerPlugins;
/** Current state for diagram maker workspace */
readonly workspace: DiagramMakerWorkspace;
/** Current state for diagram maker potential node if one needs to be rendered currently */
readonly potentialEdge?: DiagramMakerPotentialEdge | null;
/** Current state for diagram maker potential edge if one needs to be rendered currently */
readonly potentialNode?: DiagramMakerPotentialNode | null;
/** Current state for diagram maker editor */
readonly editor: DiagramMakerEditor;
/** History of undoable actions */
readonly undoHistory?: UndoHistoryState<DiagramMakerAction<NodeType, EdgeType>>;
} | the_stack |
import path from 'path';
import gulp from 'gulp';
import gulpAdd from 'gulp-add';
import chmod from 'gulp-chmod';
import merge from 'lodash/merge';
import { ModuleFormat, RollupOptions } from 'rollup';
import gulpHbsRuntime from '../plugins/gulp-hbs-runtime';
import { PackageConfig } from '../model/package-config';
import logger from '../common/logger';
import { meta } from './meta';
import {
getScriptBuildPlugin,
generateBundle,
customRollupPlugins,
getExternalFilter,
extractBundleExternals,
generateMinStyleSheet,
getBanner,
getBaseConfig,
getPostBundlePlugins,
getPreBundlePlugins,
getDependencyResolvePlugins,
getStyleBuildPlugins
} from './build-util';
import { args, requireDependency } from './util';
import * as TS from 'typescript';
/**
* Initialize build associated gulp tasks.
*/
export default function init() {
/**
* Copy build essentials gulp task.
* This task will copy dynamically generated package.json file and packer config specified copy globs.
*/
gulp.task('build:copy:essentials', () => {
const log = logger.create('[build:copy:essentials]');
try {
log.trace('start');
const packageJson = meta.readPackageData();
const config = meta.readPackerConfig(log);
const targetPackage: PackageConfig = {};
// only copy needed properties from project's package json
config.compiler.packageFieldsToCopy.forEach((field: string) => {
targetPackage[field] = packageJson[field];
});
if (config.compiler.buildMode === 'node-cli') {
targetPackage.bin = packageJson.bin;
}
if (config.compiler.build.bundleMin) {
targetPackage.main = path.join('bundle', `${packageJson.name}.${config.bundle.format}.min.js`);
} else {
targetPackage.main = path.join('bundle', `${packageJson.name}.${config.bundle.format}.js`);
}
if (config.compiler.script.preprocessor === 'typescript') {
targetPackage.typings = config.compiler.script.tsd
? path.join(config.compiler.script.tsd, 'index.d.ts')
: 'index.d.ts';
}
if (config.compiler.build.es5Min) {
const esm5MinPath = path.join('fesm5', `${packageJson.name}.esm.min.js`);
targetPackage.module = esm5MinPath;
targetPackage.fesm5 = esm5MinPath;
} else if (config.compiler.build.es5) {
const fesm5Path = path.join('fesm5', `${packageJson.name}.esm.js`);
targetPackage.module = fesm5Path;
targetPackage.fesm5 = fesm5Path;
}
if (config.compiler.build.esnextMin) {
const esmNextMinPath = path.join('fesmnext', `${packageJson.name}.esm.min.js`);
targetPackage.esnext = esmNextMinPath;
targetPackage.fesmnext = esmNextMinPath;
targetPackage['jsnext:main'] = esmNextMinPath;
} else if (config.compiler.build.esnext) {
const esmNextPath = path.join('fesmnext', `${packageJson.name}.esm.js`);
targetPackage.esnext = esmNextPath;
targetPackage.fesmnext = esmNextPath;
targetPackage['jsnext:main'] = esmNextPath;
}
// Map dependencies to target package file
switch (config.compiler.dependencyMapMode) {
case 'cross-map-peer-dependency':
targetPackage.peerDependencies = packageJson.dependencies;
break;
case 'cross-map-dependency':
targetPackage.dependencies = packageJson.peerDependencies;
break;
case 'map-dependency':
targetPackage.dependencies = packageJson.dependencies;
break;
case 'map-peer-dependency':
targetPackage.peerDependencies = packageJson.peerDependencies;
break;
case 'all':
targetPackage.peerDependencies = packageJson.peerDependencies;
targetPackage.dependencies = packageJson.dependencies;
break;
}
// copy the needed additional files in the 'dist' folder
if (config.copy.length > 0) {
log.trace('copy static files and package.json');
return gulp
.src(
config.copy.map((copyFile: string) => {
return path.join(process.cwd(), copyFile);
}),
{
base: process.cwd()
}
)
.on('error', (e) => {
log.error('copy source missing: %s\n', e.stack || e.message);
process.exit(1);
})
.pipe(gulpAdd('package.json', JSON.stringify(targetPackage, null, 2)))
.pipe(gulp.dest(path.join(process.cwd(), config.dist)))
.on('finish', () => {
log.trace('end');
});
} else {
log.trace('copy package.json');
return gulpAdd('package.json', JSON.stringify(targetPackage, null, 2))
.pipe(gulp.dest(path.join(process.cwd(), config.dist)))
.on('finish', () => {
log.trace('end');
});
}
} catch (e) {
log.error('task failure: %s\n', e.stack || e.message);
process.exit(1);
}
});
/**
* Copy bin artifacts gulp task.
* This task will copy bin artifact only when build mode is node-cli
*/
gulp.task('build:copy:bin', () => {
const log = logger.create('[build:copy:bin]');
try {
log.trace('start');
const packageJson = meta.readPackageData();
const config = meta.readPackerConfig(log);
if (config.compiler.buildMode !== 'node-cli') {
log.trace('not a cli project: bin copy abort');
log.trace('start');
return;
}
return gulp
.src([path.join(process.cwd(), '.packer/bin.hbs')])
.on('error', (e) => {
log.error('bin source missing: %s\n', e.stack || e.message);
process.exit(1);
})
.pipe(
gulpHbsRuntime(
{
packageName: packageJson.name,
format: config.bundle.format
},
{
rename: `${packageJson.name}.js`
}
)
)
.pipe(
chmod({
group: {
execute: true,
read: true
},
others: {
execute: true,
read: true
},
owner: {
execute: true,
read: true,
write: true
}
})
) // Grant read and execute permission.
.pipe(gulp.dest(path.join(process.cwd(), config.dist, 'bin')))
.on('finish', () => {
log.trace('end');
});
} catch (e) {
log.error('task failure: %s\n', e.stack || e.message);
process.exit(1);
}
});
/**
* Copy build artifacts gulp task.
* Run copy essentials and bin on parallel mode.
*/
gulp.task('build:copy', gulp.parallel('build:copy:essentials', 'build:copy:bin'));
/**
* Build distribution bundles gulp task.
* This task contains the core logic to build scripts and styles via rollup.
*/
gulp.task('build:bundle', async () => {
const log = logger.create('[build:bundle]');
try {
log.trace(' start');
const packerConfig = meta.readPackerConfig(log);
const packageConfig = meta.readPackageData();
const babelConfig = meta.readBabelConfig();
const banner = await getBanner(packerConfig, packageConfig);
const baseConfig = getBaseConfig(packerConfig, packageConfig, banner);
const externals = extractBundleExternals(packerConfig);
const buildTasks: Array<Promise<void>> = [];
const bundleFileName = `${packageConfig.name}.${packerConfig.bundle.format}.js`;
const trackBuildPerformance = args.includes('--perf') || args.includes('-P');
let typescript: typeof TS = null;
if (packerConfig.compiler.script.preprocessor === 'typescript') {
typescript = requireDependency<typeof TS>('typescript', log);
}
// flat bundle.
const flatConfig: RollupOptions = merge({}, baseConfig, {
external: externals,
output: {
amd: packerConfig.bundle.amd,
file: path.join(process.cwd(), packerConfig.dist, 'bundle', bundleFileName),
format: packerConfig.bundle.format,
globals: packerConfig.bundle.globals,
name: packerConfig.bundle.namespace
},
perf: trackBuildPerformance,
plugins: [
...getStyleBuildPlugins(packerConfig, packageConfig, false, true, log),
...getPreBundlePlugins(packerConfig),
...getDependencyResolvePlugins(packerConfig),
...getScriptBuildPlugin('bundle', true, true, packerConfig, babelConfig, typescript, log),
...getPostBundlePlugins(packerConfig, '[build:bundle]', 'bundle'),
...customRollupPlugins(packerConfig, 'bundle')
]
});
log.trace('flat bundle rollup config:\n%o', flatConfig);
buildTasks.push(
generateBundle(
packerConfig,
packageConfig,
flatConfig,
'bundle',
packerConfig.compiler.build.bundleMin,
trackBuildPerformance,
log
)
);
if (packerConfig.compiler.build.es5) {
// FESM+ES5 flat module bundle.
const es5config: RollupOptions = merge({}, baseConfig, {
external: getExternalFilter(packerConfig),
output: {
file: path.join(process.cwd(), packerConfig.dist, 'fesm5', `${packageConfig.name}.esm.js`),
format: 'esm' as ModuleFormat
},
perf: trackBuildPerformance,
plugins: [
...getStyleBuildPlugins(packerConfig, packageConfig, false, false, log),
...getPreBundlePlugins(packerConfig),
...getDependencyResolvePlugins(packerConfig),
...getScriptBuildPlugin('es5', false, true, packerConfig, babelConfig, typescript, log),
...getPostBundlePlugins(packerConfig, '[build:bundle]', 'es5'),
...customRollupPlugins(packerConfig, 'es5')
]
});
log.trace('es5 bundle rollup config:\n%o', es5config);
buildTasks.push(
generateBundle(
packerConfig,
packageConfig,
es5config,
'es5',
packerConfig.compiler.build.es5Min,
trackBuildPerformance,
log
)
);
}
if (packerConfig.compiler.build.esnext) {
// FESM+ESNEXT flat module bundle.
const esnextConfig: RollupOptions = merge({}, baseConfig, {
external: getExternalFilter(packerConfig),
output: {
file: path.join(process.cwd(), packerConfig.dist, 'fesmnext', `${packageConfig.name}.esm.js`),
format: 'esm' as ModuleFormat
},
perf: trackBuildPerformance,
plugins: [
...getStyleBuildPlugins(packerConfig, packageConfig, false, false, log),
...getPreBundlePlugins(packerConfig),
...getDependencyResolvePlugins(packerConfig),
...getScriptBuildPlugin('esnext', false, true, packerConfig, babelConfig, typescript, log),
...getPostBundlePlugins(packerConfig, '[build:bundle]', 'esnext'),
...customRollupPlugins(packerConfig, 'esnext')
]
});
log.trace('esnext bundle rollup config:\n%o', esnextConfig);
buildTasks.push(
generateBundle(
packerConfig,
packageConfig,
esnextConfig,
'esnext',
packerConfig.compiler.build.esnextMin,
trackBuildPerformance,
log
)
);
}
if (packerConfig.compiler.concurrentBuild) {
await Promise.all(buildTasks);
} else {
for (const task of buildTasks) {
await task;
}
}
await generateMinStyleSheet(packerConfig, packageConfig, log);
log.trace('end');
} catch (e) {
log.error('task failure:\n%s', e.stack || e.message);
process.exit(1);
}
});
/**
* Library build gulp task.
* Clean distribution directory and run build copy and bundle tasks on parallel mode.
*/
gulp.task('build', gulp.series('build:clean', gulp.parallel('build:copy', 'build:bundle')));
} | the_stack |
import * as React from "react";
import classNames from "classnames";
import Modal from "../Modal";
import { _t, _td } from "../languageHandler";
import { isMac, Key } from "../Keyboard";
import InfoDialog from "../components/views/dialogs/InfoDialog";
// TS: once languageHandler is TS we can probably inline this into the enum
_td("Navigation");
_td("Calls");
_td("Composer");
_td("Room List");
_td("Autocomplete");
export enum Categories {
NAVIGATION = "Navigation",
CALLS = "Calls",
COMPOSER = "Composer",
ROOM_LIST = "Room List",
ROOM = "Room",
AUTOCOMPLETE = "Autocomplete",
}
// TS: once languageHandler is TS we can probably inline this into the enum
_td("Alt");
_td("Alt Gr");
_td("Shift");
_td("Super");
_td("Ctrl");
export enum Modifiers {
ALT = "Alt", // Option on Mac and displayed as an Icon
ALT_GR = "Alt Gr",
SHIFT = "Shift",
SUPER = "Super", // should this be "Windows"?
// Instead of using below, consider CMD_OR_CTRL
COMMAND = "Command", // This gets displayed as an Icon
CONTROL = "Ctrl",
}
// Meta-modifier: isMac ? CMD : CONTROL
export const CMD_OR_CTRL = isMac ? Modifiers.COMMAND : Modifiers.CONTROL;
// Meta-key representing the digits [0-9] often found at the top of standard keyboard layouts
export const DIGITS = "digits";
interface IKeybind {
modifiers?: Modifiers[];
key: string; // TS: fix this once Key is an enum
}
interface IShortcut {
keybinds: IKeybind[];
description: string;
}
const shortcuts: Record<Categories, IShortcut[]> = {
[Categories.COMPOSER]: [
{
keybinds: [{
modifiers: [CMD_OR_CTRL],
key: Key.B,
}],
description: _td("Toggle Bold"),
}, {
keybinds: [{
modifiers: [CMD_OR_CTRL],
key: Key.I,
}],
description: _td("Toggle Italics"),
}, {
keybinds: [{
modifiers: [CMD_OR_CTRL],
key: Key.GREATER_THAN,
}],
description: _td("Toggle Quote"),
}, {
keybinds: [{
modifiers: [Modifiers.SHIFT],
key: Key.ENTER,
}],
description: _td("New line"),
}, {
keybinds: [{
key: Key.ARROW_UP,
}, {
key: Key.ARROW_DOWN,
}],
description: _td("Navigate recent messages to edit"),
}, {
keybinds: [{
modifiers: [CMD_OR_CTRL],
key: Key.HOME,
}, {
modifiers: [CMD_OR_CTRL],
key: Key.END,
}],
description: _td("Jump to start/end of the composer"),
}, {
keybinds: [{
modifiers: [Modifiers.CONTROL, Modifiers.ALT],
key: Key.ARROW_UP,
}, {
modifiers: [Modifiers.CONTROL, Modifiers.ALT],
key: Key.ARROW_DOWN,
}],
description: _td("Navigate composer history"),
}, {
keybinds: [{
key: Key.ESCAPE,
}],
description: _td("Cancel replying to a message"),
},
],
[Categories.CALLS]: [
{
keybinds: [{
modifiers: [CMD_OR_CTRL],
key: Key.D,
}],
description: _td("Toggle microphone mute"),
}, {
keybinds: [{
modifiers: [CMD_OR_CTRL],
key: Key.E,
}],
description: _td("Toggle video on/off"),
},
],
[Categories.ROOM]: [
{
keybinds: [{
key: Key.PAGE_UP,
}, {
key: Key.PAGE_DOWN,
}],
description: _td("Scroll up/down in the timeline"),
}, {
keybinds: [{
key: Key.ESCAPE,
}],
description: _td("Dismiss read marker and jump to bottom"),
}, {
keybinds: [{
modifiers: [Modifiers.SHIFT],
key: Key.PAGE_UP,
}],
description: _td("Jump to oldest unread message"),
}, {
keybinds: [{
modifiers: [CMD_OR_CTRL, Modifiers.SHIFT],
key: Key.U,
}],
description: _td("Upload a file"),
}, {
keybinds: [{
modifiers: [CMD_OR_CTRL],
key: Key.F,
}],
description: _td("Search (must be enabled)"),
},
],
[Categories.ROOM_LIST]: [
{
keybinds: [{
modifiers: [CMD_OR_CTRL],
key: Key.K,
}],
description: _td("Jump to room search"),
}, {
keybinds: [{
key: Key.ARROW_UP,
}, {
key: Key.ARROW_DOWN,
}],
description: _td("Navigate up/down in the room list"),
}, {
keybinds: [{
key: Key.ENTER,
}],
description: _td("Select room from the room list"),
}, {
keybinds: [{
key: Key.ARROW_LEFT,
}],
description: _td("Collapse room list section"),
}, {
keybinds: [{
key: Key.ARROW_RIGHT,
}],
description: _td("Expand room list section"),
}, {
keybinds: [{
key: Key.ESCAPE,
}],
description: _td("Clear room list filter field"),
},
],
[Categories.NAVIGATION]: [
{
keybinds: [{
modifiers: [Modifiers.ALT, Modifiers.SHIFT],
key: Key.ARROW_UP,
}, {
modifiers: [Modifiers.ALT, Modifiers.SHIFT],
key: Key.ARROW_DOWN,
}],
description: _td("Previous/next unread room or DM"),
}, {
keybinds: [{
modifiers: [Modifiers.ALT],
key: Key.ARROW_UP,
}, {
modifiers: [Modifiers.ALT],
key: Key.ARROW_DOWN,
}],
description: _td("Previous/next room or DM"),
}, {
keybinds: [{
modifiers: [CMD_OR_CTRL],
key: Key.BACKTICK,
}],
description: _td("Toggle the top left menu"),
}, {
keybinds: [{
key: Key.ESCAPE,
}],
description: _td("Close dialog or context menu"),
}, {
keybinds: [{
key: Key.ENTER,
}, {
key: Key.SPACE,
}],
description: _td("Activate selected button"),
}, {
keybinds: [{
modifiers: [CMD_OR_CTRL, Modifiers.SHIFT],
key: Key.D,
}],
description: _td("Toggle space panel"),
}, {
keybinds: [{
modifiers: [CMD_OR_CTRL],
key: Key.PERIOD,
}],
description: _td("Toggle right panel"),
}, {
keybinds: [{
modifiers: [CMD_OR_CTRL],
key: Key.SLASH,
}],
description: _td("Toggle this dialog"),
}, {
keybinds: [{
modifiers: [Modifiers.CONTROL, isMac ? Modifiers.SHIFT : Modifiers.ALT],
key: Key.H,
}],
description: _td("Go to Home View"),
},
],
[Categories.AUTOCOMPLETE]: [
{
keybinds: [{
key: Key.ARROW_UP,
}, {
key: Key.ARROW_DOWN,
}],
description: _td("Move autocomplete selection up/down"),
}, {
keybinds: [{
key: Key.ESCAPE,
}],
description: _td("Cancel autocomplete"),
},
],
};
const categoryOrder = [
Categories.COMPOSER,
Categories.AUTOCOMPLETE,
Categories.ROOM,
Categories.ROOM_LIST,
Categories.NAVIGATION,
Categories.CALLS,
];
interface IModal {
close: () => void;
finished: Promise<any[]>;
}
const modifierIcon: Record<string, string> = {
[Modifiers.COMMAND]: "⌘",
};
if (isMac) {
modifierIcon[Modifiers.ALT] = "⌥";
}
const alternateKeyName: Record<string, string> = {
[Key.PAGE_UP]: _td("Page Up"),
[Key.PAGE_DOWN]: _td("Page Down"),
[Key.ESCAPE]: _td("Esc"),
[Key.ENTER]: _td("Enter"),
[Key.SPACE]: _td("Space"),
[Key.HOME]: _td("Home"),
[Key.END]: _td("End"),
[DIGITS]: _td("[number]"),
};
const keyIcon: Record<string, string> = {
[Key.ARROW_UP]: "↑",
[Key.ARROW_DOWN]: "↓",
[Key.ARROW_LEFT]: "←",
[Key.ARROW_RIGHT]: "→",
};
const Shortcut: React.FC<{
shortcut: IShortcut;
}> = ({ shortcut }) => {
const classes = classNames({
"mx_KeyboardShortcutsDialog_inline": shortcut.keybinds.every(k => !k.modifiers || k.modifiers.length === 0),
});
return <div className={classes}>
<h5>{ _t(shortcut.description) }</h5>
{ shortcut.keybinds.map(s => {
let text = s.key;
if (alternateKeyName[s.key]) {
text = _t(alternateKeyName[s.key]);
} else if (keyIcon[s.key]) {
text = keyIcon[s.key];
}
return <div key={s.key}>
{ s.modifiers?.map(m => {
return <React.Fragment key={m}>
<kbd>{ modifierIcon[m] || _t(m) }</kbd>+
</React.Fragment>;
}) }
<kbd>{ text }</kbd>
</div>;
}) }
</div>;
};
let activeModal: IModal = null;
export const toggleDialog = () => {
if (activeModal) {
activeModal.close();
activeModal = null;
return;
}
const sections = categoryOrder.map(category => {
const list = shortcuts[category];
return <div className="mx_KeyboardShortcutsDialog_category" key={category}>
<h3>{ _t(category) }</h3>
<div>{ list.map(shortcut => <Shortcut key={shortcut.description} shortcut={shortcut} />) }</div>
</div>;
});
activeModal = Modal.createTrackedDialog("Keyboard Shortcuts", "", InfoDialog, {
className: "mx_KeyboardShortcutsDialog",
title: _t("Keyboard Shortcuts"),
description: sections,
hasCloseButton: true,
onKeyDown: (ev) => {
if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey && ev.key === Key.SLASH) { // Ctrl + /
ev.stopPropagation();
activeModal.close();
}
},
onFinished: () => {
activeModal = null;
},
});
};
export const registerShortcut = (category: Categories, defn: IShortcut) => {
shortcuts[category].push(defn);
}; | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as Models from "../models";
import * as Mappers from "../models/communicationsMappers";
import * as Parameters from "../models/parameters";
import { MicrosoftSupportContext } from "../microsoftSupportContext";
/** Class representing a Communications. */
export class Communications {
private readonly client: MicrosoftSupportContext;
/**
* Create a Communications.
* @param {MicrosoftSupportContext} client Reference to the service client.
*/
constructor(client: MicrosoftSupportContext) {
this.client = client;
}
/**
* Check the availability of a resource name. This API should be used to check the uniqueness of
* the name for adding a new communication to the support ticket.
* @param supportTicketName Support ticket name.
* @param checkNameAvailabilityInput Input to check.
* @param [options] The optional parameters
* @returns Promise<Models.CommunicationsCheckNameAvailabilityResponse>
*/
checkNameAvailability(supportTicketName: string, checkNameAvailabilityInput: Models.CheckNameAvailabilityInput, options?: msRest.RequestOptionsBase): Promise<Models.CommunicationsCheckNameAvailabilityResponse>;
/**
* @param supportTicketName Support ticket name.
* @param checkNameAvailabilityInput Input to check.
* @param callback The callback
*/
checkNameAvailability(supportTicketName: string, checkNameAvailabilityInput: Models.CheckNameAvailabilityInput, callback: msRest.ServiceCallback<Models.CheckNameAvailabilityOutput>): void;
/**
* @param supportTicketName Support ticket name.
* @param checkNameAvailabilityInput Input to check.
* @param options The optional parameters
* @param callback The callback
*/
checkNameAvailability(supportTicketName: string, checkNameAvailabilityInput: Models.CheckNameAvailabilityInput, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.CheckNameAvailabilityOutput>): void;
checkNameAvailability(supportTicketName: string, checkNameAvailabilityInput: Models.CheckNameAvailabilityInput, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CheckNameAvailabilityOutput>, callback?: msRest.ServiceCallback<Models.CheckNameAvailabilityOutput>): Promise<Models.CommunicationsCheckNameAvailabilityResponse> {
return this.client.sendOperationRequest(
{
supportTicketName,
checkNameAvailabilityInput,
options
},
checkNameAvailabilityOperationSpec,
callback) as Promise<Models.CommunicationsCheckNameAvailabilityResponse>;
}
/**
* Lists all communications (attachments not included) for a support ticket. <br/></br> You can
* also filter support ticket communications by _CreatedDate_ or _CommunicationType_ using the
* $filter parameter. The only type of communication supported today is _Web_. Output will be a
* paged result with _nextLink_, using which you can retrieve the next set of Communication
* results. <br/><br/>Support ticket data is available for 12 months after ticket creation. If a
* ticket was created more than 12 months ago, a request for data might cause an error.
* @param supportTicketName Support ticket name.
* @param [options] The optional parameters
* @returns Promise<Models.CommunicationsListResponse>
*/
list(supportTicketName: string, options?: Models.CommunicationsListOptionalParams): Promise<Models.CommunicationsListResponse>;
/**
* @param supportTicketName Support ticket name.
* @param callback The callback
*/
list(supportTicketName: string, callback: msRest.ServiceCallback<Models.CommunicationsListResult>): void;
/**
* @param supportTicketName Support ticket name.
* @param options The optional parameters
* @param callback The callback
*/
list(supportTicketName: string, options: Models.CommunicationsListOptionalParams, callback: msRest.ServiceCallback<Models.CommunicationsListResult>): void;
list(supportTicketName: string, options?: Models.CommunicationsListOptionalParams | msRest.ServiceCallback<Models.CommunicationsListResult>, callback?: msRest.ServiceCallback<Models.CommunicationsListResult>): Promise<Models.CommunicationsListResponse> {
return this.client.sendOperationRequest(
{
supportTicketName,
options
},
listOperationSpec,
callback) as Promise<Models.CommunicationsListResponse>;
}
/**
* Returns communication details for a support ticket.
* @param supportTicketName Support ticket name.
* @param communicationName Communication name.
* @param [options] The optional parameters
* @returns Promise<Models.CommunicationsGetResponse>
*/
get(supportTicketName: string, communicationName: string, options?: msRest.RequestOptionsBase): Promise<Models.CommunicationsGetResponse>;
/**
* @param supportTicketName Support ticket name.
* @param communicationName Communication name.
* @param callback The callback
*/
get(supportTicketName: string, communicationName: string, callback: msRest.ServiceCallback<Models.CommunicationDetails>): void;
/**
* @param supportTicketName Support ticket name.
* @param communicationName Communication name.
* @param options The optional parameters
* @param callback The callback
*/
get(supportTicketName: string, communicationName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.CommunicationDetails>): void;
get(supportTicketName: string, communicationName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CommunicationDetails>, callback?: msRest.ServiceCallback<Models.CommunicationDetails>): Promise<Models.CommunicationsGetResponse> {
return this.client.sendOperationRequest(
{
supportTicketName,
communicationName,
options
},
getOperationSpec,
callback) as Promise<Models.CommunicationsGetResponse>;
}
/**
* Adds a new customer communication to an Azure support ticket.
* @param supportTicketName Support ticket name.
* @param communicationName Communication name.
* @param createCommunicationParameters Communication object.
* @param [options] The optional parameters
* @returns Promise<Models.CommunicationsCreateResponse>
*/
create(supportTicketName: string, communicationName: string, createCommunicationParameters: Models.CommunicationDetails, options?: msRest.RequestOptionsBase): Promise<Models.CommunicationsCreateResponse> {
return this.beginCreate(supportTicketName,communicationName,createCommunicationParameters,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.CommunicationsCreateResponse>;
}
/**
* Adds a new customer communication to an Azure support ticket.
* @param supportTicketName Support ticket name.
* @param communicationName Communication name.
* @param createCommunicationParameters Communication object.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginCreate(supportTicketName: string, communicationName: string, createCommunicationParameters: Models.CommunicationDetails, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
supportTicketName,
communicationName,
createCommunicationParameters,
options
},
beginCreateOperationSpec,
options);
}
/**
* Lists all communications (attachments not included) for a support ticket. <br/></br> You can
* also filter support ticket communications by _CreatedDate_ or _CommunicationType_ using the
* $filter parameter. The only type of communication supported today is _Web_. Output will be a
* paged result with _nextLink_, using which you can retrieve the next set of Communication
* results. <br/><br/>Support ticket data is available for 12 months after ticket creation. If a
* ticket was created more than 12 months ago, a request for data might cause an error.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.CommunicationsListNextResponse>
*/
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.CommunicationsListNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.CommunicationsListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.CommunicationsListResult>): void;
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CommunicationsListResult>, callback?: msRest.ServiceCallback<Models.CommunicationsListResult>): Promise<Models.CommunicationsListNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listNextOperationSpec,
callback) as Promise<Models.CommunicationsListNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const checkNameAvailabilityOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Support/supportTickets/{supportTicketName}/checkNameAvailability",
urlParameters: [
Parameters.supportTicketName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "checkNameAvailabilityInput",
mapper: {
...Mappers.CheckNameAvailabilityInput,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.CheckNameAvailabilityOutput
},
default: {
bodyMapper: Mappers.ExceptionResponse
}
},
serializer
};
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Support/supportTickets/{supportTicketName}/communications",
urlParameters: [
Parameters.supportTicketName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.top,
Parameters.filter,
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.CommunicationsListResult
},
default: {
bodyMapper: Mappers.ExceptionResponse
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Support/supportTickets/{supportTicketName}/communications/{communicationName}",
urlParameters: [
Parameters.supportTicketName,
Parameters.communicationName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.CommunicationDetails
},
default: {
bodyMapper: Mappers.ExceptionResponse
}
},
serializer
};
const beginCreateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Support/supportTickets/{supportTicketName}/communications/{communicationName}",
urlParameters: [
Parameters.supportTicketName,
Parameters.communicationName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "createCommunicationParameters",
mapper: {
...Mappers.CommunicationDetails,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.CommunicationDetails
},
202: {},
default: {
bodyMapper: Mappers.ExceptionResponse
}
},
serializer
};
const listNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.CommunicationsListResult
},
default: {
bodyMapper: Mappers.ExceptionResponse
}
},
serializer
}; | the_stack |
import os from 'os';
import { spawn, ChildProcess, exec } from 'child_process';
import fs, { WriteStream } from 'fs';
import path from 'path';
// Import utilities
import { deepCopy } from '../utils/DeepCopy';
import { DeepPartial } from '../utils/DeepPartial';
import { deepMerge } from '../utils/DeepMerge';
import {
FatalError,
MatchError,
NotSupportedError,
} from '../DimensionError';
import { Design } from '../Design';
import { Logger } from '../Logger';
import { Agent } from '../Agent';
import { Match } from '../Match';
import Dockerode from 'dockerode';
import { isChildProcess } from '../utils/TypeGuards';
import { noop } from '../utils';
import { removeDirectorySync } from '../utils/System';
/** @ignore */
type EngineOptions = MatchEngine.EngineOptions;
/**
* The Match Engine that takes a {@link Design} and its specified {@link EngineOptions} to form the backend
* for running matches with agents.
*/
export class MatchEngine {
/** The design the engine runs on */
private design: Design;
/** Engine options */
private engineOptions: EngineOptions = deepCopy(DefaultMatchEngineOptions);
/** Override options */
private overrideOptions: Design.OverrideOptions;
/** Logger */
private log = new Logger();
/**
* A coordination signal to ensure that all processes are indeed killed due to asynchronous initialization of agents
* There is a race condition when a tournament/match is being destroyed and while every match is being destroyed, some
* matches are in the initialization stage where they call the engine's initialize function. As a result, when we
* send a match destroy signal, we spawn some processes and haven't spawned some others for the agents. As a result,
* all processes eventually get spawned but not all are cleaned up and killed.
*/
killOffSignal = false;
/** approx extra buffer time given to agents due to engine processing for timeout mechanism */
static timeoutBuffer = 25;
private docker: Dockerode;
/**
* Single memory watch interval so that all memory checks are made together
*/
private memoryWatchInterval = null;
/**
* Match engine constructor
* @param design - the design to use
* @param loggingLevel - the logging level for this engine
*/
constructor(design: Design, loggingLevel: Logger.LEVEL) {
this.design = design;
this.engineOptions = deepMerge(
this.engineOptions,
deepCopy(this.design.getDesignOptions().engineOptions)
);
this.overrideOptions = deepCopy(this.design.getDesignOptions().override);
this.log.identifier = `Engine`;
this.setLogLevel(loggingLevel);
this.docker = new Dockerode({ socketPath: '/var/run/docker.sock' });
}
/** Set log level */
setLogLevel(loggingLevel: Logger.LEVEL): void {
this.log.level = loggingLevel;
}
/** Get the engine options */
getEngineOptions(): EngineOptions {
return this.engineOptions;
}
/** Set the engine options */
setEngineOptions(newOptions: DeepPartial<EngineOptions> = {}): void {
this.engineOptions = deepMerge(this.engineOptions, newOptions);
}
/**
* Starts up the engine by intializing processes for all the agents and setting some variables for a match
* @param agents - The agents involved to be setup for the given match
* @param match - The match to initialize
* @returns a promise that resolves once succesfully initialized
*/
async initialize(agents: Array<Agent>, match: Match): Promise<void> {
this.log.systembar();
const agentSetupPromises: Array<Promise<void>> = [];
match.agents.forEach((agent: Agent) => {
agentSetupPromises.push(this.initializeAgent(agent, match));
}, this);
await Promise.all(agentSetupPromises);
this.log.system('FINISHED INITIALIZATION OF PROCESSES\n');
return;
}
/**
* Initializes a single agent, called by {@link initialize}
* @param agent - agent to initialize
* @param match - match to initialize in
*/
private async initializeAgent(agent: Agent, match: Match): Promise<void> {
this.log.system(
'Setting up and spawning ' +
agent.name +
` | Command: ${agent.cmd} ${agent.src}`
);
// create container in secureMode
if (match.configs.secureMode) {
const name = `${match.id}_agent_${agent.id}`;
await agent.setupContainer(name, this.docker, this.engineOptions);
}
if (this.engineOptions.memory.active) {
if (agent.options.secureMode) {
// await agent._setupMemoryWatcherOnContainer(this.engineOptions);
}
}
// note to self, do a Promise.all for each stage before going to the next, split initializeAgent into
// initializeAgentCompile, initializeAgentInstall, initializeAgentSpawn....
const errorLogFilepath = path.join(
match.getMatchErrorLogDirectory(),
agent.getAgentErrorLogFilename()
);
let errorLogWriteStream: WriteStream = null;
if (match.configs.storeErrorLogs) {
errorLogWriteStream = fs.createWriteStream(errorLogFilepath);
agent.errorLogWriteStream = errorLogWriteStream;
errorLogWriteStream.write('=== Agent Install Log ===\n');
}
// wait for install step
await agent._install(
errorLogWriteStream,
errorLogWriteStream,
this.engineOptions
);
this.log.system('Succesfully ran install step for agent ' + agent.id);
if (match.configs.storeErrorLogs) {
errorLogWriteStream.write('=== Agent Compile Log ===\n');
}
// wait for compilation step
await agent._compile(
errorLogWriteStream,
errorLogWriteStream,
this.engineOptions
);
this.log.system('Succesfully ran compile step for agent ' + agent.id);
let p: ChildProcess | Agent.ContainerExecData = null;
p = await agent._spawn();
this.log.system('Spawned agent ' + agent.id);
if (isChildProcess(p)) {
// store process and streams
agent._storeProcess(p);
agent.streams.in = p.stdin;
agent.streams.out = p.stdout;
agent.streams.err = p.stderr;
p.on('close', (code) => {
agent.emit(Agent.AGENT_EVENTS.CLOSE, code);
});
// we do not care if input stream is broken, engine will detect this error through timeouts and what not
agent.streams.in.on('error', noop);
} else {
// store streams
agent.streams.in = p.in;
agent.streams.out = p.out;
agent.streams.err = p.err;
const containerExec = p.exec;
p.stream.on('end', async () => {
const endRes = await containerExec.inspect();
agent.emit(Agent.AGENT_EVENTS.CLOSE, endRes.ExitCode);
});
}
// add listener for memory limit exceeded
agent.on(Agent.AGENT_EVENTS.EXCEED_MEMORY_LIMIT, () => {
this.engineOptions.memory.memoryCallback(
agent,
match,
this.engineOptions
);
});
// add listener for timeouts
agent.on(Agent.AGENT_EVENTS.TIMEOUT, () => {
this.engineOptions.timeout.timeoutCallback(
agent,
match,
this.engineOptions
);
});
match.idToAgentsMap.set(agent.id, agent);
// set agent status as running
agent.status = Agent.Status.RUNNING;
// handler for stdout of Agent processes. Stores their output commands and resolves move promises
agent.streams.out.on('readable', () => {
let data: Array<string>;
while ((data = agent.streams.out.read())) {
// split chunks into line by line and handle each line of commands
const strs = `${data}`.split(/\r?\n/);
// first store data into a buffer and process later if no newline character is detected
// if final char in the strs array is not '', then \n is not at the end
const endsWithNewline = strs[strs.length - 1] === '';
// if strs when split up by \n, is greater than one in length, must have at least 1 newline char
const agentOutputContainsNewline = strs.length > 1;
if (agentOutputContainsNewline) {
// if there is a newline, take whatever was stored in the buffer and
// concat it with the output before the newline as they are part of the same line of commands
strs[0] = agent._buffer.join('').concat(strs[0]);
agent._buffer = [];
}
// handle each complete line of commands
for (let i = 0; i < strs.length - 1; i++) {
if (strs[i] === '') continue; // skip empty lines caused by adjacent \n chars
// handle commands from this agent provided it is allowed to send commands
if (agent.isAllowedToSendCommands()) {
this.handleCommand(agent, strs[i]);
}
}
// push final command that didn't have a newline into buffer
if (
this.engineOptions.commandLines.waitForNewline &&
strs.length >= 1 &&
!endsWithNewline
) {
agent._buffer.push(strs[strs.length - 1]);
}
}
});
// log stderr from agents to this stderr if option active
if (!this.engineOptions.noStdErr) {
agent.streams.err.on('data', (data) => {
const strs = `${data}`.split(/\r?\n/);
for (const str of strs) {
if (str === '') continue;
this.log.custom(
`[Agent ${agent.id} Log]`.cyan,
Logger.LEVEL.WARN,
str
);
}
});
}
// pipe stderr of agent process to error log file if enabled
if (match.configs.storeErrorLogs) {
errorLogWriteStream.write('=== Agent Error Log ===\n');
agent.streams.err.on('data', (data: Buffer) => {
// store logs below limit only
if (agent._logsize < agent.options.logLimit) {
agent._logsize += data.length;
errorLogWriteStream.write(`${data}`);
} else {
if (agent._trimmed === false) {
agent._trimmed = true;
this.log.warn(`agent ${agent.id}'s logs were trimmed`);
errorLogWriteStream.write(`\nend of logs as logs were trimmed\n`);
}
}
});
}
// when process closes, print message
agent.on(Agent.AGENT_EVENTS.CLOSE, (code) => {
// terminate agent with engine kill if it hasn't been marked as terminated yet, indicating process likely exited
// prematurely
if (!agent.isTerminated()) {
// if secureMode, agent wasn't terminated yet, and container exited prematurely with 137, it likely had an OOM error
if (agent.options.secureMode && code === 137) {
this.kill(
agent,
'agent closed but agent not terminated yet, likely exceeded memory'
);
this.engineOptions.memory.memoryCallback(
agent,
match,
this.engineOptions
);
} else {
this.kill(agent, 'agent closed but agent not terminated yet');
}
}
this.log.system(
`${agent.name} | id: ${agent.id} - exited with code ${code}`
);
});
if (this.engineOptions.memory.active) {
if (!agent.options.secureMode) {
agent._setupMemoryWatcher(this.engineOptions);
}
}
// this is for handling a race condition explained in the comments of this.killOffSignal
// Briefly, sometimes agent process isn't stored yet during initialization and doesn't get killed as a result
if (this.killOffSignal) {
this.kill(
agent,
'engine has killOffSignal on, killing agent during initialization'
);
}
}
/**
* Handles partial stdout from an agent
* @param agent - the agent to process the command for
* @param str - the string the agent sent
*/
private async handleCommand(agent: Agent, str: string) {
// TODO: Implement parallel command stream type
if (
this.engineOptions.commandStreamType ===
MatchEngine.COMMAND_STREAM_TYPE.SEQUENTIAL
) {
// IF SEQUENTIAL, we wait for each unit to finish their move and output their commands
switch (this.engineOptions.commandFinishPolicy) {
case MatchEngine.COMMAND_FINISH_POLICIES.FINISH_SYMBOL:
// if we receive the symbol representing that the agent is done with output and now awaits for updates
if (`${str}` === this.engineOptions.commandFinishSymbol) {
await agent._finishMove();
} else {
agent.currentMoveCommands.push(str);
}
break;
case MatchEngine.COMMAND_FINISH_POLICIES.LINE_COUNT:
// if we receive the finish symbol, we mark agent as done with output (finishes their move prematurely)
if (`${str}` === this.engineOptions.commandFinishSymbol) {
await agent._finishMove();
}
// only log command if max isnt reached
else if (
agent.currentMoveCommands.length <
this.engineOptions.commandLines.max - 1
) {
agent.currentMoveCommands.push(str);
}
// else if on final command before reaching max, push final command and resolve
else if (
agent.currentMoveCommands.length ==
this.engineOptions.commandLines.max - 1
) {
await agent._finishMove();
agent.currentMoveCommands.push(str);
}
break;
case MatchEngine.COMMAND_FINISH_POLICIES.CUSTOM:
// TODO: Not implemented yet
throw new NotSupportedError(
'Custom command finish policies are not allowed yet'
);
break;
}
}
// else if (this.engineOptions.commandStreamType === COMMAND_STREAM_TYPE.PARALLEL) {
// // If PARALLEL, theres no waiting, we store commands immediately and resolve right away after each command
// agent.currentMoveResolve();
// // updates to match are first come first serve
// }
}
/**
* Attempts to gracefully and synchronously stop a match's agents
* @param match - the match to stop
*/
public async stop(match: Match): Promise<void> {
const stopPromises: Array<Promise<void>> = [];
match.agents.forEach((agent) => {
stopPromises.push(agent.stop());
});
await Promise.all(stopPromises);
this.log.system('Stopped all agents');
}
/**
* Attempts to gracefully and synchronously resume a previously stopped match
* @param match - the match to resume
*/
public async resume(match: Match): Promise<void> {
const resumePromises: Array<Promise<void>> = [];
match.agents.forEach((agent) => {
resumePromises.push(agent.resume());
});
await Promise.all(resumePromises);
this.log.system('Resumed all agents');
}
/**
* Kills all intervals and agents and processes from a match and cleans up. Kills any game processes as well. Shouldn't be used
* for custom design based matches. Called by {@link Match}
*
* @param match - the match to kill all agents in and clean up
*/
public async killAndClean(match: Match): Promise<void> {
// set to true to ensure no more processes are being spawned.
this.killOffSignal = true;
clearInterval(this.memoryWatchInterval);
const cleanUpPromises: Array<Promise<any>> = [];
if (match.agents) {
match.agents.forEach((agent) => {
cleanUpPromises.push(this.kill(agent, 'cleanup'));
});
}
await Promise.all(cleanUpPromises);
}
/**
* Kills an agent and closes the process, and no longer attempts to receive coommands from it anymore
* @param agent - the agent to kill off
*/
public async kill(agent: Agent, reason = 'unspecified'): Promise<void> {
try {
await agent._terminate();
this.log.system(
`Killed off agent ${agent.id} - ${agent.name}`,
`Reason: ${reason}`
);
} catch (err) {
this.log.system('This should not happen when terminating agents.', err);
}
agent._currentMoveResolve();
}
/**
* Returns a promise that resolves with all the commands loaded from the previous time step of the provided match
* This coordinates all the Agents and waits for each one to finish their step
* @param match - The match to get commands from agents for
* @returns a promise that resolves with an array of {@link MatchEngine.Command} elements, holding the command and id
* of the agent that sent it
*/
public getCommands(match: Match): Promise<Array<MatchEngine.Command>> {
return new Promise((resolve) => {
const commands: Array<MatchEngine.Command> = [];
const nonTerminatedAgents = match.agents.filter((agent: Agent) => {
return !agent.isTerminated();
});
const allAgentMovePromises = nonTerminatedAgents.map((agent: Agent) => {
return agent._currentMovePromise;
});
Promise.all(allAgentMovePromises).then(() => {
this.log.system(`All move promises resolved`);
match.agents.forEach((agent: Agent) => {
// for each set of commands delimited by '\n' in stdout of process, split it by delimiter and push to
// commands
agent.currentMoveCommands.forEach((commandString) => {
commandString
.split(this.engineOptions.commandDelimiter)
.forEach((c) => {
// we don't accept '' as commands.
if (c !== '') {
commands.push({ command: c, agentID: agent.id });
}
});
});
});
this.log.systemIO(
`Agent commands at end of time step ${
match.timeStep
} to be sent to match on time step ${match.timeStep + 1} `
);
this.log.systemIO(
commands.length ? JSON.stringify(commands) : 'No commands'
);
resolve(commands);
});
});
}
/**
* Sends a message to a particular process governed by an agent in a specified match specified by the agentID
* @param match - the match to work with
* @param message - the message to send to agent's stdin
* @param agentID - id that specifies the agent in the match to send the message to
*/
public send(
match: Match,
message: string,
agentID: Agent.ID
): Promise<boolean> {
return new Promise((resolve, reject) => {
const agent = match.idToAgentsMap.get(agentID);
if (
agent.options.detached ||
(!agent.inputDestroyed() && !agent.isTerminated())
) {
const written = agent.options.detached ? `${message}` : `${message}\n`;
const bufferReachedHighWaterMark = agent.write(
written,
(error: Error) => {
if (error) reject(error);
resolve(true);
}
);
if (!bufferReachedHighWaterMark) {
// reject(
// new AgentNotHandlingInputError(
// 'Input stream buffer highWaterMark reached, agent is not processing input',
// agentID
// )
// );
this.log.system(`Agent ${agentID} buffer reached high watermark`);
}
} else {
this.log.error(
`Agent ${agentID} - ${agent.name} - has been killed off already, can't send messages now`
);
resolve(false);
}
});
}
/**
* @param match - The match to initialize with a custom design
*/
async initializeCustom(): Promise<boolean> {
// TODO: Initialize a custom design based match and run through some basic security measures
return true;
}
/**
* Run a custom match. A custom match much print to stdout all relevant data to be used by the engine and
* Dimensions framework. All output after the conclude command from {@link Design.OverrideOptions} is outputted
* is stored as a list of new line delimited strings and returned as the match results. The match must exit with
* exit code 0 to be marked as succesfully complete and the processing of results stops and this function resolves
* @param match - the match to run
*/
public runCustom(match: Match): Promise<Array<string>> {
return new Promise((resolve, reject) => {
if (this.overrideOptions.active == false) {
reject(
new FatalError(
'Override was not set active! Make sure to set the overide.active field to true'
)
);
}
const cmd = this.overrideOptions.command;
const parsed = this.parseCustomArguments(
match,
this.overrideOptions.arguments
);
// spawn the match process with the parsed arguments
let matchProcessTimer: any;
// TODO: configure some kind of secureMode for custom matches
match.matchProcess = spawn(cmd, parsed).on('error', (err) => {
if (err) throw err;
});
this.log.system(
`${match.name} | id: ${match.id} - spawned: ${cmd} ${parsed.join(' ')}`
);
const errorLogFilepath = path.join(
match.getMatchErrorLogDirectory(),
`match_error.log`
);
let errorLogWriteStream: WriteStream = null;
if (match.configs.storeErrorLogs) {
errorLogWriteStream = fs.createWriteStream(errorLogFilepath);
}
// pipe stderr of match process to error log file if enabled
if (match.configs.storeErrorLogs) {
errorLogWriteStream.write('=== Custom Match Error Log ===\n');
match.matchProcess.stderr.pipe(errorLogWriteStream);
}
let matchTimedOut = false;
// set up timer if specified
if (this.overrideOptions.timeout !== null) {
matchProcessTimer = setTimeout(() => {
this.log.system(`${match.name} | id: ${match.id} - Timed out`);
match.matchProcess.kill('SIGKILL');
matchTimedOut = true;
}, this.overrideOptions.timeout);
}
let processingStage = false;
match.matchProcess.stdout.on('readable', () => {
let data: string[];
while ((data = match.matchProcess.stdout.read())) {
// split chunks into line by line and handle each line of output
const strs = `${data}`.split(/\r?\n/);
for (let i = 0; i < strs.length; i++) {
const str = strs[i];
// skip empties
if (str === '') continue;
// if we reached conclude command, default being D_MATCH_FINISHED, we start the processing stage
if (str === this.overrideOptions.conclude_command) {
processingStage = true;
}
// else if we aren't in the processing stage
else if (!processingStage) {
// store all stdout
match.state.matchOutput.push(str);
}
// otherwise we are in processing stage
else {
// store into results
match.results.push(str);
}
}
}
});
match.matchProcess.stdout.on('close', (code) => {
this.log.system(
`${match.name} | id: ${match.id} - exited with code ${code}`
);
if (matchTimedOut) {
reject(new MatchError('Match timed out'));
} else {
clearTimeout(matchProcessTimer);
resolve(match.results);
}
// remove the agent files if on secureMode and double check it is the temporary directory
match.agents.forEach((agent) => {
if (agent.options.secureMode) {
const tmpdir = os.tmpdir();
if (agent.cwd.slice(0, tmpdir.length) === tmpdir) {
removeDirectorySync(agent.cwd);
} else {
this.log.error(
"couldn't remove agent files while in secure mode"
);
}
}
});
});
});
}
/**
* Attempts to stop a {@link Match} based on a custom {@link Design}
* @param match - the match to stop
*/
public async stopCustom(match: Match): Promise<void> {
// attempt to stop the match
match.matchProcess.kill('SIGSTOP');
// TODO: stop the match process timer
}
/**
* Attempts to resume a {@link Match} based on a custom {@link Design}
* @param match - the match to resume
*/
public async resumeCustom(match: Match): Promise<void> {
// attempt to resume the match
match.matchProcess.kill('SIGCONT');
}
/**
* Attempts to kill and clean up anything else for a custom design based match
* @param match - the match to kill and clean up
*/
public async killAndCleanCustom(match: Match): Promise<void> {
if (match.matchProcess) match.matchProcess.kill('SIGKILL');
}
/**
* Parses a list of arguments for a given match and populates relevant strings as needed
* @param match - the match to parse arguments for
* @param args - the arguments to parse
*/
private parseCustomArguments(
match: Match,
args: Array<string | MatchEngine.DynamicDataStrings>
): Array<string> {
if (match.matchStatus === Match.Status.UNINITIALIZED) {
throw new FatalError(
`Match ${match.id} - ${match.name} is not initialized yet`
);
}
const parsed = [];
for (let i = 0; i < args.length; i++) {
switch (args[i]) {
case MatchEngine.DynamicDataStrings.D_FILES:
match.agents.forEach((agent) => {
parsed.push(agent.file);
});
break;
case MatchEngine.DynamicDataStrings.D_TOURNAMENT_IDS:
match.agents.forEach((agent) => {
// pass in tournament ID string if it exists, otherwise pass in 0
parsed.push(agent.tournamentID.id ? agent.tournamentID : '0');
});
break;
case MatchEngine.DynamicDataStrings.D_AGENT_IDS:
match.agents.forEach((agent) => {
parsed.push(agent.id);
});
break;
case MatchEngine.DynamicDataStrings.D_MATCH_ID:
parsed.push(match.id);
break;
case MatchEngine.DynamicDataStrings.D_MATCH_NAME:
parsed.push(match.name);
break;
case MatchEngine.DynamicDataStrings.D_NAMES:
match.agents.forEach((agent) => {
let parsedName = agent.name;
parsedName = parsedName.replace(/\//g, '-');
parsedName = parsedName.replace(/ /g, '_');
parsed.push(parsedName);
});
break;
default:
parsed.push(args[i]);
break;
}
}
return parsed;
}
/**
* Returns the logger for this match engine
*/
public getLogger(): Logger {
return this.log;
}
}
export namespace MatchEngine {
/**
* Various policies available that describe the requirements before an agent is marked as done with sending commands
* at some time step
*/
export enum COMMAND_FINISH_POLICIES {
/**
* Agent's finish their commands by sending a finish symbol, namely {@link EngineOptions.commandFinishSymbol}
*/
FINISH_SYMBOL = 'finish_symbol',
/**
* Agent's finish their commands by either sending a finish symmbol or after they send
* {@link EngineOptions.commandLines.max} lines
*/
LINE_COUNT = 'line_count',
/**
* Custom finishing policy provided by user. Not allowed at the moment
*/
CUSTOM = 'custom',
// TODO: implement custom finish policy
}
/**
* Engine Options that specify how the {@link MatchEngine} should operate on a {@link Match}
*/
export interface EngineOptions {
/** The command streaming type */
commandStreamType: MatchEngine.COMMAND_STREAM_TYPE;
/**
* Delimiter for seperating commands from agents in their stdout and then sending these delimited commands to
* {@link Design.update}. If an agent sent `move a b 3,run 24 d,t 3` and the delimiter is `','` then the
* {@link Design.update} function will receive commands `'move a b 3'` and `'run 24 d'` and `'t 3'`
* @default ','
*/
commandDelimiter: string;
/**
* The finish symbol to use
* @default 'D_FINISH'
*/
commandFinishSymbol: string;
/**
* Which kind of command finishing policy to use
* @default 'finish_symbol'
*/
commandFinishPolicy: MatchEngine.COMMAND_FINISH_POLICIES;
/**
* Options for the {@link COMMAND_FINISH_POLICIES.LINE_COUNT} finishing policy. Used only if this policy is active
*/
commandLines: {
/**
* Maximum lines of commands delimited by new line characters '\n' allowed before engine cuts off an Agent
* @default 1
*/
max: number;
/**
* Whether the engine should wait for a newline character before processing the line of commands received
* This should for most cases be set to `true`; false will lead to some unpredictable behavior.
* @default true
*/
waitForNewline: boolean;
};
/**
* Whether agents output to standard error is logged by the matchengine or not
*
* It's suggested to let agent output go to a file.
*
* @default true
*/
noStdErr: boolean;
/**
* Options for timeouts of agents
*/
timeout: {
/**
* On or not
* @default true
*/
active: boolean;
/**
* How long in milliseconds each agent is given before they are timed out and the timeoutCallback
* function is called
* @default 1000
*/
max: number;
/**
* the callback called when an agent times out.
* Default is kill the agent with {@link Match.kill}.
*/
timeoutCallback: /**
* @param agent the agent that timed out
* @param match - the match the agent timed out in
* @param engineOptions - a copy of the engineOptions used that timed out the agent
*/
(agent: Agent, match: Match, engineOptions: EngineOptions) => void;
};
/**
* Options related to the memory usage of agents. The memoryCallback is called when the limit is reached
*/
memory: {
/**
* Whether or not the engine will monitor the memory use. Currently is disabled on windows and this option does nothing.
* @default true
*/
active: boolean;
/**
* Maximum number of bytes an agent can use before the memoryCallback is called
* @default 1 GB (1,000,000,000 bytes)
*/
limit: number;
/**
* The callback called when an agent raeches the memory limit
* Default is kill the agent with {@link Match.kill}
*/
memoryCallback: /**
* @param agent the agent that reached the memory limit
* @param match - the match the agent was in
* @param engineOptions - a copy of the engineOptions used in the match
*/
(agent: Agent, match: Match, engineOptions: EngineOptions) => void;
/**
* How frequently the engine checks the memory usage of an agent in milliseconds
* @default 100
*/
checkRate: number;
/**
* Whether or not to use `ps` instead of `procfile` for measuring memory through the
* pidusage package.
*
* @default true
*/
usePs: boolean;
};
}
/** Standard ways for commands from agents to be streamed to the MatchEngine for the {@link Design} to handle */
export enum COMMAND_STREAM_TYPE {
/** First come first serve for commands run. Not implemented */
PARALLEL = 'parallel',
/** Each agent's set of commands is run before the next agent */
SEQUENTIAL = 'sequential',
}
/**
* A command delimited by the delimiter of the match engine from all commands sent by agent specified by agentID
*/
export interface Command {
/**
* The string command received
*/
command: string;
/**
* The id of the agent that sent this command
*/
agentID: Agent.ID;
}
/**
* Dynammic Data strings are strings in the {@link OverrideOptions} arguments array that are automatically replaced
* with dynamic data as defined in the documentation of these enums
*/
export enum DynamicDataStrings {
/**
* `D_FILES` is automatically populated by a space seperated string list of the file paths provided for each of the
* agents competing in a match.
*
* NOTE, these paths don't actually need to be files, they can be directories or anything that works with
* your own command and design
*
* @example Suppose the paths to the sources the agents operate on are `path1`, `path2`, `path3`. Then `D_FILES`
* will be passed into your command as `path1 path2 path3`
*/
D_FILES = 'D_FILES',
/**
* `D_AGENT_IDS` is automatically populated by a space seperated string list of the agent IDs of every agent being
* loaded into a match in the same order as D_FILES. This should always be sorted by default as agents are loaded
* in order from agent ID `0` to agent ID `n-1`in a `n` agent match
*
* @example Suppose a match is running with agents with IDs `0, 1, 2, 3`. Then `D_AGENT_IDS` will be passed into
* your command as `0 1 2 3`
*/
D_AGENT_IDS = 'D_AGENT_IDS',
/**
* `D_TOURNAMENT_IDS` is automatically populated by a space seperated string list of the tournament ID numbers of
* the agents being loaded into the match in the same order. If no tournament is being run all the ID numbers will
* default to 0 but still be passed in to the command you give for the override configurations
*
* @example Suppose a match in a tournament is running 2 agents with tournament IDs `Qb6NyTxufGGU`, `EGg3tSN2KUgl`
* Then `D_TOURNAMENT_IDS` will be passed into your command as `Qb6NyTxufGGU EGg3tSN2KUgl`
*/
D_TOURNAMENT_IDS = 'D_TOURNAMENT_IDS',
/**
* D_MATCH_ID is automatically replaced with the id of the match being run
*
* @example Suppose the match has ID `eF1uEacgfgMm`, then `D_MATCH_ID` is passed into your command as `eF1uEacgfgMm`
*/
D_MATCH_ID = 'D_MATCH_ID',
/**
* D_MATCH_NAME is automatically replaced with the name of the match being run
*
* @example Suppose the match has name 'my_match'. Then `D_MATCH_NAME` is passed into your commnad as `my_match`
*/
D_MATCH_NAME = 'D_MATCH_NAME',
/**
* D_NAMES is automatically replaced with the names of the agents
*
* @example Suppose the agents 0 and 1 had names `bob, richard`. Then `D_NAMES` is passed into your command as
* `bob richard`
*/
D_NAMES = 'D_NAMES',
}
}
export const DefaultMatchEngineOptions: MatchEngine.EngineOptions = {
commandStreamType: MatchEngine.COMMAND_STREAM_TYPE.SEQUENTIAL,
commandDelimiter: ',',
commandFinishSymbol: 'D_FINISH',
commandFinishPolicy: MatchEngine.COMMAND_FINISH_POLICIES.FINISH_SYMBOL,
commandLines: {
max: 1,
// min: 1
waitForNewline: true,
},
noStdErr: true,
timeout: {
max: 1000,
active: true,
timeoutCallback: (
agent: Agent,
match: Match,
engineOptions: EngineOptions
): void => {
match.kill(agent.id, 'timed out');
match.log.error(
`agent ${agent.id} - '${agent.name}' timed out after ${engineOptions.timeout.max} ms`
);
},
/**
* (agent: Agent, match: Match) => {
* agent.finish();
* }
*/
},
memory: {
limit: 1000000000,
active: true,
usePs: true,
memoryCallback: (
agent: Agent,
match: Match,
engineOptions: EngineOptions
): void => {
match.kill(agent.id, 'exceed memory limit');
match.log.error(
`agent ${agent.id} - '${agent.name}' reached the memory limit of ${
engineOptions.memory.limit / 1000000
} MB`
);
},
checkRate: 100,
},
}; | the_stack |
import { ModelRepresentation } from '../model/modelRepresentation';
import { ObjectNode } from '../model/objectNode';
import { ResultListDataRepresentationModelRepresentation } from '../model/resultListDataRepresentationModelRepresentation';
import { ValidationErrorRepresentation } from '../model/validationErrorRepresentation';
import { BaseApi } from './base.api';
import { throwIfNotDefined } from '../../../assert';
/**
* Models service.
* @module ModelsApi
*/
export class ModelsApi extends BaseApi {
/**
* Create a new model
*
*
*
* @param modelRepresentation modelRepresentation
* @return Promise<ModelRepresentation>
*/
createModel(modelRepresentation: ModelRepresentation): Promise<ModelRepresentation> {
throwIfNotDefined(modelRepresentation, 'modelRepresentation');
let postBody = modelRepresentation;
let pathParams = {
};
let queryParams = {
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/models', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, ModelRepresentation);
}
/**
* Delete a model
*
*
*
* @param modelId modelId
* @param opts Optional parameters
* @param opts.cascade cascade
* @param opts.deleteRuntimeApp deleteRuntimeApp
* @return Promise<{}>
*/
deleteModel(modelId: number, opts?: any): Promise<any> {
throwIfNotDefined(modelId, 'modelId');
opts = opts || {};
let postBody = null;
let pathParams = {
'modelId': modelId
};
let queryParams = {
'cascade': opts['cascade'],
'deleteRuntimeApp': opts['deleteRuntimeApp']
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/models/{modelId}', 'DELETE',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts);
}
/**
* Duplicate an existing model
*
*
*
* @param modelId modelId
* @param modelRepresentation modelRepresentation
* @return Promise<ModelRepresentation>
*/
duplicateModel(modelId: number, modelRepresentation: ModelRepresentation): Promise<ModelRepresentation> {
throwIfNotDefined(modelId, 'modelId');
throwIfNotDefined(modelRepresentation, 'modelRepresentation');
let postBody = modelRepresentation;
let pathParams = {
'modelId': modelId
};
let queryParams = {
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/models/{modelId}/clone', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, ModelRepresentation);
}
/**
* Get model content
*
*
*
* @param modelId modelId
* @return Promise<ObjectNode>
*/
getModelJSON(modelId: number): Promise<ObjectNode> {
throwIfNotDefined(modelId, 'modelId');
let postBody = null;
let pathParams = {
'modelId': modelId
};
let queryParams = {
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/models/{modelId}/editor/json', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, ObjectNode);
}
/**
* Get a model's thumbnail image
*
*
*
* @param modelId modelId
* @return Promise<string>
*/
getModelThumbnail(modelId: number): Promise<string> {
throwIfNotDefined(modelId, 'modelId');
let postBody = null;
let pathParams = {
'modelId': modelId
};
let queryParams = {
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['image/png'];
return this.apiClient.callApi(
'/api/enterprise/models/{modelId}/thumbnail', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts);
}
/**
* Get a model
*
* Models act as containers for process, form, decision table and app definitions
*
* @param modelId modelId
* @param opts Optional parameters
* @param opts.includePermissions includePermissions
* @return Promise<ModelRepresentation>
*/
getModel(modelId: number, opts?: any): Promise<ModelRepresentation> {
throwIfNotDefined(modelId, 'modelId');
opts = opts || {};
let postBody = null;
let pathParams = {
'modelId': modelId
};
let queryParams = {
'includePermissions': opts['includePermissions']
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/models/{modelId}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, ModelRepresentation);
}
/**
* List process definition models shared with the current user
*
*
*
* @return Promise<ResultListDataRepresentationModelRepresentation>
*/
getModelsToIncludeInAppDefinition(): Promise<ResultListDataRepresentationModelRepresentation> {
let postBody = null;
let pathParams = {
};
let queryParams = {
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/models-for-app-definition', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, ResultListDataRepresentationModelRepresentation);
}
/**
* List models (process, form, decision rule or app)
*
*
*
* @param opts Optional parameters
* @param opts.filter filter
* @param opts.sort sort
* @param opts.modelType modelType
* @param opts.referenceId referenceId
* @return Promise<ResultListDataRepresentationModelRepresentation>
*/
getModels(opts?: any): Promise<ResultListDataRepresentationModelRepresentation> {
opts = opts || {};
let postBody = null;
let pathParams = {
};
let queryParams = {
'filter': opts['filter'],
'filterText': opts['filterText'],
'sort': opts['sort'],
'modelType': opts['modelType'],
'referenceId': opts['referenceId']
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/models', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, ResultListDataRepresentationModelRepresentation);
}
/**
* Create a new version of a model
*
*
*
* @param modelId modelId
* @param file file
* @return Promise<ModelRepresentation>
*/
importNewVersion(modelId: number, file: any): Promise<ModelRepresentation> {
throwIfNotDefined(modelId, 'modelId');
throwIfNotDefined(file, 'file');
let postBody = null;
let pathParams = {
'modelId': modelId
};
let queryParams = {
};
let headerParams = {
};
let formParams = {
'file': file
};
let contentTypes = ['multipart/form-data'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/models/{modelId}/newversion', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, ModelRepresentation);
}
/**
* Import a BPMN 2.0 XML file
*
*
*
* @param file file
* @return Promise<ModelRepresentation>
*/
importProcessModel(file: any): Promise<ModelRepresentation> {
throwIfNotDefined(file, 'file');
let postBody = null;
let pathParams = {
};
let queryParams = {
};
let headerParams = {
};
let formParams = {
'file': file
};
let contentTypes = ['multipart/form-data'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/process-models/import', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, ModelRepresentation);
}
/**
* Update model content
*
*
*
* @param modelId modelId
* @param values values
* @return Promise<ModelRepresentation>
*/
saveModel(modelId: number, values: any): Promise<ModelRepresentation> {
throwIfNotDefined(modelId, 'modelId');
throwIfNotDefined(values, 'values');
let postBody = values;
let pathParams = {
'modelId': modelId
};
let queryParams = {
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/models/{modelId}/editor/json', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, ModelRepresentation);
}
/**
* Update a model
*
* This method allows you to update the metadata of a model. In order to update the content of the model you will need to call the specific endpoint for that model type.
*
* @param modelId modelId
* @param updatedModel updatedModel
* @return Promise<ModelRepresentation>
*/
updateModel(modelId: number, updatedModel: ModelRepresentation): Promise<ModelRepresentation> {
throwIfNotDefined(modelId, 'modelId');
throwIfNotDefined(updatedModel, 'updatedModel');
let postBody = updatedModel;
let pathParams = {
'modelId': modelId
};
let queryParams = {
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/models/{modelId}', 'PUT',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, ModelRepresentation);
}
/**
* Validate model content
*
*
*
* @param modelId modelId
* @param opts Optional parameters
* @param opts.values values
* @return Promise<ValidationErrorRepresentation>
*/
validateModel(modelId: number, opts?: any): Promise<ValidationErrorRepresentation> {
throwIfNotDefined(modelId, 'modelId');
opts = opts || {};
let postBody = opts['values'];
let pathParams = {
'modelId': modelId
};
let queryParams = {
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/x-www-form-urlencoded'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/models/{modelId}/editor/validate', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, ValidationErrorRepresentation);
}
} | the_stack |
import { HttpClient } from '@angular/common/http';
import { Inject } from '@angular/core';
import {
areCoordinatesNumeric,
BaseImageryMap,
ExtentCalculator, IExportMapMetadata,
IMAGERY_MAIN_LAYER_NAME,
IMAGERY_SLOW_ZOOM_FACTOR,
ImageryLayerProperties,
ImageryMap,
ImageryMapExtent,
ImageryMapExtentPolygon,
IImageryMapPosition,
IMapProgress, GetProvidersMapsService, IBaseImageryLayer
} from '@ansyn/imagery';
import * as turf from '@turf/turf';
import { feature } from '@turf/turf';
import { Feature, FeatureCollection, GeoJsonObject, GeometryObject, Point as GeoPoint, Polygon } from 'geojson';
import AttributionControl from 'ol/control/Attribution';
import ScaleLine from 'ol/control/ScaleLine';
import olFeature from 'ol/Feature';
import olGeoJSON from 'ol/format/GeoJSON';
import OLGeoJSON from 'ol/format/GeoJSON';
import olPolygon from 'ol/geom/Polygon';
import * as olInteraction from 'ol/interaction'
import Group from 'ol/layer/Group';
import ol_Layer from 'ol/layer/Layer';
import VectorLayer from 'ol/layer/Vector';
import OLMap from 'ol/Map';
import Vector from 'ol/source/Vector';
import Projection from 'ol/proj/Projection';
import View from 'ol/View';
import { Observable, of, Subject, timer } from 'rxjs';
import { debounceTime, filter, map, switchMap, take, takeUntil, tap, mergeMap } from 'rxjs/operators';
import { IOlConfig, OL_CONFIG } from '../../../config/ol-config';
import { OpenLayersProjectionService } from '../../../projection/open-layers-projection.service';
import { OpenLayersMonitor } from '../helpers/openlayers-monitor';
import { Utils } from '../utils/utils';
import { exportMapHelper } from '../../helpers/helpers';
export const OpenlayersMapName = 'openLayersMap';
export enum StaticGroupsKeys {
layers = 'layers',
map = 'map'
}
// @dynamic
@ImageryMap({
mapType: OpenlayersMapName,
deps: [HttpClient, OpenLayersProjectionService, OL_CONFIG, GetProvidersMapsService]
})
export class OpenLayersMap extends BaseImageryMap<OLMap> {
static groupsKeys = StaticGroupsKeys;
groupLayersMap = new Map<StaticGroupsKeys, Group>(Object.values(StaticGroupsKeys).map((key) => [key, new Group({className: `group-${key}`})]));
private _mapObject: OLMap;
private _backgroundMapObject: OLMap;
public isValidPosition;
targetElement: HTMLElement = null;
public shadowNorthElement = null;
getMoveEndPositionObservable = new Subject<IImageryMapPosition>();
getMoveStartPositionObservable = new Subject<IImageryMapPosition>();
subscribers = [];
private showGroups = new Map<StaticGroupsKeys, boolean>();
private _backgroundMapParams: object;
private olGeoJSON: OLGeoJSON = new OLGeoJSON();
private _mapLayers = [];
private isLoading$: Subject<boolean> = new Subject();
private monitor: OpenLayersMonitor = new OpenLayersMonitor(
this.tilesLoadProgressEventEmitter,
this.tilesLoadErrorEventEmitter,
this.http
);
constructor(protected http: HttpClient,
public projectionService: OpenLayersProjectionService,
@Inject(OL_CONFIG) public olConfig: IOlConfig,
protected getProvidersMapsService: GetProvidersMapsService) {
super();
// todo: a more orderly way to give default values to config params
this.olConfig.tilesLoadingDoubleBuffer = this.olConfig.tilesLoadingDoubleBuffer || {
debounceTimeInMs: 500,
timeoutInMs: 3000
};
}
public get mapObject() {
return this._mapObject;
}
public get backgroundMapObject() {
return this._backgroundMapObject;
}
signalWhenTilesLoadingEnds() {
this.isLoading$.next(true);
this.tilesLoadProgressEventEmitter.pipe(
filter((payload: IMapProgress) => {
return payload.progress === 100;
}),
debounceTime(this.olConfig.tilesLoadingDoubleBuffer.debounceTimeInMs), // Adding debounce, to compensate for strange multiple loads when reading tiles from the browser cache (e.g. after browser refresh)
takeUntil(timer(this.olConfig.tilesLoadingDoubleBuffer.timeoutInMs).pipe(tap(() => {
this.isLoading$.next(false);
}))),
tap(() => {
this.isLoading$.next(false);
}),
take(1)
).subscribe();
}
private addToBaseMapGroup(layer: IBaseImageryLayer) {
if (this.groupLayersMap.get(StaticGroupsKeys.map).getLayersArray()[0]?.get('id') !== layer.get('id')) {
this.groupLayersMap.get(StaticGroupsKeys.map).getLayers().setAt(1, layer);
}
else if (this.groupLayersMap.get(StaticGroupsKeys.map).getLayersArray().length > 1) {
this.groupLayersMap.get(StaticGroupsKeys.map).getLayers().removeAt(1);
}
}
/**
* add layer to the map if it is not already exists the layer must have an id set
* @param layer
*/
public addLayerIfNotExist(layer): ol_Layer {
const layerId = layer.get(ImageryLayerProperties.ID);
if (!layerId) {
return;
}
const existingLayer: ol_Layer = this.getLayerById(layerId);
if (!existingLayer) {
// layer.set('visible',false);
this.addLayer(layer);
return layer;
}
return existingLayer;
}
toggleGroup(groupName: StaticGroupsKeys, newState: boolean) {
if (newState) {
this.addLayer(this.groupLayersMap.get(groupName));
} else {
this.removeLayer(this.groupLayersMap.get(groupName));
}
this.showGroups.set(groupName, newState);
}
getLayers(): ol_Layer[] {
return this.mapObject.getLayers().getArray();
}
getGroupLayers() {
return this.groupLayersMap.get(StaticGroupsKeys.layers);
}
initMap(target: HTMLElement, shadowNorthElement: HTMLElement, shadowDoubleBufferElement: HTMLElement, layer: ol_Layer, position?: IImageryMapPosition): Observable<boolean> {
this.targetElement = target;
this.shadowNorthElement = shadowNorthElement;
this._mapLayers = [];
const controls = [
new ScaleLine(),
new AttributionControl({
collapsible: true
})
];
const renderer = 'canvas';
this._mapObject = new OLMap({
target,
renderer,
controls,
interactions: olInteraction.defaults({ doubleClickZoom: false }),
preload: Infinity
});
this.initListeners();
this._backgroundMapParams = {
target: shadowDoubleBufferElement,
renderer
};
// For initMap() we invoke resetView without double buffer
// (otherwise resetView() would have waited for the tile loading to end, but we don't want initMap() to wait).
// The double buffer is not relevant at this stage anyway.
return this.getProvidersMapsService.getDefaultProviderByType(this.mapType).pipe(
mergeMap( (defaultSourceType) => this.getProvidersMapsService.createMapSourceForMapType(this.mapType, defaultSourceType)),
mergeMap( (defaultLayer) => {
this.groupLayersMap.get(StaticGroupsKeys.map).getLayers().setAt(0, defaultLayer);
return this.resetView(layer, position);
})
)
}
initListeners() {
this._mapObject.on('moveend', this._moveEndListener);
this._mapObject.on('movestart', this._moveStartListener);
this._mapObject.on('pointerdown', this._pointerDownListener);
this._mapObject.on('pointermove', this._pointerMoveListener);
this.subscribers.push(
this.getMoveEndPositionObservable.pipe(
switchMap((a) => {
return this.getPosition();
})
).subscribe(position => {
if (position) {
this.positionChanged.emit(position);
}
}),
this.getMoveStartPositionObservable.pipe(
switchMap((a) => {
return this.getPosition();
})
).subscribe(position => {
if (position) {
this.moveStart.emit(position)
}
})
);
}
createView(layer): View {
return new View({
projection: layer.getSource().getProjection(),
maxZoom: 21,
minZoom: 1
});
}
public resetView(layer: ol_Layer, position: IImageryMapPosition, extent?: ImageryMapExtent, useDoubleBuffer?: boolean): Observable<boolean> {
useDoubleBuffer = useDoubleBuffer && !layer.get(ImageryLayerProperties.FROM_CACHE);
if (useDoubleBuffer) {
this._backgroundMapObject = new OLMap(this._backgroundMapParams);
} else if (this._backgroundMapObject) {
this._backgroundMapObject.setTarget(null);
this._backgroundMapObject = null;
}
const rotation: number = this._mapObject.getView() && this.mapObject.getView().getRotation();
const view = this.createView(layer);
// set default values to prevent map Assertion error's
view.setCenter([0, 0]);
view.setRotation(rotation ? rotation : 0);
view.setResolution(1);
if (useDoubleBuffer) {
this.setMainLayerToBackgroundMap(layer);
this._backgroundMapObject.setView(view);
this.monitor.start(this.backgroundMapObject);
this.signalWhenTilesLoadingEnds();
return this._setMapPositionOrExtent(this.backgroundMapObject, position, extent, rotation).pipe(
switchMap(() => this.isLoading$.pipe(
filter((isLoading) => !isLoading),
take(1))),
switchMap(() => {
this.setMainLayerToForegroundMap(layer);
this._mapObject.setView(view);
return this._setMapPositionOrExtent(this.mapObject, position, extent, rotation);
})
);
} else {
this.setMainLayerToForegroundMap(layer);
this._mapObject.setView(view);
this.monitor.start(this.mapObject);
return this._setMapPositionOrExtent(this.mapObject, position, extent, rotation);
}
}
public getLayerById(id: string): ol_Layer {
return <ol_Layer>this.mapObject.getLayers().getArray().find(item => item.get(ImageryLayerProperties.ID) === id);
}
setGroupLayers() {
this.showGroups.forEach((show, group) => {
if (show) {
this.addLayer(this.groupLayersMap.get(StaticGroupsKeys.layers));
}
});
}
setMainLayerToForegroundMap(layer: ol_Layer) {
this.removeAllLayers();
if (layer.get(ImageryLayerProperties.IS_OVERLAY)) {
this.addLayer(layer);
}
else {
this.addToBaseMapGroup(layer);
this.addLayer(this.groupLayersMap.get(StaticGroupsKeys.map));
}
this.setGroupLayers();
}
setMainLayerToBackgroundMap(layer: ol_Layer) {
// should be removed useDoubleBuffer is deprecated.
layer.set(ImageryLayerProperties.NAME, IMAGERY_MAIN_LAYER_NAME);
this.backgroundMapObject.getLayers().clear();
this.backgroundMapObject.addLayer(layer);
}
getMainLayer(): ol_Layer {
return this.groupLayersMap.get(StaticGroupsKeys.map).getLayers().item(0);
}
fitToExtent(extent: ImageryMapExtent, map: OLMap = this.mapObject, view: View = map.getView()) {
const collection: any = turf.featureCollection([ExtentCalculator.extentToPolygon(extent)]);
return this.projectionService.projectCollectionAccuratelyToImage<olFeature>(collection, map).pipe(
tap((features: olFeature[]) => {
view.fit(features[0].getGeometry() as olPolygon, { nearest: true, constrainResolution: false });
})
);
}
public addMapLayer(layer: ol_Layer) {
this.addToBaseMapGroup(layer);
}
public addLayer(layer: ol_Layer) {
if (!this._mapLayers.includes(layer)) {
this._mapLayers.push(layer);
this._mapObject.addLayer(layer);
}
}
public removeAllLayers() {
this.showGroups.forEach((show, group) => {
if (show && this._mapObject) {
this._mapObject.removeLayer(this.groupLayersMap.get(StaticGroupsKeys.layers));
}
});
while (this._mapLayers.length > 0) {
this.removeLayer(this._mapLayers[0]);
}
this._mapLayers = [];
}
public removeLayer(layer: ol_Layer): void {
if (!layer) {
return;
}
this._mapLayers = this._mapLayers.filter((mapLayer) => mapLayer !== layer);
this._mapObject.removeLayer(layer);
this._mapObject.renderSync();
}
public setCenter(center: GeoPoint, animation: boolean): Observable<boolean> {
return this.projectionService.projectAccuratelyToImage(center, this.mapObject).pipe(map(projectedCenter => {
const olCenter = <[number, number]>projectedCenter.coordinates;
if (animation) {
this.flyTo(olCenter);
} else {
const view = this._mapObject.getView();
view.setCenter(olCenter);
}
return true;
}));
}
public updateSize(): void {
const center = this._mapObject.getView().getCenter();
if (!areCoordinatesNumeric(center)) {
return;
}
this._mapObject.updateSize();
this._mapObject.renderSync();
}
public getCenter(): Observable<GeoPoint> {
if (!this.isValidPosition) {
return of(null);
}
const view = this._mapObject.getView();
const center = view.getCenter();
if (!areCoordinatesNumeric(center)) {
return of(null);
}
const point = <GeoPoint>turf.geometry('Point', center);
return this.projectionService.projectAccurately(point, this.mapObject);
}
calculateRotateExtent(olmap: OLMap): Observable<{ extentPolygon: ImageryMapExtentPolygon, layerExtentPolygon: ImageryMapExtentPolygon }> {
const mainLayer = this.getMainLayer();
if (!this.isValidPosition || !mainLayer) {
return of({ extentPolygon: null, layerExtentPolygon: null });
}
const [width, height] = olmap.getSize();
const topLeft = olmap.getCoordinateFromPixel([0, 0]);
const topRight = olmap.getCoordinateFromPixel([width, 0]);
const bottomRight = olmap.getCoordinateFromPixel([width, height]);
const bottomLeft = olmap.getCoordinateFromPixel([0, height]);
const coordinates = [[topLeft, topRight, bottomRight, bottomLeft, topLeft]];
const someIsNaN = !coordinates[0].every(areCoordinatesNumeric);
if (someIsNaN) {
return of({ extentPolygon: null, layerExtentPolygon: null });
}
const cachedMainExtent = mainLayer.get(ImageryLayerProperties.MAIN_EXTENT);
const mainExtent = mainLayer.getExtent();
if (mainExtent && !Boolean(cachedMainExtent)) {
const layerExtentPolygon = Utils.extentToOlPolygon(mainExtent);
return this.projectionService.projectCollectionAccurately([new olFeature(new olPolygon(coordinates)), new olFeature(layerExtentPolygon)], olmap).pipe(
map((collection: FeatureCollection<GeometryObject>) => {
mainLayer.set(ImageryLayerProperties.MAIN_EXTENT, collection.features[1].geometry as Polygon);
return {
extentPolygon: collection.features[0].geometry as Polygon,
layerExtentPolygon: collection.features[1].geometry as Polygon
};
})
);
}
return this.projectionService.projectCollectionAccurately([new olFeature(new olPolygon(coordinates))], olmap)
.pipe(map((collection: FeatureCollection<GeometryObject>) => {
return {
extentPolygon: collection.features[0].geometry as Polygon,
layerExtentPolygon: cachedMainExtent
};
}));
}
fitRotateExtent(olmap: OLMap, extentFeature: Feature<ImageryMapExtentPolygon>, customResolution?: number): Observable<boolean> {
const collection: any = turf.featureCollection([extentFeature]);
return this.projectionService.projectCollectionAccuratelyToImage<olFeature>(collection, olmap).pipe(
map((features: olFeature[]) => {
const view: View = olmap.getView();
const geoJsonFeature = <any>this.olGeoJSON.writeFeaturesObject(features,
{ featureProjection: view.getProjection(), dataProjection: view.getProjection() });
const geoJsonExtent = geoJsonFeature.features[0].geometry;
const center = ExtentCalculator.calcCenter(geoJsonExtent);
const rotation = ExtentCalculator.calcRotation(geoJsonExtent);
const resolution = ExtentCalculator.calcResolution(geoJsonExtent, olmap.getSize(), rotation);
view.setCenter(center);
view.setRotation(rotation);
view.setResolution(customResolution ? customResolution : Math.abs(resolution));
this.isValidPosition = true;
return true;
})
);
}
public setPosition(position: IImageryMapPosition, map: OLMap = this.mapObject, view: View = map.getView()): Observable<boolean> {
const { extentPolygon, projectedState, customResolution } = position;
const someIsNan = !extentPolygon.coordinates[0].every(areCoordinatesNumeric);
if (someIsNan) {
console.warn('ol map setposition failed, can\'t handle invalid coordinates ' + extentPolygon);
return of(true);
}
const viewProjection = view.getProjection();
const isProjectedPosition = projectedState && viewProjection.getCode() === projectedState.projection.code;
if (isProjectedPosition) {
const { center, zoom, rotation } = projectedState;
view.setCenter(center);
view.setZoom(zoom);
view.setRotation(rotation);
this.isValidPosition = true;
return of(true);
} else {
const extentFeature = feature(extentPolygon);
return this.fitRotateExtent(map, extentFeature, customResolution);
}
}
public getPosition(): Observable<IImageryMapPosition> {
const view = this.mapObject.getView();
const projection = view.getProjection();
const projectedState = {
...(<any>view).getState(),
center: (<any>view).getCenter(),
projection: { code: projection.getCode() }
};
return this.calculateRotateExtent(this.mapObject).pipe(map(({ extentPolygon: extentPolygon, layerExtentPolygon: layerExtentPolygon }) => {
if (!extentPolygon) {
return null;
}
const someIsNaN = !extentPolygon.coordinates[0].every(areCoordinatesNumeric);
if (someIsNaN) {
console.warn('ol map getPosition failed invalid coordinates ', extentPolygon);
return null;
}
if (this.olConfig.needToUseLayerExtent && this.needToUseLayerExtent(layerExtentPolygon, extentPolygon)) {
extentPolygon = layerExtentPolygon;
}
return { extentPolygon, projectedState };
}));
}
needToUseLayerExtent(layerExtentPolygon: ImageryMapExtentPolygon, extentPolygon: ImageryMapExtentPolygon) {
if (!layerExtentPolygon) {
return false;
}
// check if 3 out of 4 coordinates inside main layer extent
let cornersInside = 0;
for (let i = 0; i < extentPolygon.coordinates[0].length - 1; i++) { // -1 in order to ignore duplicated coordinate
const isInside = turf.booleanPointInPolygon(turf.point(extentPolygon.coordinates[0][i]), turf.polygon(layerExtentPolygon.coordinates), { ignoreBoundary: false });
if (isInside) {
cornersInside++;
}
}
return cornersInside < 3;
}
public setRotation(rotation: number, map: OLMap = this.mapObject, view: View = map.getView()) {
view.setRotation(rotation);
}
public getRotation(view: View = this.mapObject.getView()): number {
return view.getRotation();
}
exportMap(exportMetadata: IExportMapMetadata): Observable<HTMLCanvasElement> {
const {size, resolution, extra: {annotations}} = exportMetadata;
const classToInclude = '.ol-layer canvas' + (annotations ? `,${annotations}` : '');
return exportMapHelper(this.mapObject, size, resolution, classToInclude);
}
one2one(): void {
const view = this.mapObject.getView();
view.setResolution(1)
}
zoomOut(): void {
const view = this.mapObject.getView();
const current = view.getZoom();
view.setZoom(current - IMAGERY_SLOW_ZOOM_FACTOR);
}
zoomIn(): void {
const view = this.mapObject.getView();
const current = view.getZoom();
view.setZoom(current + IMAGERY_SLOW_ZOOM_FACTOR);
}
flyTo(location: [number, number]) {
const view = this._mapObject.getView();
view.animate({
center: location,
duration: 2000
});
}
public addGeojsonLayer(data: GeoJsonObject): void {
let layer: VectorLayer = new VectorLayer({
updateWhileAnimating: true,
updateWhileInteracting: true,
source: new Vector({
features: new olGeoJSON().readFeatures(data)
})
});
this.mapObject.addLayer(layer);
}
getExtraData() {
return this.getMainLayer().getProperties()
}
getCoordinateFromScreenPixel(screenPixel: { x, y }): [number, number, number] {
const coordinate = this.mapObject.getCoordinateFromPixel([screenPixel.x, screenPixel.y]);
return coordinate;
}
getHtmlContainer(): HTMLElement {
return this.targetElement;
}
// BaseImageryMap End
public dispose() {
this.removeAllLayers();
if (this._mapObject) {
if (this.subscribers) {
this.subscribers.forEach((subscriber) => subscriber.unsubscribe());
delete this.subscribers;
}
this._mapObject.un('moveend', this._moveEndListener);
this._mapObject.un('movestart', this._moveStartListener);
this._mapObject.un('pointerdown', this._pointerDownListener);
this._mapObject.un('pointermove', this._pointerMoveListener);
this._mapObject.setTarget(null);
}
if (this._backgroundMapObject) {
this._backgroundMapObject.setTarget(null);
}
this.monitor.dispose();
}
private _moveEndListener: () => void = () => {
this.getMoveEndPositionObservable.next(null);
};
private _pointerMoveListener: (args) => void = (args) => {
const point = <GeoPoint>turf.geometry('Point', args.coordinate);
return this.projectionService.projectApproximately(point, this.mapObject).pipe(
take(1),
tap((projectedPoint) => {
if (areCoordinatesNumeric(projectedPoint.coordinates)) {
this.mousePointerMoved.emit({
long: projectedPoint.coordinates[0],
lat: projectedPoint.coordinates[1],
height: NaN
});
} else {
this.mousePointerMoved.emit({ long: NaN, lat: NaN, height: NaN });
}
}))
.subscribe();
};
private _moveStartListener: () => void = () => {
this.getMoveStartPositionObservable.next(null);
};
private _pointerDownListener: (args) => void = () => {
(<any>document.activeElement).blur();
};
// Used by resetView()
private _setMapPositionOrExtent(map: OLMap, position: IImageryMapPosition, extent: ImageryMapExtent, rotation: number): Observable<boolean> {
if (extent) {
this.fitToExtent(extent, map).subscribe();
if (rotation) {
this.setRotation(rotation, map);
}
this.isValidPosition = true;
} else if (position) {
return this.setPosition(position, map);
}
return of(true);
}
getProjectionCode(): string {
return this.getProjection().code_;
}
getProjection(): Projection {
return this._mapObject.getView().getProjection();
}
} | the_stack |
import { dew as _utilsDewDew } from "../utils.dew.js";
import { dew as _GenericWorkerDewDew } from "../stream/GenericWorker.dew.js";
import { dew as _utf8DewDew } from "../utf8.dew.js";
import { dew as _crc32DewDew } from "../crc32.dew.js";
import { dew as _signatureDewDew } from "../signature.dew.js";
var exports = {},
_dewExec = false;
export function dew() {
if (_dewExec) return exports;
_dewExec = true;
var utils = _utilsDewDew();
var GenericWorker = _GenericWorkerDewDew();
var utf8 = _utf8DewDew();
var crc32 = _crc32DewDew();
var signature = _signatureDewDew();
/**
* Transform an integer into a string in hexadecimal.
* @private
* @param {number} dec the number to convert.
* @param {number} bytes the number of bytes to generate.
* @returns {string} the result.
*/
var decToHex = function (dec, bytes) {
var hex = "",
i;
for (i = 0; i < bytes; i++) {
hex += String.fromCharCode(dec & 0xff);
dec = dec >>> 8;
}
return hex;
};
/**
* Generate the UNIX part of the external file attributes.
* @param {Object} unixPermissions the unix permissions or null.
* @param {Boolean} isDir true if the entry is a directory, false otherwise.
* @return {Number} a 32 bit integer.
*
* adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
*
* TTTTsstrwxrwxrwx0000000000ADVSHR
* ^^^^____________________________ file type, see zipinfo.c (UNX_*)
* ^^^_________________________ setuid, setgid, sticky
* ^^^^^^^^^________________ permissions
* ^^^^^^^^^^______ not used ?
* ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
*/
var generateUnixExternalFileAttr = function (unixPermissions, isDir) {
var result = unixPermissions;
if (!unixPermissions) {
// I can't use octal values in strict mode, hence the hexa.
// 040775 => 0x41fd
// 0100664 => 0x81b4
result = isDir ? 0x41fd : 0x81b4;
}
return (result & 0xFFFF) << 16;
};
/**
* Generate the DOS part of the external file attributes.
* @param {Object} dosPermissions the dos permissions or null.
* @param {Boolean} isDir true if the entry is a directory, false otherwise.
* @return {Number} a 32 bit integer.
*
* Bit 0 Read-Only
* Bit 1 Hidden
* Bit 2 System
* Bit 3 Volume Label
* Bit 4 Directory
* Bit 5 Archive
*/
var generateDosExternalFileAttr = function (dosPermissions, isDir) {
// the dir flag is already set for compatibility
return (dosPermissions || 0) & 0x3F;
};
/**
* Generate the various parts used in the construction of the final zip file.
* @param {Object} streamInfo the hash with information about the compressed file.
* @param {Boolean} streamedContent is the content streamed ?
* @param {Boolean} streamingEnded is the stream finished ?
* @param {number} offset the current offset from the start of the zip file.
* @param {String} platform let's pretend we are this platform (change platform dependents fields)
* @param {Function} encodeFileName the function to encode the file name / comment.
* @return {Object} the zip parts.
*/
var generateZipParts = function (streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) {
var file = streamInfo['file'],
compression = streamInfo['compression'],
useCustomEncoding = encodeFileName !== utf8.utf8encode,
encodedFileName = utils.transformTo("string", encodeFileName(file.name)),
utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
comment = file.comment,
encodedComment = utils.transformTo("string", encodeFileName(comment)),
utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
useUTF8ForComment = utfEncodedComment.length !== comment.length,
dosTime,
dosDate,
extraFields = "",
unicodePathExtraField = "",
unicodeCommentExtraField = "",
dir = file.dir,
date = file.date;
var dataInfo = {
crc32: 0,
compressedSize: 0,
uncompressedSize: 0
}; // if the content is streamed, the sizes/crc32 are only available AFTER
// the end of the stream.
if (!streamedContent || streamingEnded) {
dataInfo.crc32 = streamInfo['crc32'];
dataInfo.compressedSize = streamInfo['compressedSize'];
dataInfo.uncompressedSize = streamInfo['uncompressedSize'];
}
var bitflag = 0;
if (streamedContent) {
// Bit 3: the sizes/crc32 are set to zero in the local header.
// The correct values are put in the data descriptor immediately
// following the compressed data.
bitflag |= 0x0008;
}
if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) {
// Bit 11: Language encoding flag (EFS).
bitflag |= 0x0800;
}
var extFileAttr = 0;
var versionMadeBy = 0;
if (dir) {
// dos or unix, we set the dos dir flag
extFileAttr |= 0x00010;
}
if (platform === "UNIX") {
versionMadeBy = 0x031E; // UNIX, version 3.0
extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
} else {
// DOS or other, fallback to DOS
versionMadeBy = 0x0014; // DOS, version 2.0
extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
} // date
// @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
// @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
// @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
dosTime = date.getUTCHours();
dosTime = dosTime << 6;
dosTime = dosTime | date.getUTCMinutes();
dosTime = dosTime << 5;
dosTime = dosTime | date.getUTCSeconds() / 2;
dosDate = date.getUTCFullYear() - 1980;
dosDate = dosDate << 4;
dosDate = dosDate | date.getUTCMonth() + 1;
dosDate = dosDate << 5;
dosDate = dosDate | date.getUTCDate();
if (useUTF8ForFileName) {
// set the unicode path extra field. unzip needs at least one extra
// field to correctly handle unicode path, so using the path is as good
// as any other information. This could improve the situation with
// other archive managers too.
// This field is usually used without the utf8 flag, with a non
// unicode path in the header (winrar, winzip). This helps (a bit)
// with the messy Windows' default compressed folders feature but
// breaks on p7zip which doesn't seek the unicode path extra field.
// So for now, UTF-8 everywhere !
unicodePathExtraField = // Version
decToHex(1, 1) + // NameCRC32
decToHex(crc32(encodedFileName), 4) + // UnicodeName
utfEncodedFileName;
extraFields += // Info-ZIP Unicode Path Extra Field
"\x75\x70" + // size
decToHex(unicodePathExtraField.length, 2) + // content
unicodePathExtraField;
}
if (useUTF8ForComment) {
unicodeCommentExtraField = // Version
decToHex(1, 1) + // CommentCRC32
decToHex(crc32(encodedComment), 4) + // UnicodeName
utfEncodedComment;
extraFields += // Info-ZIP Unicode Path Extra Field
"\x75\x63" + // size
decToHex(unicodeCommentExtraField.length, 2) + // content
unicodeCommentExtraField;
}
var header = ""; // version needed to extract
header += "\x0A\x00"; // general purpose bit flag
header += decToHex(bitflag, 2); // compression method
header += compression.magic; // last mod file time
header += decToHex(dosTime, 2); // last mod file date
header += decToHex(dosDate, 2); // crc-32
header += decToHex(dataInfo.crc32, 4); // compressed size
header += decToHex(dataInfo.compressedSize, 4); // uncompressed size
header += decToHex(dataInfo.uncompressedSize, 4); // file name length
header += decToHex(encodedFileName.length, 2); // extra field length
header += decToHex(extraFields.length, 2);
var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields;
var dirRecord = signature.CENTRAL_FILE_HEADER + // version made by (00: DOS)
decToHex(versionMadeBy, 2) + // file header (common to file and central directory)
header + // file comment length
decToHex(encodedComment.length, 2) + // disk number start
"\x00\x00" + // internal file attributes TODO
"\x00\x00" + // external file attributes
decToHex(extFileAttr, 4) + // relative offset of local header
decToHex(offset, 4) + // file name
encodedFileName + // extra field
extraFields + // file comment
encodedComment;
return {
fileRecord: fileRecord,
dirRecord: dirRecord
};
};
/**
* Generate the EOCD record.
* @param {Number} entriesCount the number of entries in the zip file.
* @param {Number} centralDirLength the length (in bytes) of the central dir.
* @param {Number} localDirLength the length (in bytes) of the local dir.
* @param {String} comment the zip file comment as a binary string.
* @param {Function} encodeFileName the function to encode the comment.
* @return {String} the EOCD record.
*/
var generateCentralDirectoryEnd = function (entriesCount, centralDirLength, localDirLength, comment, encodeFileName) {
var dirEnd = "";
var encodedComment = utils.transformTo("string", encodeFileName(comment)); // end of central dir signature
dirEnd = signature.CENTRAL_DIRECTORY_END + // number of this disk
"\x00\x00" + // number of the disk with the start of the central directory
"\x00\x00" + // total number of entries in the central directory on this disk
decToHex(entriesCount, 2) + // total number of entries in the central directory
decToHex(entriesCount, 2) + // size of the central directory 4 bytes
decToHex(centralDirLength, 4) + // offset of start of central directory with respect to the starting disk number
decToHex(localDirLength, 4) + // .ZIP file comment length
decToHex(encodedComment.length, 2) + // .ZIP file comment
encodedComment;
return dirEnd;
};
/**
* Generate data descriptors for a file entry.
* @param {Object} streamInfo the hash generated by a worker, containing information
* on the file entry.
* @return {String} the data descriptors.
*/
var generateDataDescriptors = function (streamInfo) {
var descriptor = "";
descriptor = signature.DATA_DESCRIPTOR + // crc-32 4 bytes
decToHex(streamInfo['crc32'], 4) + // compressed size 4 bytes
decToHex(streamInfo['compressedSize'], 4) + // uncompressed size 4 bytes
decToHex(streamInfo['uncompressedSize'], 4);
return descriptor;
};
/**
* A worker to concatenate other workers to create a zip file.
* @param {Boolean} streamFiles `true` to stream the content of the files,
* `false` to accumulate it.
* @param {String} comment the comment to use.
* @param {String} platform the platform to use, "UNIX" or "DOS".
* @param {Function} encodeFileName the function to encode file names and comments.
*/
function ZipFileWorker(streamFiles, comment, platform, encodeFileName) {
GenericWorker.call(this, "ZipFileWorker"); // The number of bytes written so far. This doesn't count accumulated chunks.
this.bytesWritten = 0; // The comment of the zip file
this.zipComment = comment; // The platform "generating" the zip file.
this.zipPlatform = platform; // the function to encode file names and comments.
this.encodeFileName = encodeFileName; // Should we stream the content of the files ?
this.streamFiles = streamFiles; // If `streamFiles` is false, we will need to accumulate the content of the
// files to calculate sizes / crc32 (and write them *before* the content).
// This boolean indicates if we are accumulating chunks (it will change a lot
// during the lifetime of this worker).
this.accumulate = false; // The buffer receiving chunks when accumulating content.
this.contentBuffer = []; // The list of generated directory records.
this.dirRecords = []; // The offset (in bytes) from the beginning of the zip file for the current source.
this.currentSourceOffset = 0; // The total number of entries in this zip file.
this.entriesCount = 0; // the name of the file currently being added, null when handling the end of the zip file.
// Used for the emitted metadata.
this.currentFile = null;
this._sources = [];
}
utils.inherits(ZipFileWorker, GenericWorker);
/**
* @see GenericWorker.push
*/
ZipFileWorker.prototype.push = function (chunk) {
var currentFilePercent = chunk.meta.percent || 0;
var entriesCount = this.entriesCount;
var remainingFiles = this._sources.length;
if (this.accumulate) {
this.contentBuffer.push(chunk);
} else {
this.bytesWritten += chunk.data.length;
GenericWorker.prototype.push.call(this, {
data: chunk.data,
meta: {
currentFile: this.currentFile,
percent: entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100
}
});
}
};
/**
* The worker started a new source (an other worker).
* @param {Object} streamInfo the streamInfo object from the new source.
*/
ZipFileWorker.prototype.openedSource = function (streamInfo) {
this.currentSourceOffset = this.bytesWritten;
this.currentFile = streamInfo['file'].name;
var streamedContent = this.streamFiles && !streamInfo['file'].dir; // don't stream folders (because they don't have any content)
if (streamedContent) {
var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
this.push({
data: record.fileRecord,
meta: {
percent: 0
}
});
} else {
// we need to wait for the whole file before pushing anything
this.accumulate = true;
}
};
/**
* The worker finished a source (an other worker).
* @param {Object} streamInfo the streamInfo object from the finished source.
*/
ZipFileWorker.prototype.closedSource = function (streamInfo) {
this.accumulate = false;
var streamedContent = this.streamFiles && !streamInfo['file'].dir;
var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);
this.dirRecords.push(record.dirRecord);
if (streamedContent) {
// after the streamed file, we put data descriptors
this.push({
data: generateDataDescriptors(streamInfo),
meta: {
percent: 100
}
});
} else {
// the content wasn't streamed, we need to push everything now
// first the file record, then the content
this.push({
data: record.fileRecord,
meta: {
percent: 0
}
});
while (this.contentBuffer.length) {
this.push(this.contentBuffer.shift());
}
}
this.currentFile = null;
};
/**
* @see GenericWorker.flush
*/
ZipFileWorker.prototype.flush = function () {
var localDirLength = this.bytesWritten;
for (var i = 0; i < this.dirRecords.length; i++) {
this.push({
data: this.dirRecords[i],
meta: {
percent: 100
}
});
}
var centralDirLength = this.bytesWritten - localDirLength;
var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName);
this.push({
data: dirEnd,
meta: {
percent: 100
}
});
};
/**
* Prepare the next source to be read.
*/
ZipFileWorker.prototype.prepareNextSource = function () {
this.previous = this._sources.shift();
this.openedSource(this.previous.streamInfo);
if (this.isPaused) {
this.previous.pause();
} else {
this.previous.resume();
}
};
/**
* @see GenericWorker.registerPrevious
*/
ZipFileWorker.prototype.registerPrevious = function (previous) {
this._sources.push(previous);
var self = this;
previous.on('data', function (chunk) {
self.processChunk(chunk);
});
previous.on('end', function () {
self.closedSource(self.previous.streamInfo);
if (self._sources.length) {
self.prepareNextSource();
} else {
self.end();
}
});
previous.on('error', function (e) {
self.error(e);
});
return this;
};
/**
* @see GenericWorker.resume
*/
ZipFileWorker.prototype.resume = function () {
if (!GenericWorker.prototype.resume.call(this)) {
return false;
}
if (!this.previous && this._sources.length) {
this.prepareNextSource();
return true;
}
if (!this.previous && !this._sources.length && !this.generatedError) {
this.end();
return true;
}
};
/**
* @see GenericWorker.error
*/
ZipFileWorker.prototype.error = function (e) {
var sources = this._sources;
if (!GenericWorker.prototype.error.call(this, e)) {
return false;
}
for (var i = 0; i < sources.length; i++) {
try {
sources[i].error(e);
} catch (e) {// the `error` exploded, nothing to do
}
}
return true;
};
/**
* @see GenericWorker.lock
*/
ZipFileWorker.prototype.lock = function () {
GenericWorker.prototype.lock.call(this);
var sources = this._sources;
for (var i = 0; i < sources.length; i++) {
sources[i].lock();
}
};
exports = ZipFileWorker;
return exports;
} | the_stack |
import { bigint_asm, bigintresult } from './bigint.asm';
import { string_to_bytes } from '../other/utils';
import { IllegalArgumentError } from '../other/errors';
import { BigNumber_extGCD, Number_extGCD } from './extgcd';
import { getRandomValues } from '../other/get-random-values';
///////////////////////////////////////////////////////////////////////////////
export const _bigint_stdlib = { Uint32Array: Uint32Array, Math: Math };
export const _bigint_heap = new Uint32Array(0x100000);
export let _bigint_asm: bigintresult;
function _half_imul(a: number, b: number) {
return (a * b) | 0;
}
if (_bigint_stdlib.Math.imul === undefined) {
_bigint_stdlib.Math.imul = _half_imul;
_bigint_asm = bigint_asm(_bigint_stdlib, null, _bigint_heap.buffer);
delete _bigint_stdlib.Math.imul;
} else {
_bigint_asm = bigint_asm(_bigint_stdlib, null, _bigint_heap.buffer);
}
///////////////////////////////////////////////////////////////////////////////
const _BigNumber_ZERO_limbs = new Uint32Array(0);
export class BigNumber {
public limbs!: Uint32Array;
public bitLength!: number;
public sign!: number;
static extGCD = BigNumber_extGCD;
static ZERO = BigNumber.fromNumber(0);
static ONE = BigNumber.fromNumber(1);
static fromString(str: string): BigNumber {
const bytes = string_to_bytes(str);
return new BigNumber(bytes);
}
static fromNumber(num: number): BigNumber {
let limbs = _BigNumber_ZERO_limbs;
let bitlen = 0;
let sign = 0;
var absnum = Math.abs(num);
if (absnum > 0xffffffff) {
limbs = new Uint32Array(2);
limbs[0] = absnum | 0;
limbs[1] = (absnum / 0x100000000) | 0;
bitlen = 52;
} else if (absnum > 0) {
limbs = new Uint32Array(1);
limbs[0] = absnum;
bitlen = 32;
} else {
limbs = _BigNumber_ZERO_limbs;
bitlen = 0;
}
sign = num < 0 ? -1 : 1;
return BigNumber.fromConfig({ limbs, bitLength: bitlen, sign });
}
static fromArrayBuffer(buffer: ArrayBuffer): BigNumber {
return new BigNumber(new Uint8Array(buffer));
}
static fromConfig(obj: { limbs: Uint32Array; bitLength: number; sign: number }): BigNumber {
const bn = new BigNumber();
bn.limbs = new Uint32Array(obj.limbs);
bn.bitLength = obj.bitLength;
bn.sign = obj.sign;
return bn;
}
constructor(num?: Uint8Array) {
let limbs = _BigNumber_ZERO_limbs;
let bitlen = 0;
let sign = 0;
if (num === undefined) {
// do nothing
} else {
for (var i = 0; !num[i]; i++);
bitlen = (num.length - i) * 8;
if (!bitlen) return BigNumber.ZERO;
limbs = new Uint32Array((bitlen + 31) >> 5);
for (var j = num.length - 4; j >= i; j -= 4) {
limbs[(num.length - 4 - j) >> 2] = (num[j] << 24) | (num[j + 1] << 16) | (num[j + 2] << 8) | num[j + 3];
}
if (i - j === 3) {
limbs[limbs.length - 1] = num[i];
} else if (i - j === 2) {
limbs[limbs.length - 1] = (num[i] << 8) | num[i + 1];
} else if (i - j === 1) {
limbs[limbs.length - 1] = (num[i] << 16) | (num[i + 1] << 8) | num[i + 2];
}
sign = 1;
}
this.limbs = limbs;
this.bitLength = bitlen;
this.sign = sign;
}
toString(radix: number): string {
radix = radix || 16;
const limbs = this.limbs;
const bitlen = this.bitLength;
let str = '';
if (radix === 16) {
// FIXME clamp last limb to (bitlen % 32)
for (var i = ((bitlen + 31) >> 5) - 1; i >= 0; i--) {
var h = limbs[i].toString(16);
str += '00000000'.substr(h.length);
str += h;
}
str = str.replace(/^0+/, '');
if (!str.length) str = '0';
} else {
throw new IllegalArgumentError('bad radix');
}
if (this.sign < 0) str = '-' + str;
return str;
}
toBytes(): Uint8Array {
const bitlen = this.bitLength;
const limbs = this.limbs;
if (bitlen === 0) return new Uint8Array(0);
const bytelen = (bitlen + 7) >> 3;
const bytes = new Uint8Array(bytelen);
for (let i = 0; i < bytelen; i++) {
let j = bytelen - i - 1;
bytes[i] = limbs[j >> 2] >> ((j & 3) << 3);
}
return bytes;
}
/**
* Downgrade to Number
*/
valueOf(): number {
const limbs = this.limbs;
const bits = this.bitLength;
const sign = this.sign;
if (!sign) return 0;
if (bits <= 32) return sign * (limbs[0] >>> 0);
if (bits <= 52) return sign * (0x100000000 * (limbs[1] >>> 0) + (limbs[0] >>> 0));
// normalization
let i,
l,
e = 0;
for (i = limbs.length - 1; i >= 0; i--) {
if ((l = limbs[i]) === 0) continue;
while (((l << e) & 0x80000000) === 0) e++;
break;
}
if (i === 0) return sign * (limbs[0] >>> 0);
return (
sign *
(0x100000 * (((limbs[i] << e) | (e ? limbs[i - 1] >>> (32 - e) : 0)) >>> 0) +
(((limbs[i - 1] << e) | (e && i > 1 ? limbs[i - 2] >>> (32 - e) : 0)) >>> 12)) *
Math.pow(2, 32 * i - e - 52)
);
}
clamp(b: number): BigNumber {
const limbs = this.limbs;
const bitlen = this.bitLength;
// FIXME check b is number and in a valid range
if (b >= bitlen) return this;
const clamped = new BigNumber();
let n = (b + 31) >> 5;
let k = b % 32;
clamped.limbs = new Uint32Array(limbs.subarray(0, n));
clamped.bitLength = b;
clamped.sign = this.sign;
if (k) clamped.limbs[n - 1] &= -1 >>> (32 - k);
return clamped;
}
slice(f: number, b?: number): BigNumber {
const limbs = this.limbs;
const bitlen = this.bitLength;
if (f < 0) throw new RangeError('TODO');
if (f >= bitlen) return BigNumber.ZERO;
if (b === undefined || b > bitlen - f) b = bitlen - f;
const sliced = new BigNumber();
let n = f >> 5;
let m = (f + b + 31) >> 5;
let l = (b + 31) >> 5;
let t = f % 32;
let k = b % 32;
const slimbs = new Uint32Array(l);
if (t) {
for (var i = 0; i < m - n - 1; i++) {
slimbs[i] = (limbs[n + i] >>> t) | (limbs[n + i + 1] << (32 - t));
}
slimbs[i] = limbs[n + i] >>> t;
} else {
slimbs.set(limbs.subarray(n, m));
}
if (k) {
slimbs[l - 1] &= -1 >>> (32 - k);
}
sliced.limbs = slimbs;
sliced.bitLength = b;
sliced.sign = this.sign;
return sliced;
}
negate(): BigNumber {
const negative = new BigNumber();
negative.limbs = this.limbs;
negative.bitLength = this.bitLength;
negative.sign = -1 * this.sign;
return negative;
}
compare(that: BigNumber): number {
var alimbs = this.limbs,
alimbcnt = alimbs.length,
blimbs = that.limbs,
blimbcnt = blimbs.length,
z = 0;
if (this.sign < that.sign) return -1;
if (this.sign > that.sign) return 1;
_bigint_heap.set(alimbs, 0);
_bigint_heap.set(blimbs, alimbcnt);
z = _bigint_asm.cmp(0, alimbcnt << 2, alimbcnt << 2, blimbcnt << 2);
return z * this.sign;
}
add(that: BigNumber): BigNumber {
if (!this.sign) return that;
if (!that.sign) return this;
var abitlen = this.bitLength,
alimbs = this.limbs,
alimbcnt = alimbs.length,
asign = this.sign,
bbitlen = that.bitLength,
blimbs = that.limbs,
blimbcnt = blimbs.length,
bsign = that.sign,
rbitlen,
rlimbcnt,
rsign,
rof,
result = new BigNumber();
rbitlen = (abitlen > bbitlen ? abitlen : bbitlen) + (asign * bsign > 0 ? 1 : 0);
rlimbcnt = (rbitlen + 31) >> 5;
_bigint_asm.sreset();
var pA = _bigint_asm.salloc(alimbcnt << 2),
pB = _bigint_asm.salloc(blimbcnt << 2),
pR = _bigint_asm.salloc(rlimbcnt << 2);
_bigint_asm.z(pR - pA + (rlimbcnt << 2), 0, pA);
_bigint_heap.set(alimbs, pA >> 2);
_bigint_heap.set(blimbs, pB >> 2);
if (asign * bsign > 0) {
_bigint_asm.add(pA, alimbcnt << 2, pB, blimbcnt << 2, pR, rlimbcnt << 2);
rsign = asign;
} else if (asign > bsign) {
rof = _bigint_asm.sub(pA, alimbcnt << 2, pB, blimbcnt << 2, pR, rlimbcnt << 2);
rsign = rof ? bsign : asign;
} else {
rof = _bigint_asm.sub(pB, blimbcnt << 2, pA, alimbcnt << 2, pR, rlimbcnt << 2);
rsign = rof ? asign : bsign;
}
if (rof) _bigint_asm.neg(pR, rlimbcnt << 2, pR, rlimbcnt << 2);
if (_bigint_asm.tst(pR, rlimbcnt << 2) === 0) return BigNumber.ZERO;
result.limbs = new Uint32Array(_bigint_heap.subarray(pR >> 2, (pR >> 2) + rlimbcnt));
result.bitLength = rbitlen;
result.sign = rsign;
return result;
}
subtract(that: BigNumber): BigNumber {
return this.add(that.negate());
}
square(): BigNumber {
if (!this.sign) return BigNumber.ZERO;
var abitlen = this.bitLength,
alimbs = this.limbs,
alimbcnt = alimbs.length,
rbitlen,
rlimbcnt,
result = new BigNumber();
rbitlen = abitlen << 1;
rlimbcnt = (rbitlen + 31) >> 5;
_bigint_asm.sreset();
var pA = _bigint_asm.salloc(alimbcnt << 2),
pR = _bigint_asm.salloc(rlimbcnt << 2);
_bigint_asm.z(pR - pA + (rlimbcnt << 2), 0, pA);
_bigint_heap.set(alimbs, pA >> 2);
_bigint_asm.sqr(pA, alimbcnt << 2, pR);
result.limbs = new Uint32Array(_bigint_heap.subarray(pR >> 2, (pR >> 2) + rlimbcnt));
result.bitLength = rbitlen;
result.sign = 1;
return result;
}
divide(that: BigNumber): { quotient: BigNumber; remainder: BigNumber } {
var abitlen = this.bitLength,
alimbs = this.limbs,
alimbcnt = alimbs.length,
bbitlen = that.bitLength,
blimbs = that.limbs,
blimbcnt = blimbs.length,
qlimbcnt,
rlimbcnt,
quotient = BigNumber.ZERO,
remainder = BigNumber.ZERO;
_bigint_asm.sreset();
var pA = _bigint_asm.salloc(alimbcnt << 2),
pB = _bigint_asm.salloc(blimbcnt << 2),
pQ = _bigint_asm.salloc(alimbcnt << 2);
_bigint_asm.z(pQ - pA + (alimbcnt << 2), 0, pA);
_bigint_heap.set(alimbs, pA >> 2);
_bigint_heap.set(blimbs, pB >> 2);
_bigint_asm.div(pA, alimbcnt << 2, pB, blimbcnt << 2, pQ);
qlimbcnt = _bigint_asm.tst(pQ, alimbcnt << 2) >> 2;
if (qlimbcnt) {
quotient = new BigNumber();
quotient.limbs = new Uint32Array(_bigint_heap.subarray(pQ >> 2, (pQ >> 2) + qlimbcnt));
quotient.bitLength = abitlen < qlimbcnt << 5 ? abitlen : qlimbcnt << 5;
quotient.sign = this.sign * that.sign;
}
rlimbcnt = _bigint_asm.tst(pA, blimbcnt << 2) >> 2;
if (rlimbcnt) {
remainder = new BigNumber();
remainder.limbs = new Uint32Array(_bigint_heap.subarray(pA >> 2, (pA >> 2) + rlimbcnt));
remainder.bitLength = bbitlen < rlimbcnt << 5 ? bbitlen : rlimbcnt << 5;
remainder.sign = this.sign;
}
return {
quotient: quotient,
remainder: remainder,
};
}
multiply(that: BigNumber): BigNumber {
if (!this.sign || !that.sign) return BigNumber.ZERO;
var abitlen = this.bitLength,
alimbs = this.limbs,
alimbcnt = alimbs.length,
bbitlen = that.bitLength,
blimbs = that.limbs,
blimbcnt = blimbs.length,
rbitlen,
rlimbcnt,
result = new BigNumber();
rbitlen = abitlen + bbitlen;
rlimbcnt = (rbitlen + 31) >> 5;
_bigint_asm.sreset();
var pA = _bigint_asm.salloc(alimbcnt << 2),
pB = _bigint_asm.salloc(blimbcnt << 2),
pR = _bigint_asm.salloc(rlimbcnt << 2);
_bigint_asm.z(pR - pA + (rlimbcnt << 2), 0, pA);
_bigint_heap.set(alimbs, pA >> 2);
_bigint_heap.set(blimbs, pB >> 2);
_bigint_asm.mul(pA, alimbcnt << 2, pB, blimbcnt << 2, pR, rlimbcnt << 2);
result.limbs = new Uint32Array(_bigint_heap.subarray(pR >> 2, (pR >> 2) + rlimbcnt));
result.sign = this.sign * that.sign;
result.bitLength = rbitlen;
return result;
}
public isMillerRabinProbablePrime(rounds: number): boolean {
var t = BigNumber.fromConfig(this),
s = 0;
t.limbs[0] -= 1;
while (t.limbs[s >> 5] === 0) s += 32;
while (((t.limbs[s >> 5] >> (s & 31)) & 1) === 0) s++;
t = t.slice(s);
var m = new Modulus(this),
m1 = this.subtract(BigNumber.ONE),
a = BigNumber.fromConfig(this),
l = this.limbs.length - 1;
while (a.limbs[l] === 0) l--;
while (--rounds >= 0) {
getRandomValues(a.limbs);
if (a.limbs[0] < 2) a.limbs[0] += 2;
while (a.compare(m1) >= 0) a.limbs[l] >>>= 1;
var x = m.power(a, t);
if (x.compare(BigNumber.ONE) === 0) continue;
if (x.compare(m1) === 0) continue;
var c = s;
while (--c > 0) {
x = x.square().divide(m).remainder;
if (x.compare(BigNumber.ONE) === 0) return false;
if (x.compare(m1) === 0) break;
}
if (c === 0) return false;
}
return true;
}
isProbablePrime(paranoia: number = 80): boolean {
var limbs = this.limbs;
var i = 0;
// Oddity test
// (50% false positive probability)
if ((limbs[0] & 1) === 0) return false;
if (paranoia <= 1) return true;
// Magic divisors (3, 5, 17) test
// (~25% false positive probability)
var s3 = 0,
s5 = 0,
s17 = 0;
for (i = 0; i < limbs.length; i++) {
var l3 = limbs[i];
while (l3) {
s3 += l3 & 3;
l3 >>>= 2;
}
var l5 = limbs[i];
while (l5) {
s5 += l5 & 3;
l5 >>>= 2;
s5 -= l5 & 3;
l5 >>>= 2;
}
var l17 = limbs[i];
while (l17) {
s17 += l17 & 15;
l17 >>>= 4;
s17 -= l17 & 15;
l17 >>>= 4;
}
}
if (!(s3 % 3) || !(s5 % 5) || !(s17 % 17)) return false;
if (paranoia <= 2) return true;
// Miller-Rabin test
// (≤ 4^(-k) false positive probability)
return this.isMillerRabinProbablePrime(paranoia >>> 1);
}
}
export class Modulus extends BigNumber {
// @ts-ignore
private comodulus!: BigNumber;
private comodulusRemainder!: BigNumber;
private comodulusRemainderSquare!: BigNumber;
private coefficient!: number;
constructor(number: BigNumber) {
super();
this.limbs = number.limbs;
this.bitLength = number.bitLength;
this.sign = number.sign;
if (this.valueOf() < 1) throw new RangeError();
if (this.bitLength <= 32) return;
let comodulus: BigNumber;
if (this.limbs[0] & 1) {
const bitlen = ((this.bitLength + 31) & -32) + 1;
const limbs = new Uint32Array((bitlen + 31) >> 5);
limbs[limbs.length - 1] = 1;
comodulus = new BigNumber();
comodulus.sign = 1;
comodulus.bitLength = bitlen;
comodulus.limbs = limbs;
const k = Number_extGCD(0x100000000, this.limbs[0]).y;
this.coefficient = k < 0 ? -k : 0x100000000 - k;
} else {
/**
* TODO even modulus reduction
* Modulus represented as `N = 2^U * V`, where `V` is odd and thus `GCD(2^U, V) = 1`.
* Calculation `A = TR' mod V` is made as for odd modulo using Montgomery method.
* Calculation `B = TR' mod 2^U` is easy as modulus is a power of 2.
* Using Chinese Remainder Theorem and Garner's Algorithm restore `TR' mod N` from `A` and `B`.
*/
return;
}
this.comodulus = comodulus;
this.comodulusRemainder = comodulus.divide(this).remainder;
this.comodulusRemainderSquare = comodulus.square().divide(this).remainder;
}
/**
* Modular reduction
*/
reduce(a: BigNumber): BigNumber {
if (a.bitLength <= 32 && this.bitLength <= 32) return BigNumber.fromNumber(a.valueOf() % this.valueOf());
if (a.compare(this) < 0) return a;
return a.divide(this).remainder;
}
/**
* Modular inverse
*/
inverse(a: BigNumber): BigNumber {
a = this.reduce(a);
const r = BigNumber_extGCD(this, a);
if (r.gcd.valueOf() !== 1) throw new Error('GCD is not 1');
if (r.y.sign < 0) return r.y.add(this).clamp(this.bitLength);
return r.y;
}
/**
* Modular exponentiation
*/
power(g: BigNumber, e: BigNumber): BigNumber {
// count exponent set bits
let c = 0;
for (let i = 0; i < e.limbs.length; i++) {
let t = e.limbs[i];
while (t) {
if (t & 1) c++;
t >>>= 1;
}
}
// window size parameter
let k = 8;
if (e.bitLength <= 4536) k = 7;
if (e.bitLength <= 1736) k = 6;
if (e.bitLength <= 630) k = 5;
if (e.bitLength <= 210) k = 4;
if (e.bitLength <= 60) k = 3;
if (e.bitLength <= 12) k = 2;
if (c <= 1 << (k - 1)) k = 1;
// montgomerize base
g = Modulus._Montgomery_reduce(this.reduce(g).multiply(this.comodulusRemainderSquare), this);
// precompute odd powers
const g2 = Modulus._Montgomery_reduce(g.square(), this),
gn = new Array(1 << (k - 1));
gn[0] = g;
gn[1] = Modulus._Montgomery_reduce(g.multiply(g2), this);
for (let i = 2; i < 1 << (k - 1); i++) {
gn[i] = Modulus._Montgomery_reduce(gn[i - 1].multiply(g2), this);
}
// perform exponentiation
const u = this.comodulusRemainder;
let r = u;
for (let i = e.limbs.length - 1; i >= 0; i--) {
let t = e.limbs[i];
for (let j = 32; j > 0; ) {
if (t & 0x80000000) {
let n = t >>> (32 - k),
l = k;
while ((n & 1) === 0) {
n >>>= 1;
l--;
}
var m = gn[n >>> 1];
while (n) {
n >>>= 1;
if (r !== u) r = Modulus._Montgomery_reduce(r.square(), this);
}
r = r !== u ? Modulus._Montgomery_reduce(r.multiply(m), this) : m;
(t <<= l), (j -= l);
} else {
if (r !== u) r = Modulus._Montgomery_reduce(r.square(), this);
(t <<= 1), j--;
}
}
}
// de-montgomerize result
return Modulus._Montgomery_reduce(r, this);
}
static _Montgomery_reduce(a: BigNumber, n: Modulus): BigNumber {
const alimbs = a.limbs;
const alimbcnt = alimbs.length;
const nlimbs = n.limbs;
const nlimbcnt = nlimbs.length;
const y = n.coefficient;
_bigint_asm.sreset();
const pA = _bigint_asm.salloc(alimbcnt << 2),
pN = _bigint_asm.salloc(nlimbcnt << 2),
pR = _bigint_asm.salloc(nlimbcnt << 2);
_bigint_asm.z(pR - pA + (nlimbcnt << 2), 0, pA);
_bigint_heap.set(alimbs, pA >> 2);
_bigint_heap.set(nlimbs, pN >> 2);
_bigint_asm.mredc(pA, alimbcnt << 2, pN, nlimbcnt << 2, y, pR);
const result = new BigNumber();
result.limbs = new Uint32Array(_bigint_heap.subarray(pR >> 2, (pR >> 2) + nlimbcnt));
result.bitLength = n.bitLength;
result.sign = 1;
return result;
}
} | the_stack |
import { IEquals, hashCodeOfString, NotImplementedError, Throwable } from "funfix-core"
import { Duration } from "./time"
import { ICancelable, Cancelable, IAssignCancelable, MultiAssignCancelable } from "./cancelable"
import { DynamicRef } from "./ref"
import { arrayBSearchInsertPos, maxPowerOf2, nextPowerOf2 } from "./internals"
/**
* A `Scheduler` is an execution context that can execute units of
* work asynchronously, with a delay or periodically.
*
* It replaces Javascript's `setTimeout`, which is desirable due to
* the provided utilities and because special behavior might be needed
* in certain specialized contexts (e.g. tests), even if the
* [[Scheduler.global]] reference is implemented with `setTimeout`.
*/
export abstract class Scheduler {
/**
* The {@link ExecutionModel} is a specification of how run-loops
* and producers should behave in regards to executing tasks
* either synchronously or asynchronously.
*/
public readonly executionModel: ExecutionModel
/**
* Index of the current cycle, incremented automatically (modulo
* the batch size) when doing execution by means of
* {@link Scheduler.executeBatched} and the `Scheduler` is
* configured with {@link ExecutionModel.batched}.
*
* When observed as being zero, it means an async boundary just
* happened.
*/
batchIndex: number = 0
/**
* @param em the {@link ExecutionModel} to use for
* {@link Scheduler.executionModel}, should default to
* {@link ExecutionModel.global}
*/
protected constructor(em: ExecutionModel) {
this.executionModel = em
// Building an optimized executeBatched
switch (em.type) {
case "alwaysAsync":
this.executeBatched = this.executeAsync
break
case "synchronous":
this.executeBatched = this.trampoline
break
case "batched":
const modulus = em.recommendedBatchSize - 1
this.executeBatched = (r) => {
const next = (this.batchIndex + 1) & modulus
if (next) {
this.batchIndex = next
return this.trampoline(r)
} else {
return this.executeAsync(r)
}
}
}
}
/**
* Executes tasks in batches, according to the rules set by the
* given {@link ExecutionModel}.
*
* The rules, depending on the chosen `ExecutionModel`:
*
* - if `synchronous`, then all tasks are executed with
* {@link Scheduler.trampoline}
* - if `asynchronous`, then all tasks are executed with
* {@link Scheduler.executeAsync}
* - if `batched(n)`, then `n` tasks will be executed
* with `Scheduler.trampoline` and then the next execution
* will force an asynchronous boundary by means of
* `Scheduler.executeAsync`
*
* Thus, in case of batched execution, an internal counter gets
* incremented to keep track of how many tasks where executed
* immediately (trampolined), a counter that's reset when reaching
* the threshold or when an `executeAsync` happens.
*/
public readonly executeBatched!: (runnable: () => void) => void
/**
* Schedules the given `command` for async execution.
*
* In [[GlobalScheduler]] this method uses
* [setImmediate]{@link https://developer.mozilla.org/en/docs/Web/API/Window/setImmediate}
* when available. But given that `setImmediate` is a very
* non-standard operation that is currently implemented only by
* IExplorer and Node.js, on non-supporting environments we fallback
* on `setTimeout`. See
* [the W3C proposal]{@link https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/setImmediate/Overview.html}.
*
* @param runnable is the thunk to execute asynchronously
*/
public abstract executeAsync(runnable: () => void): void
/**
* Execute the given `runnable` on the current call stack by means
* of a "trampoline", preserving stack safety.
*
* This is an alternative to {@link executeAsync} for triggering
* light asynchronous boundaries.
*/
public abstract trampoline(runnable: () => void): void
/** Reports that an asynchronous computation failed. */
public abstract reportFailure(e: Throwable): void
/**
* Returns the current time in milliseconds. Note that while the
* unit of time of the return value is a millisecond, the
* granularity of the value depends on the underlying operating
* system and may be larger. For example, many operating systems
* measure time in units of tens of milliseconds.
*
* It's the equivalent of `Date.now()`. When wanting to measure
* time, do not use `Date.now()` directly, prefer this method
* instead, because then it can be mocked for testing purposes,
* or overridden for better precision.
*/
public abstract currentTimeMillis(): number
/**
* Schedules a task to run in the future, after `delay`.
*
* For example the following schedules a message to be printed to
* standard output after 5 minutes:
*
* ```typescript
* const task =
* scheduler.scheduleOnce(Duration.minutes(5), () => {
* console.log("Hello, world!")
* })
*
* // later if you change your mind ... task.cancel()
* ```
*
* @param delay is the time to wait until the execution happens; if
* specified as a `number`, then it's interpreted as milliseconds;
* for readability, prefer passing [[Duration]] values
* @param runnable is the callback to be executed
*
* @return a [[Cancelable]] that can be used to cancel the created
* task before execution.
*/
public abstract scheduleOnce(delay: number | Duration, runnable: () => void): ICancelable
/**
* Given a function that will receive the underlying
* {@link ExecutionModel}, returns a new {@link Scheduler}
* reference, based on the source that exposes the new
* `ExecutionModel` value when queried by means of the
* {@link Scheduler.executionModel} property.
*
* This method enables reusing global scheduler references in
* a local scope, but with a modified execution model to inject.
*
* The contract of this method (things you can rely on):
*
* 1. the source `Scheduler` must not be modified in any way
* 2. the implementation should wrap the source efficiently, such
* that the result mirrors the implementation of the source
* `Scheduler` in every way except for the execution model
*
* Sample:
*
* ```typescript
* import { Scheduler, ExecutionModel } from "funfix"
*
* const scheduler = Schedule.global()
* .withExecutionModel(ExecutionModel.trampolined())
* ```
*/
public abstract withExecutionModel(em: ExecutionModel): Scheduler
/**
* Schedules for execution a periodic task that is first executed
* after the given initial delay and subsequently with the given
* delay between the termination of one execution and the
* commencement of the next.
*
* For example the following schedules a message to be printed to
* standard output every 10 seconds with an initial delay of 5
* seconds:
*
* ```typescript
* const task =
* s.scheduleWithFixedDelay(Duration.seconds(5), Duration.seconds(10), () => {
* console.log("repeated message")
* })
*
* // later if you change your mind ...
* task.cancel()
* ```
*
* @param initialDelay is the time to wait until the first execution happens
* @param delay is the time to wait between 2 successive executions of the task
* @param runnable is the thunk to be executed
* @return a cancelable that can be used to cancel the execution of
* this repeated task at any time.
*/
public scheduleWithFixedDelay(initialDelay: number | Duration, delay: number | Duration, runnable: () => void): ICancelable {
const loop = (self: Scheduler, ref: IAssignCancelable, delayNow: number | Duration) =>
ref.update(self.scheduleOnce(delayNow, () => {
runnable()
loop(self, ref, delay)
}))
const task = MultiAssignCancelable.empty()
return loop(this, task, initialDelay)
}
/**
* Schedules a periodic task that becomes enabled first after the given
* initial delay, and subsequently with the given period. Executions will
* commence after `initialDelay` then `initialDelay + period`, then
* `initialDelay + 2 * period` and so on.
*
* If any execution of the task encounters an exception, subsequent executions
* are suppressed. Otherwise, the task will only terminate via cancellation or
* termination of the scheduler. If any execution of this task takes longer
* than its period, then subsequent executions may start late, but will not
* concurrently execute.
*
* For example the following schedules a message to be printed to standard
* output approximately every 10 seconds with an initial delay of 5 seconds:
*
* ```typescript
* const task =
* s.scheduleAtFixedRate(Duration.seconds(5), Duration.seconds(10), () => {
* console.log("repeated message")
* })
*
* // later if you change your mind ...
* task.cancel()
* ```
*
* @param initialDelay is the time to wait until the first execution happens
* @param period is the time to wait between 2 successive executions of the task
* @param runnable is the thunk to be executed
* @return a cancelable that can be used to cancel the execution of
* this repeated task at any time.
*/
public scheduleAtFixedRate(initialDelay: number | Duration, period: number | Duration, runnable: () => void): ICancelable {
const loop = (self: Scheduler, ref: IAssignCancelable, delayNowMs: number, periodMs: number) =>
ref.update(self.scheduleOnce(delayNowMs, () => {
// Benchmarking the duration of the runnable
const startAt = self.currentTimeMillis()
runnable()
// Calculating the next delay based on the current execution
const elapsedMs = self.currentTimeMillis() - startAt
const nextDelayMs = Math.max(0, periodMs - elapsedMs)
loop(self, ref, periodMs, nextDelayMs)
}))
const task = MultiAssignCancelable.empty()
return loop(this, task,
typeof initialDelay === "number" ? initialDelay : initialDelay.toMillis(),
typeof period === "number" ? period : period.toMillis()
)
}
/**
* Exposes a reusable [[GlobalScheduler]] reference by means of a
* {@link DynamicRef}, which allows for lexically scoped bindings to happen.
*
* ```typescript
* const myScheduler = new GlobalScheduler(false)
*
* Scheduler.global.bind(myScheduler, () => {
* Scheduler.global.get() // myScheduler
* })
*
* Scheduler.global.get() // default instance
* ```
*/
static readonly global: DynamicRef<Scheduler> =
DynamicRef.of(() => globalSchedulerRef)
}
/**
* The `ExecutionModel` is a specification for how potentially asynchronous
* run-loops should execute, imposed by the `Scheduler`.
*
* When executing tasks, a run-loop can always execute tasks
* asynchronously (by forking logical threads), or it can always
* execute them synchronously (same thread and call-stack, by
* using an internal trampoline), or it can do a mixed mode
* that executes tasks in batches before forking.
*
* The specification is considered a recommendation for how
* run loops should behave, but ultimately it's up to the client
* to choose the best execution model. This can be related to
* recursive loops or to events pushed into consumers.
*/
export class ExecutionModel implements IEquals<ExecutionModel> {
/**
* Recommended batch size used for breaking synchronous loops in
* asynchronous batches. When streaming value from a producer to
* a synchronous consumer it's recommended to break the streaming
* in batches as to not hold the current thread or run-loop
* indefinitely.
*
* This is rounded to the next power of 2, because then for
* applying the modulo operation we can just do:
*
* ```typescript
* const modulus = recommendedBatchSize - 1
* // ...
* nr = (nr + 1) & modulus
* ```
*/
public readonly recommendedBatchSize!: number
/**
* The type of the execution model, which can be:
*
* - `batched`: the default, specifying an mixed execution
* mode under which tasks are executed synchronously in
* batches up to a maximum size; after a batch of
* {@link recommendedBatchSize} is executed, the next
* execution should be asynchronous.
* - `synchronous`: specifies that execution should be
* synchronous (immediate / trampolined) for as long as
* possible.
* - `alwaysAsync`: specifies a run-loop should always do
* async execution of tasks, triggering asynchronous
* boundaries on each step.
*/
public type: "batched" | "synchronous" | "alwaysAsync"
private constructor(type: "batched" | "synchronous" | "alwaysAsync", batchSize?: number) {
this.type = type
switch (type) {
case "synchronous":
this.recommendedBatchSize = maxPowerOf2
break
case "alwaysAsync":
this.recommendedBatchSize = 1
break
case "batched":
this.recommendedBatchSize = nextPowerOf2(batchSize || 128)
break
}
}
/** Implements `IEquals.equals`. */
equals(other: ExecutionModel): boolean {
return this.type === other.type &&
this.recommendedBatchSize === other.recommendedBatchSize
}
/** Implements `IEquals.hashCode`. */
hashCode(): number {
return hashCodeOfString(this.type) * 47 + this.recommendedBatchSize
}
/**
* An {@link ExecutionModel} that specifies that execution should be
* synchronous (immediate, trampolined) for as long as possible.
*/
static synchronous(): ExecutionModel {
return new ExecutionModel("synchronous")
}
/**
* An {@link ExecutionModel} that specifies a run-loop should always do
* async execution of tasks, thus triggering asynchronous boundaries on
* each step.
*/
static alwaysAsync(): ExecutionModel {
return new ExecutionModel("alwaysAsync")
}
/**
* Returns an {@link ExecutionModel} that specifies a mixed execution
* mode under which tasks are executed synchronously in batches up to
* a maximum size, the `recommendedBatchSize`.
*
* After such a batch of {@link recommendedBatchSize} is executed, the
* next execution should have a forced asynchronous boundary.
*/
static batched(recommendedBatchSize?: number): ExecutionModel {
return new ExecutionModel("batched", recommendedBatchSize)
}
/**
* The default {@link ExecutionModel} that should be used whenever
* an execution model isn't explicitly specified.
*/
static readonly global: DynamicRef<ExecutionModel> =
DynamicRef.of(() => ExecutionModel.batched())
}
/**
* Internal trampoline implementation used for implementing
* {@link Scheduler.trampoline}.
*
* @final
* @hidden
*/
class Trampoline {
private readonly _reporter: (e: Throwable) => void
private readonly _queue: (() => void)[]
private _isActive: boolean
constructor(reporter: (e: Throwable) => void) {
this._isActive = false
this._queue = []
this._reporter = reporter
}
execute(r: () => void) {
if (!this._isActive) {
this.runLoop(r)
} else {
this._queue.push(r)
}
}
private runLoop(r: () => void) {
this._isActive = true
try {
let cursor: (() => void) | undefined = r
while (cursor) {
try { cursor() } catch (e) { this._reporter(e) }
cursor = this._queue.pop()
}
} finally {
this._isActive = false
}
}
}
/**
* `GlobalScheduler` is a [[Scheduler]] implementation based on Javascript's
* [setTimeout]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout}
* and (if available and configured)
* [setImmediate]{@link https://developer.mozilla.org/en/docs/Web/API/Window/setImmediate}.
*/
export class GlobalScheduler extends Scheduler {
/**
* If `true`, then `setImmediate` is used in `execute`.
*/
private readonly _useSetImmediate: boolean
/**
* {@link Trampoline} used for immediate execution in
* {@link Scheduler.trampoline}.
*/
private readonly _trampoline: Trampoline
/**
* @param canUseSetImmediate is a boolean informing the
* `GlobalScheduler` implementation that it can use the
* nonstandard `setImmediate` for scheduling asynchronous
* tasks without extra delays.
*
* @param em the {@link ExecutionModel} to use for
* {@link Scheduler.executionModel}, should default to
* {@link ExecutionModel.global}
*
* @param reporter is the reporter to use for reporting uncaught
* errors, defaults to `console.error`
*/
constructor(
canUseSetImmediate: boolean = false,
em: ExecutionModel = ExecutionModel.global.get(),
reporter?: (e: Throwable) => void) {
super(em)
if (reporter) this.reportFailure = reporter
this._trampoline = new Trampoline(this.reportFailure)
// tslint:disable:strict-type-predicates
this._useSetImmediate = (canUseSetImmediate || false) && (typeof setImmediate === "function")
this.executeAsync = this._useSetImmediate
? r => setImmediate(safeRunnable(r, this.reportFailure))
: r => setTimeout(safeRunnable(r, this.reportFailure))
}
/* istanbul ignore next */
executeAsync(runnable: () => void): void {
/* istanbul ignore next */
throw new NotImplementedError("Constructor of GlobalScheduler wasn't executed")
}
trampoline(runnable: () => void): void {
return this._trampoline.execute(runnable)
}
/* istanbul ignore next */
reportFailure(e: Throwable): void {
console.error(e)
}
currentTimeMillis(): number {
return Date.now()
}
scheduleOnce(delay: number | Duration, runnable: () => void): ICancelable {
const r = () => {
this.batchIndex = 0
try { runnable() } catch (e) { this.reportFailure(e) }
}
const ms = Math.max(0, Duration.of(delay).toMillis())
const task = setTimeout(r, ms)
return Cancelable.of(() => clearTimeout(task))
}
withExecutionModel(em: ExecutionModel) {
return new GlobalScheduler(this._useSetImmediate, em)
}
}
/**
* The `TestScheduler` is a {@link Scheduler} type meant for testing purposes,
* being capable of simulating asynchronous execution and the passage of time.
*
* Example:
*
* ```typescript
* const s = new TestScheduler()
*
* s.execute(() => { console.log("Hello, world!") })
*
* // Triggers actual execution
* s.tick()
*
* // Simulating delayed execution
* const task = s.scheduleOnce(Duration.seconds(10), () => {
* console.log("Hello, delayed!")
* })
*
* // We can cancel a delayed task if we want
* task.cancel()
*
* // Or we can execute it by moving the internal clock forward in time
* s.tick(Duration.seconds(10))
* ```
*/
export class TestScheduler extends Scheduler {
private _reporter: (error: any) => void
private _trampoline: Trampoline
private _stateRef?: TestSchedulerState
/**
* @param reporter is an optional function that will be called
* whenever {@link Scheduler.reportFailure} is invoked.
*
* @param em the {@link ExecutionModel} to use for
* the {@link Scheduler.executionModel}, defaults to
* `"synchronous"` for `TestScheduler`
*/
constructor(reporter?: (error: any) => void, em: ExecutionModel = ExecutionModel.synchronous()) {
super(em)
this._reporter = reporter || (_ => {})
this._trampoline = new Trampoline(this.reportFailure.bind(this))
}
private _state() {
if (!this._stateRef) {
this._stateRef = new TestSchedulerState()
this._stateRef.updateTasks([])
}
return this._stateRef
}
/**
* Returns a list of triggered errors, if any happened during
* the {@link tick} execution.
*/
public triggeredFailures(): Array<any> { return this._state().triggeredFailures }
/**
* Returns `true` if there are any tasks left to execute, `false`
* otherwise.
*/
public hasTasksLeft(): boolean { return this._state().tasks.length > 0 }
public executeAsync(runnable: () => void): void {
this._state().tasks.push([this._state().clock, runnable])
}
public trampoline(runnable: () => void): void {
this._trampoline.execute(runnable)
}
public reportFailure(e: Throwable): void {
this._state().triggeredFailures.push(e)
this._reporter(e)
}
public currentTimeMillis(): number {
return this._state().clock
}
public scheduleOnce(delay: number | Duration, runnable: () => void): ICancelable {
const d = Math.max(0, Duration.of(delay).toMillis())
const state = this._state()
const scheduleAt = state.clock + d
const insertAt = state.tasksSearch(-scheduleAt)
const ref: [number, () => void] = [scheduleAt, runnable]
state.tasks.splice(insertAt, 0, ref)
return Cancelable.of(() => {
const filtered: Array<[number, () => void]> = []
for (const e of state.tasks) {
if (e !== ref) filtered.push(e)
}
state.updateTasks(filtered)
})
}
public withExecutionModel(em: ExecutionModel): TestScheduler {
const ec2 = new TestScheduler(this._reporter, em)
ec2._stateRef = this._state()
return ec2
}
/**
* Executes the current batch of tasks that are pending, relative
* to [currentTimeMillis]{@link TestScheduler.currentTimeMillis}.
*
* ```typescript
* const s = new TestScheduler()
*
* // Immediate execution
* s.executeAsync(() => console.log("A"))
* s.executeAsync(() => console.log("B"))
* // Delay with 1 second from now
* s.scheduleOnce(Duration.seconds(1), () => console.log("C"))
* s.scheduleOnce(Duration.seconds(1), () => console.log("D"))
* // Delay with 2 seconds from now
* s.scheduleOnce(Duration.seconds(2), () => console.log("E"))
* s.scheduleOnce(Duration.seconds(2), () => console.log("F"))
*
* // Actual execution...
*
* // Prints A, B
* s.tick()
* // Prints C, D
* s.tick(Duration.seconds(1))
* // Prints E, F
* s.tick(Duration.seconds(1))
* ```
*
* @param duration is an optional timespan to user for incrementing
* [currentTimeMillis]{@link TestScheduler.currentTimeMillis}, thus allowing
* the execution of tasks scheduled to execute with a delay.
*
* @return the number of executed tasks
*/
public tick(duration?: number | Duration): number {
const state = this._state()
let toExecute = []
let jumpMs = Duration.of(duration || 0).toMillis()
let executed = 0
while (true) {
const peek = state.tasks.length > 0
? state.tasks[state.tasks.length - 1]
: undefined
if (peek && peek[0] <= state.clock) {
toExecute.push(state.tasks.pop())
} else if (toExecute.length > 0) {
// Executing current batch, randomized
while (toExecute.length > 0) {
const index = Math.floor(Math.random() * toExecute.length)
const elem = toExecute[index] as any
try {
toExecute.splice(index, 1)
this.batchIndex = 0
elem[1]()
} catch (e) {
this.reportFailure(e)
} finally {
executed += 1
}
}
} else if (jumpMs > 0) {
const nextTaskJump = peek && (peek[0] - state.clock) || jumpMs
const add = Math.min(nextTaskJump, jumpMs)
state.clock += add
jumpMs -= add
} else {
break
}
}
return executed
}
/**
* Executes the task that's at the top of the stack, in case we
* have a task to execute that doesn't require a jump in time.
*
* ```typescript
* const ec = new TestScheduler()
*
* ec.execute(() => console.log("A"))
* ec.execute(() => console.log("B"))
*
* // Prints B
* ec.tickOne()
* // Prints A
* ec.tickOne()
* ```
*/
public tickOne(): boolean {
const state = this._state()
const peek = state.tasks.length > 0
? state.tasks[state.tasks.length - 1]
: undefined
if (!peek || peek[0] > state.clock) return false
this._state().tasks.pop()
this.batchIndex = 0
try { peek[1]() } catch (e) { this.reportFailure(e) }
return true
}
}
class TestSchedulerState {
public clock: number
public triggeredFailures: Array<any>
public tasks!: Array<[number, () => void]>
public tasksSearch!: (search: number) => number
constructor() {
this.clock = 0
this.triggeredFailures = []
this.updateTasks([])
}
updateTasks(tasks: Array<[number, () => void]>) {
this.tasks = tasks
this.tasksSearch = arrayBSearchInsertPos(this.tasks, e => -e[0])
}
}
/**
* Internal, reusable [[GlobalScheduler]] reference.
*
* @Hidden
*/
const globalSchedulerRef = new GlobalScheduler(true)
/**
* Internal utility wrapper a runner in an implementation that
* reports errors with the provided `reporter` callback.
*
* @Hidden
*/
function safeRunnable(r: () => void, reporter: (error: any) => void): () => void {
return () => { try { r() } catch (e) { reporter(e) } }
} | the_stack |
import * as vscode from 'vscode';
import assert from 'assert';
import { beforeEach, afterEach } from 'mocha';
import sinon from 'sinon';
import Connection = require('mongodb-connection-model/lib/model');
import {
DefaultSavingLocations,
StorageScope
} from '../../../storage/storageController';
import { mdbTestExtension } from '../stubbableMdbExtension';
import { TEST_DATABASE_URI } from '../dbTestHelper';
const testDatabaseURI2WithTimeout =
'mongodb://shouldfail?connectTimeoutMS=500&serverSelectionTimeoutMS=500';
suite('Explorer Controller Test Suite', function () {
// Longer timeout, sometimes it takes a few seconds for vscode to
// load the extension before running tests.
this.timeout(10000);
beforeEach(async () => {
// Don't save connections on default.
await vscode.workspace
.getConfiguration('mdb.connectionSaving')
.update(
'defaultConnectionSavingLocation',
DefaultSavingLocations['Session Only']
);
// Here we stub the showInformationMessage process because it is too much
// for the render process and leads to crashes while testing.
sinon.replace(vscode.window, 'showInformationMessage', sinon.fake.resolves(true));
});
afterEach(async () => {
// Unset the variable we set in `beforeEach`.
await vscode.workspace
.getConfiguration('mdb.connectionSaving')
.update(
'defaultConnectionSavingLocation',
DefaultSavingLocations.Workspace
);
// Reset our connections.
await mdbTestExtension.testExtensionController._connectionController.disconnect();
mdbTestExtension.testExtensionController._connectionController.clearAllConnections();
sinon.restore();
mdbTestExtension.testExtensionController._explorerController.deactivate();
});
test('it updates the connections to account for a change in the connection controller', async () => {
const testConnectionController =
mdbTestExtension.testExtensionController._connectionController;
const testExplorerController =
mdbTestExtension.testExtensionController._explorerController;
const treeController = testExplorerController.getTreeController();
const mockConnectionId = 'testConnectionId';
testConnectionController._connections = {
testConnectionId: {
id: 'testConnectionId',
connectionModel: new Connection(),
name: 'testConnectionName',
storageLocation: StorageScope.NONE
}
};
testConnectionController.setConnnectingConnectionId(mockConnectionId);
testConnectionController.setConnnecting(true);
const connectionsItems = await treeController.getChildren();
assert(
connectionsItems.length === 1,
`Expected there to be 1 connection tree item, found ${connectionsItems.length}`
);
assert(
connectionsItems[0].label === 'testConnectionName',
'There should be a connection tree item with the label "testConnectionName"'
);
});
test('when a connection is added and connected it is added to the tree', async () => {
const testConnectionController =
mdbTestExtension.testExtensionController._connectionController;
const testExplorerController =
mdbTestExtension.testExtensionController._explorerController;
const treeController = testExplorerController.getTreeController();
const succesfullyConnected = await testConnectionController.addNewConnectionStringAndConnect(
TEST_DATABASE_URI
);
assert(
succesfullyConnected === true,
'Expected a successful connection response.'
);
assert(
Object.keys(testConnectionController._connections).length === 1,
'Expected there to be 1 connection in the connection list.'
);
const activeId = testConnectionController.getActiveConnectionId();
assert(
activeId === Object.keys(testConnectionController._connections)[0],
`Expected active connection to be '${
Object.keys(testConnectionController._connections)[0]
}' found ${activeId}`
);
const connectionsItems = await treeController.getChildren();
assert(
connectionsItems.length === 1,
`Expected there be 1 connection tree item, found ${connectionsItems.length}`
);
assert(
connectionsItems[0].label === 'localhost:27018',
'There should be a connection tree item with the label "localhost:27018"'
);
assert(
connectionsItems[0].description === 'connected',
'There should be a connection tree item with the description "connected"'
);
});
test('only the active connection is displayed as connected in the tree', async () => {
const testConnectionController =
mdbTestExtension.testExtensionController._connectionController;
const testExplorerController =
mdbTestExtension.testExtensionController._explorerController;
const treeController = testExplorerController.getTreeController();
const succesfullyConnected = await testConnectionController.addNewConnectionStringAndConnect(
TEST_DATABASE_URI
);
assert(
succesfullyConnected === true,
'Expected a successful connection response.'
);
assert(
Object.keys(testConnectionController._connections).length === 1,
'Expected there to be 1 connection in the connection list.'
);
const connectionId = testConnectionController.getActiveConnectionId() || '';
const connectionName =
testConnectionController._connections[connectionId].name;
assert(
connectionName === 'localhost:27018',
`Expected active connection name to be 'localhost:27018' found ${connectionName}`
);
try {
await testConnectionController.addNewConnectionStringAndConnect(
testDatabaseURI2WithTimeout
);
} catch (error) {
/* Silent fail (should fail) */
}
const connectionsItems = await treeController.getChildren();
assert(
connectionsItems.length === 2,
`Expected there be 2 connection tree item, found ${connectionsItems.length}`
);
assert(
connectionsItems[0].label === 'localhost:27018',
`First connection tree item should have label "localhost:27018" found ${connectionsItems[0].label}`
);
assert(
connectionsItems[0].isExpanded === false,
'Expected the first connection tree item to not be expanded'
);
assert(
connectionsItems[1].label === 'shouldfail:27017',
'Second connection tree item should have label "shouldfail:27017"'
);
});
test('shows connection names sorted alphabetically in the tree', async () => {
const testConnectionController =
mdbTestExtension.testExtensionController._connectionController;
const testExplorerController =
mdbTestExtension.testExtensionController._explorerController;
const treeController = testExplorerController.getTreeController();
await testConnectionController.addNewConnectionStringAndConnect(
TEST_DATABASE_URI
);
const connectionId = testConnectionController.getActiveConnectionId() || '';
testConnectionController._connections.aaa = {
connectionModel:
testConnectionController._connections[connectionId].connectionModel,
name: 'aaa',
id: 'aaa',
storageLocation: StorageScope.WORKSPACE
};
testConnectionController._connections.zzz = {
connectionModel:
testConnectionController._connections[connectionId].connectionModel,
name: 'zzz',
id: 'zzz',
storageLocation: StorageScope.WORKSPACE
};
const connectionsItems = await treeController.getChildren();
assert(
connectionsItems.length === 3,
`Expected there be 3 connection tree item, found ${connectionsItems.length}`
);
assert(
connectionsItems[0].label === 'aaa',
`First connection tree item should have label "aaa" found ${connectionsItems[0].label}`
);
assert(
connectionsItems[2].label === 'zzz',
`First connection tree item should have label "zzz" found ${connectionsItems[0].label}`
);
testConnectionController._connections.zzz.name = '111';
const afterAdditionConnectionsItems = await treeController.getChildren();
assert(
afterAdditionConnectionsItems[0].label === '111',
`First connection tree item should have label "111" found ${afterAdditionConnectionsItems[0].label}`
);
});
test('shows the databases of connected connection in tree', async () => {
const testConnectionController =
mdbTestExtension.testExtensionController._connectionController;
const testExplorerController =
mdbTestExtension.testExtensionController._explorerController;
const treeController = testExplorerController.getTreeController();
await testConnectionController.addNewConnectionStringAndConnect(
TEST_DATABASE_URI
);
const connectionsItems = await treeController.getChildren();
const databaseItems = await connectionsItems[0].getChildren();
assert(
databaseItems.length >= 3,
`Expected there be 3 or more database tree items, found ${databaseItems.length}`
);
assert(
databaseItems[0].label === 'admin',
`First database tree item should have label "admin" found ${connectionsItems[0].label}.`
);
});
test('caches the expanded state of databases in the tree when a connection is expanded or collapsed', async () => {
const testConnectionController =
mdbTestExtension.testExtensionController._connectionController;
const testExplorerController =
mdbTestExtension.testExtensionController._explorerController;
const treeController = testExplorerController.getTreeController();
await testConnectionController.addNewConnectionStringAndConnect(
TEST_DATABASE_URI
);
const connectionsItems = await treeController.getChildren();
// Expand the connection.
const testConnectionTreeItem = connectionsItems[0];
await testConnectionTreeItem.onDidExpand();
const databaseItems = await testConnectionTreeItem.getChildren();
assert(
databaseItems[1].isExpanded === false,
'Expected database tree item not to be expanded on default.'
);
// Expand the first database item.
await databaseItems[1].onDidExpand();
assert(
databaseItems[1].isExpanded === true,
'Expected database tree item be expanded.'
);
// Collapse the connection.
testConnectionTreeItem.onDidCollapse();
const databaseTreeItems = await testConnectionTreeItem.getChildren();
assert(
databaseTreeItems.length === 0,
`Expected the connection tree to return no children when collapsed, found ${databaseTreeItems.length}`
);
testConnectionTreeItem.onDidExpand();
const newDatabaseItems = await testConnectionTreeItem.getChildren();
assert(
newDatabaseItems[1].isExpanded === true,
'Expected database tree to be expanded from cache.'
);
});
test('tree view should be not created by default (shows welcome view)', () => {
const testExplorerController =
mdbTestExtension.testExtensionController._explorerController;
assert(testExplorerController.getConnectionsTreeView() === undefined);
});
test('tree view should call create tree view after a "CONNECTIONS_DID_CHANGE" event', async () => {
const testConnectionController =
mdbTestExtension.testExtensionController._connectionController;
const testExplorerController =
mdbTestExtension.testExtensionController._explorerController;
testExplorerController.activateConnectionsTreeView();
const treeControllerStub = sinon.stub().returns(null);
sinon.replace(
testExplorerController.getTreeController(),
'activateTreeViewEventHandlers',
treeControllerStub
);
const vscodeCreateTreeViewStub = sinon.stub().returns('');
sinon.replace(vscode.window, 'createTreeView', vscodeCreateTreeViewStub);
await testConnectionController.addNewConnectionStringAndConnect(
TEST_DATABASE_URI
);
await testConnectionController.disconnect();
assert(vscodeCreateTreeViewStub.called);
});
}); | the_stack |
import { ParserSymbol } from './parsertokens/ParserSymbol';
import { PrimitiveElement } from './PrimitiveElement';
import { Expression } from './Expression';
import { ExpressionConstants } from './ExpressionConstants';
import { java } from 'j4ts/j4ts';
import { HeadEqBody } from './Miscellaneous';
import { mXparserConstants } from './mXparserConstants';
/**
* Constructor - creates constant with a given name and given value.
* Additionally description is being set.
*
* @param {string} constantName the constant name
* @param {number} constantValue the constant value
* @param {string} description the constant description
* @class
* @extends PrimitiveElement
*/
export class Constant extends PrimitiveElement {
/**
* When constant could not be found
*/
public static NOT_FOUND: number; public static NOT_FOUND_$LI$(): number { if (Constant.NOT_FOUND == null) { Constant.NOT_FOUND = ExpressionConstants.NOT_FOUND_$LI$(); } return Constant.NOT_FOUND; }
/**
* Type identifier for constants
*/
public static TYPE_ID: number = 104;
public static TYPE_DESC: string = "User defined constant";
/**
* Status of the Expression syntax
*/
public static NO_SYNTAX_ERRORS: boolean; public static NO_SYNTAX_ERRORS_$LI$(): boolean { if (Constant.NO_SYNTAX_ERRORS == null) { Constant.NO_SYNTAX_ERRORS = ExpressionConstants.NO_SYNTAX_ERRORS; } return Constant.NO_SYNTAX_ERRORS; }
public static SYNTAX_ERROR_OR_STATUS_UNKNOWN: boolean; public static SYNTAX_ERROR_OR_STATUS_UNKNOWN_$LI$(): boolean { if (Constant.SYNTAX_ERROR_OR_STATUS_UNKNOWN == null) { Constant.SYNTAX_ERROR_OR_STATUS_UNKNOWN = ExpressionConstants.SYNTAX_ERROR_OR_STATUS_UNKNOWN; } return Constant.SYNTAX_ERROR_OR_STATUS_UNKNOWN; }
static NO_SYNTAX_ERROR_MSG: string = "Constant - no syntax errors.";
/**
* Name of the constant
*/
/*private*/ constantName: string;
/**
* COnstant value
*/
/*private*/ constantValue: number;
/**
* Constant description
*/
/*private*/ description: string;
/**
* Dependent expression list
*/
/*private*/ relatedExpressionsList: java.util.List<Expression>;
/**
* Status of the expression syntax
*
* Please referet to the:
* - NO_SYNTAX_ERRORS
* - SYNTAX_ERROR_OR_STATUS_UNKNOWN
*/
/*private*/ syntaxStatus: boolean;
/**
* Message after checking the syntax
*/
/*private*/ errorMessage: string;
public constructor(constantName?: any, constantValue?: any, description?: any) {
if (((typeof constantName === 'string') || constantName === null) && ((typeof constantValue === 'number') || constantValue === null) && ((typeof description === 'string') || description === null)) {
let __args = arguments;
super(Constant.TYPE_ID);
if (this.constantName === undefined) { this.constantName = null; }
if (this.constantValue === undefined) { this.constantValue = 0; }
if (this.description === undefined) { this.description = null; }
if (this.relatedExpressionsList === undefined) { this.relatedExpressionsList = null; }
if (this.syntaxStatus === undefined) { this.syntaxStatus = false; }
if (this.errorMessage === undefined) { this.errorMessage = null; }
this.relatedExpressionsList = <any>(new java.util.ArrayList<Expression>());
if (mXparserConstants.regexMatch(constantName, ParserSymbol.nameOnlyTokenOptBracketsRegExp_$LI$())){
this.constantName = constantName;
this.constantValue = constantValue;
this.description = description;
this.syntaxStatus = Constant.NO_SYNTAX_ERRORS_$LI$();
this.errorMessage = Constant.NO_SYNTAX_ERROR_MSG;
} else {
this.syntaxStatus = Constant.SYNTAX_ERROR_OR_STATUS_UNKNOWN_$LI$();
this.errorMessage = "[" + constantName + "] --> invalid constant name, pattern not mathes: " + ParserSymbol.nameOnlyTokenOptBracketsRegExp_$LI$();
}
} else if (((typeof constantName === 'string') || constantName === null) && ((constantValue != null && constantValue instanceof <any>Array && (constantValue.length == 0 || constantValue[0] == null ||(constantValue[0] != null && constantValue[0] instanceof <any>PrimitiveElement))) || constantValue === null) && description === undefined) {
let __args = arguments;
let constantDefinitionString: any = __args[0];
let elements: any[] = __args[1];
super(Constant.TYPE_ID);
if (this.constantName === undefined) { this.constantName = null; }
if (this.constantValue === undefined) { this.constantValue = 0; }
if (this.description === undefined) { this.description = null; }
if (this.relatedExpressionsList === undefined) { this.relatedExpressionsList = null; }
if (this.syntaxStatus === undefined) { this.syntaxStatus = false; }
if (this.errorMessage === undefined) { this.errorMessage = null; }
this.description = "";
this.syntaxStatus = Constant.SYNTAX_ERROR_OR_STATUS_UNKNOWN_$LI$();
this.relatedExpressionsList = <any>(new java.util.ArrayList<Expression>());
if (mXparserConstants.regexMatch(constantDefinitionString, ParserSymbol.constUnitgDefStrRegExp_$LI$())){
const headEqBody: HeadEqBody = new HeadEqBody(constantDefinitionString);
this.constantName = headEqBody.headTokens.get(0).tokenStr;
const bodyExpression: Expression = <any>new (__Function.prototype.bind.apply(Expression, [null, headEqBody.bodyStr].concat(<any[]>elements)));
this.constantValue = bodyExpression.calculate();
this.syntaxStatus = bodyExpression.getSyntaxStatus();
this.errorMessage = bodyExpression.getErrorMessage();
} else this.errorMessage = "[" + constantDefinitionString + "] --> pattern not mathes: " + ParserSymbol.constUnitgDefStrRegExp_$LI$();
} else if (((typeof constantName === 'string') || constantName === null) && ((typeof constantValue === 'number') || constantValue === null) && description === undefined) {
let __args = arguments;
super(Constant.TYPE_ID);
if (this.constantName === undefined) { this.constantName = null; }
if (this.constantValue === undefined) { this.constantValue = 0; }
if (this.description === undefined) { this.description = null; }
if (this.relatedExpressionsList === undefined) { this.relatedExpressionsList = null; }
if (this.syntaxStatus === undefined) { this.syntaxStatus = false; }
if (this.errorMessage === undefined) { this.errorMessage = null; }
this.relatedExpressionsList = <any>(new java.util.ArrayList<Expression>());
if (mXparserConstants.regexMatch(constantName, ParserSymbol.nameOnlyTokenOptBracketsRegExp_$LI$())){
this.constantName = constantName;
this.constantValue = constantValue;
this.description = "";
this.syntaxStatus = Constant.NO_SYNTAX_ERRORS_$LI$();
this.errorMessage = Constant.NO_SYNTAX_ERROR_MSG;
} else {
this.syntaxStatus = Constant.SYNTAX_ERROR_OR_STATUS_UNKNOWN_$LI$();
this.errorMessage = "[" + constantName + "] --> invalid constant name, pattern not mathes: " + ParserSymbol.nameOnlyTokenOptBracketsRegExp_$LI$();
}
} else throw new Error('invalid overload');
}
/**
* Gets constant name
*
* @return {string} the constant name as string.
*/
public getConstantName(): string {
return this.constantName;
}
/**
* Sets constant name. If constant is associated with any expression
* then this operation will set modified flag to each related expression.
*
* @param {string} constantName the constant name
*/
public setConstantName(constantName: string) {
if (mXparserConstants.regexMatch(constantName, ParserSymbol.nameOnlyTokenOptBracketsRegExp_$LI$())){
this.constantName = constantName;
this.setExpressionModifiedFlags();
} else {
this.syntaxStatus = Constant.SYNTAX_ERROR_OR_STATUS_UNKNOWN_$LI$();
this.errorMessage = "[" + constantName + "] --> invalid constant name, pattern not mathes: " + ParserSymbol.nameOnlyTokenOptBracketsRegExp_$LI$();
}
}
/**
* Sets constant value
* @param {number} constantValue constant value
*/
public setConstantValue(constantValue: number) {
this.constantValue = constantValue;
}
/**
* Gets constant value.
*
* @return {number} constant value as double
*/
public getConstantValue(): number {
return this.constantValue;
}
/**
* Gets constant description.
*
* @return {string} constant description as string.
*/
public getDescription(): string {
return this.description;
}
/**
* Sets constant description.
*
* @param {string} description the constant description
*/
public setDescription(description: string) {
this.description = description;
}
/**
* Method return error message after
*
* @return {string} Error message as string.
*/
public getErrorMessage(): string {
return this.errorMessage;
}
/**
* Gets syntax status of the expression.
*
* @return {boolean} Constant.NO_SYNTAX_ERRORS if there are no syntax errors,
* Const.SYNTAX_ERROR_OR_STATUS_UNKNOWN when syntax error was found or
* syntax status is unknown
*/
public getSyntaxStatus(): boolean {
return this.syntaxStatus;
}
/**
* Adds related expression.
*
* @param {Expression} expression the related expression.
*/
addRelatedExpression(expression: Expression) {
if (expression != null)if (!this.relatedExpressionsList.contains(expression))this.relatedExpressionsList.add(expression);
}
/**
* Removes related expression.
*
* @param {Expression} expression the related expression.
*/
removeRelatedExpression(expression: Expression) {
if (expression != null)this.relatedExpressionsList.remove(expression);
}
/**
* Sets expression modified flag to each related expression.
*/
setExpressionModifiedFlags() {
for(let index121=this.relatedExpressionsList.iterator();index121.hasNext();) {
let e = index121.next();
e.setExpressionModifiedFlag()
}
}
}
Constant["__class"] = "org.mariuszgromada.math.mxparser.Constant";
var __Function = Function; | the_stack |
import './ForceDirectedGraphCanvas.css'
import * as React from "react";
import {drawRectStroke, drawRect, drawNodeGlyph, drawLine} from './CanvasDrawing';
const d3 = require("d3");
export interface IProps {
graph_json : any,
width : number,
height : number,
onNodeClick: any,
GraphViewState:any,
UpdateCurrentGraphJson:any
}
export interface IState {
}
export default class ForceDirectedGraphCanvas extends React.Component<IProps, IState>{
public global_simulation:any = null;
public saved_transform:any = null;
public refresh_number = 0;
public current_graph_json:any = null;
constructor(props:IProps) {
super(props);
this.updateTransform = this.updateTransform.bind(this);
this.state = {
}
}
componentDidMount(){
this.renderCanvas();
}
componentDidUpdate(prevProps:IProps, prevState:IState) {
if(prevProps.graph_json.name !== this.props.graph_json.name || prevProps.width !== this.props.width || prevProps.GraphViewState !== this.props.GraphViewState){
this.renderCanvas();
}
}
public updateTransform(transform:any){
this.saved_transform = transform;
}
// Render Legend Function.
public renderLegend(legend_configuration:any){
var width = legend_configuration["width"];
var height = legend_configuration["height"];
var colorLegend = legend_configuration["colorLegend"];
// ---------------- Color Legend -------------------------//
let legend_pie_y = height - 10 - 100;
var top_svg = d3.select("#force_directed_graph")
.select("#svgChart")
.attr("width", width)
.attr("height", height);
let legend_color_x = 10;
let max_text_length = 0;
colorLegend.forEach((d:any)=>{
let text = "" + d.text;
if(text.length>max_text_length){
max_text_length = text.length;
}
})
let legend_color_width = max_text_length*8+24;
//console.log("maxtextlength", max_text_length, legend_color_width);
let legend_color_height = colorLegend.length*20;
let legend_color_y = legend_pie_y - legend_color_height - 10;
var legend_color_svg = top_svg.select("#ForceDirectedColorLegend")
.attr("width", legend_color_width)
.attr("height", legend_color_height)
.attr("transform", "translate("+legend_color_x+","+legend_color_y+")")
let legend_rect = legend_color_svg.selectAll("rect").data([0]);
let legend_rect_enter = legend_rect.enter().append("rect");
//console.log("legend_rect", legend_rect);
legend_rect_enter.merge(legend_rect)
.attr("x", 0)
.attr("y", 0)
.attr("width", legend_color_width)
.attr("height", legend_color_height)
.attr("fill", "#fff")
.attr("opacity", 0.8)
.attr("stroke", "#bbb")
.attr("stroke-width", 1)
.attr("rx",3)
.attr("ry",3);
let row_legend_color = legend_color_svg.selectAll("g.legend_row_color")
.data(colorLegend, function(d:any,i:any){
return d.text+"_"+i+"_"+d.color;
});
let g_row_legend_color = row_legend_color.enter().append("g")
.attr("class","legend_row_color")
.attr("transform", function(d:any,i:any){
return "translate(10,"+(10+i*20)+")";
});
g_row_legend_color.append("circle")
.attr("r", 5)
.attr("fill", function(d:any){
return d.color;
})
g_row_legend_color.append("text")
.attr("x", 10)
.attr("y", 5)
.text(function(d:any){
return d.text;
})
row_legend_color.exit().remove();
// ---------------- Edge Color Legend -------------------------//
// let legend_edge_color_x = 10;
// let legend_edge_color_width = 38;
// let legend_edge_color_height = 100;
// let legend_edge_color_y = legend_pie_y - legend_color_height - legend_edge_color_height - 20;
// var legend_edge_color_svg = top_svg.select("#ForceDirectedEdgeColorLegend")
// .attr("width", legend_edge_color_width)
// .attr("height", legend_edge_color_height)
// .attr("transform", "translate("+legend_edge_color_x+","+legend_edge_color_y+")");
// let legend_edge_rect = legend_edge_color_svg.selectAll("rect").data([0]);
// let legend_edge_rect_enter = legend_edge_rect.enter().append("rect");
// console.log("legend_rect", legend_rect);
// legend_edge_rect_enter.merge(legend_edge_rect)
// .attr("x", 0)
// .attr("y", 0)
// .attr("width", legend_edge_color_width)
// .attr("height", legend_edge_color_height)
// .attr("fill", "#fff")
// .attr("opacity", 1)
// .attr("stroke", "#bbb")
// .attr("stroke-width", 1)
// .attr("rx",3)
// .attr("ry",3);
// Create the svg:defs element and the main gradient definition.
// var svgDefs = legend_edge_color_svg.selectAll("defs").data([0]);
// var svgDefs_enter = svgDefs.enter().append('defs');
// var mainGradient = svgDefs_enter.append('linearGradient')
// .attr('id', 'mainGradient')
// .attr("gradientTransform","rotate(90)");
// Create the stops of the main gradient. Each stop will be assigned
// a class to style the stop using CSS.
// mainGradient.append('stop')
// .attr('stop-color', "rgba(187, 187, 187 ,1)")
// .attr('offset', '0');
// mainGradient.append('stop')
// .attr('stop-color', 'rgba(187, 187, 187 ,0.1)')
// .attr('offset', '1');
// let g_legend_edge_color = legend_edge_color_svg.selectAll("g.legend_edge_color").data([0]);
// let g_legend_edge_color_enter = g_legend_edge_color.enter().append("g").attr("class","legend_edge_color");
// let rect_legend_edge_color_enter = g_legend_edge_color_enter.append("rect");
// let rect_legend_edge_color = g_legend_edge_color.select("rect");
//let colorGradient = d3.scaleSequential(d3.interpolateRdYlGn);
// let top_padding = 20;
// let padding = 5;
// let text_width = 10;
// let rect_width = legend_edge_color_width-2*padding-text_width;
// let rect_height = legend_edge_color_height-2*padding - top_padding;
// rect_legend_edge_color_enter.merge(rect_legend_edge_color)
// .attr("x", padding)
// .attr("y", top_padding + padding)
// .attr("width", rect_width)
// .attr("height", rect_height)
// .attr("fill","url(#mainGradient)");
// let legend_text_list = [
// {
// "text":"1",
// "x":padding + rect_width,
// "y":top_padding + padding,
// "dx":".02em",
// "dy":".65em",
// "text-anchor":"start"
// },
// {
// "text":"0",
// "x":padding + rect_width,
// "y":top_padding + padding + rect_height,
// "dx":".02em",
// "dy":".05em",
// "text-anchor":"start"
// },
// {
// "text":"Edge",
// "x":padding,
// "y":padding,
// "dx":".00em",
// "dy":".65em",
// "text-anchor":"start"
// }];
// let legend_text_update = g_legend_edge_color_enter.selectAll("text").data(legend_text_list, function(d:any){
// return d.text;
// });
// let legend_text_enter = legend_text_update.enter().append("text");
// legend_text_update.merge(legend_text_enter)
// .attr("x", (d:any)=>d.x)
// .attr("y", (d:any)=>d.y)
// .attr("dx", (d:any)=>d.dx)
// .attr("dy", (d:any)=>d.dy)
// .attr("text-anchor",(d:any)=>d["text-anchor"])
// .text((d:any)=>{
// return d.text;
// });
// let legend_title = g_legend_edge_color.exit().remove();
}
// Render Canvas Main Function
public renderCanvas(){
// initialize
this.props.UpdateCurrentGraphJson(this.props.graph_json);
var onNodeClick = this.props.onNodeClick;
var nodenum = this.props.graph_json.nodenum;
var enabledForceDirected = this.props.graph_json.enable_forceDirected;
var neighborSet = this.props.graph_json.NeighborSet;
var colorLegend = this.props.graph_json.colorLegend;
var configuration = {
"strength": 0.01,
"radius":15,
"showlabel": true,
"showarrow": true,
"width": this.props.width,
"height": this.props.height
}
var GraphViewState = this.props.GraphViewState;
var DisplayUnfocusedNodes = GraphViewState.DisplayUnfocusedNodes;
var DisplayOverview = GraphViewState.DisplayOverview;
//console.log("ForceDirected" , nodenum)
if(nodenum >= 100){
configuration = {
"strength": 0.4,
"radius":3,
"showlabel": false,
"showarrow": false,
"width": this.props.width,
"height": this.props.height
}
}
var width = configuration["width"];
var height = configuration["height"];
var radius = configuration["radius"];
var radius_gap = 0.3;
var graphWidth = this.props.width;
var legend_configuration:any = {
"width":width,
"height":height,
"colorLegend":colorLegend,
}
// Render Legend
this.renderLegend(legend_configuration);
// Layered Canvas
// Detect Event -- Capture Event
// Overview Canvas -- Display Overview
// Hovered Canvas -- Hovered Canvas (will not modify the bottom canvas when hovering)
// Bottom Canvas -- Bottom Canvas
// 1. Original Canvas
var graphCanvas = d3.select('#force_directed_graph').select('#bottom')
.attr('width', graphWidth + 'px')
.attr('height', height + 'px')
.node();
var context = graphCanvas.getContext('2d');
// 2. Hovered Canvas
var middleCanvas = d3.select('#force_directed_graph').select("#middle")
.attr('width', graphWidth + 'px')
.attr('height', height + 'px')
.node();
var middle_context = middleCanvas.getContext('2d');
// 3. Overview Canvas
var overviewCanvas = d3.select('#force_directed_graph').select('#overview')
.attr('width', graphWidth + 'px')
.attr('height', height + 'px')
.node();
var overview_context = overviewCanvas.getContext('2d');
// 4. Detect Event
var eventCanvas = d3.select('#force_directed_graph').select("#event")
.attr('width', graphWidth + 'px')
.attr('height', height + 'px')
.node();
/**
* OverviewCanvas
*/
let canvasWidth = 100;
let canvasHeight = 100;
let margin = 10;
let canvasX = graphWidth - canvasWidth - margin;
let canvasY = height - canvasHeight - margin;
let canvasXRight = canvasX + canvasWidth;
let canvasYBottom = canvasY + canvasHeight;
let radius_collision = radius*3 + radius_gap*3;
// Force Directed Layout Algorithm.
if(this.global_simulation){
this.global_simulation.stop();
delete this.global_simulation;
}
var simulation = d3.forceSimulation()
.force("center", d3.forceCenter(graphWidth / 2, height / 2))
.force("x", d3.forceX(graphWidth / 2).strength(0.1))
.force("y", d3.forceY(height / 2).strength(0.1))
.force("charge", d3.forceManyBody().strength(-50))
.force("link", d3.forceLink().strength(1).id(function(d:any) { return d.id; }))
.force('collide', d3.forceCollide().radius((d:any) => radius_collision))
.alphaTarget(0)
.alphaDecay(0.05)
this.global_simulation = simulation;
let updateTransform = this.updateTransform;
// Transform
// This transform is preserved.
var transform:any;
var calTransform:any={
"x":0,
"y":0,
"k":1
};
if(this.saved_transform){
transform =this.saved_transform ;
}else{
transform = d3.zoomIdentity;
}
// Judge the hovered flag.
function judgeHoveredFlag(d:any, bool:boolean){
if(!d.hasOwnProperty("hovered") || d["hovered"]===false ){
if(bool === false){
return false;
}else{
return true;
}
}else{
if(bool === true){
return false;
}else{
return true;
}
}
}
// Hide the tooltip.
function hiddenTooltip(){
d3.select("#force_directed_graph").select("#tooltip").style('opacity', 0);
}
// Processed Data.
let tempData = this.props.graph_json;
//console.log("tempData", tempData);
let event_canvas = eventCanvas;
var mouseCoordinates:any = null;
d3.select(event_canvas).on("click",handleMouseClick).on("mousemove", handleMouseMove).on("mouseout",handleMouseOut);
d3.select(event_canvas).call(d3.zoom().scaleExtent([1 / 10, 8]).on("zoom", zoomed))
// Control whether using force directed layout.
// SimulationUpdate is used to render the layout.
if(enabledForceDirected){
simulation
.nodes(tempData.nodes)
.on("tick", simulationUpdate);
simulation.force("link")
.links(tempData.links);
}else{
simulation.stop();
simulation
.nodes(tempData.nodes);
simulation.force("link")
.links(tempData.links);
simulationUpdate();
}
// Determine the clicked ordering.
function order_determine(a:any,b:any){
let hover_cons_a = a.hasOwnProperty("hover_cons")?a.hover_cons:1;
let hover_cons_b = b.hasOwnProperty("hover_cons")?b.hover_cons:1;
let node_outer_radius_a = a.radius*hover_cons_a*2;
let node_outer_radius_b = b.radius*hover_cons_b*2;
return node_outer_radius_a<node_outer_radius_b?-1:1;
}
// Determine the clicked object.
function determineSubject(mouse_x:number,mouse_y:number){
var i,
x = transform.invertX(mouse_x),
y = transform.invertY(mouse_y),
dx,
dy;
let newNodeList = tempData.nodes.slice().sort(order_determine)
for (i = newNodeList.length - 1; i >= 0; --i) {
var node = newNodeList[i];
if(!DisplayUnfocusedNodes && !node["highlight"]){
continue;
}
dx = x - node.x;
dy = y - node.y;
let hover_cons = node.hasOwnProperty("hover_cons")?node.hover_cons:1;
let outer_radius_node = node.radius * 2 * hover_cons;
if (dx * dx + dy * dy < outer_radius_node * outer_radius_node) {
return node;
}
}
return null;
}
// Zoom updating.
function zoomed(this:any) {
var xy = d3.mouse(this);
mouseCoordinates = xy;
transform = d3.event.transform;
if(determineEventSubject(xy[0], xy[1])==="GraphCanvas"){
updateTransform(transform);
simulationUpdate();
}
}
// Mouse Move Handler.
// Use middleCanvasSimulationUpdate() to update the hovered nodes.
function handleMouseMove(this:any, obj:any=null, defaultUpdateFlag:boolean=false){
var xy:any;
if(obj){
xy = mouseCoordinates;
}else{
xy = d3.mouse(this);
mouseCoordinates = xy;
}
var updateFlag = defaultUpdateFlag;
if(xy){
let event_subject = determineEventSubject(xy[0], xy[1]);
var selected = determineSubject(xy[0],xy[1]);
if(event_subject==="GraphCanvas"&&selected){
updateFlag = true;
let target_id = selected.id;
d3.select("#force_directed_graph").select('#tooltip')
.style('opacity', 0.8)
.style('top', (xy[1] + 5) + 'px')
.style('left', (xy[0] + 5) + 'px')
.html(target_id);
let neighbor_id = neighborSet[selected.id];
tempData.nodes.forEach((d:any)=>{
if(target_id === d.id){
d.hovered = true;
d.hover_cons = 3;
}else if(neighbor_id.indexOf(d.id)>=0){
d.hovered = true;
d.hover_cons = 2;
}else{
d.hovered = false;
d.hover_cons = 1;
}
})
}else{
tempData.nodes.forEach((d:any)=>{
updateFlag = updateFlag || judgeHoveredFlag(d, false);
d.hovered = false;
d.hover_cons = 1;
})
hiddenTooltip();
}
}else{
tempData.nodes.forEach((d:any)=>{
updateFlag = updateFlag || judgeHoveredFlag(d, false);
d.hovered = false;
d.hover_cons = 1;
})
hiddenTooltip();
}
if(updateFlag){
middleCanvasSimulationUpdate()
}
}
// Mouse Out handler.
function handleMouseOut(this:any, obj:any=null, defaultUpdateFlag:boolean=false){
var updateFlag = defaultUpdateFlag;
mouseCoordinates = null;
tempData.nodes.forEach((d:any)=>{
updateFlag = updateFlag || judgeHoveredFlag(d, false);
d.hovered = false;
d.hover_cons = 1;
})
hiddenTooltip();
if(updateFlag){
middleCanvasSimulationUpdate()
}
}
// Determine the clicked canvas.
function determineEventSubject(mouse_x:number, mouse_y:number){
if(mouse_x >= canvasX && mouse_x <=canvasXRight
&& mouse_y >= canvasY && mouse_y <=canvasYBottom && DisplayOverview){
return "OverviewCanvas";
}else{
return "GraphCanvas";
}
}
// Mouse Click Handler.
function handleMouseClick(this:any, obj:any=null, defaultUpdateFlag:boolean=false){
if (d3.event.defaultPrevented) return; // zoomed
var xy:any;
if(obj){
xy = mouseCoordinates;
}else{
xy = d3.mouse(this);
mouseCoordinates = xy;
}
if(xy){
if(determineEventSubject(xy[0],xy[1])==="OverviewCanvas"){
moveFocalPoint(xy[0], xy[1]);
}else{
var selected = determineSubject(xy[0],xy[1]);
if(selected){
onNodeClick(selected.id);
}
}
}else{
}
}
// ---- The following code is reserved for overview canvas calculation. NOT IMPORTANT ---- //
// Calculate the bounding box of graph.
function calculateGraphBoundingBox(){
//let canvasWidth = graphWidth;
//let canvasHeight = height;
let minx=0, miny=0, maxx=0, maxy=0;
let flag = false;
tempData.nodes.forEach(function(d:any){
if(DisplayUnfocusedNodes || (!DisplayUnfocusedNodes && d.highlight)){
let x = d.x;
let y = d.y;
if(!flag){
minx = x;
miny = y;
maxx = x;
maxy = y;
flag = true;
}else{
if(minx > x){
minx = x;
}
if(maxx < x){
maxx = x;
}
if(miny > y){
miny = y;
}
if(maxy < y){
maxy = y;
}
}
}
})
let glyph_outer_radius = 3*2;
let margin = 14;
let leftbound = minx - glyph_outer_radius - margin;
let upperbound = miny - glyph_outer_radius - margin;
let occupyWidth = maxx - minx + glyph_outer_radius*2 + margin*2;
let occupyHeight = maxy - miny + glyph_outer_radius*2 + margin*2;
return {
"leftbound":leftbound,
"upperbound":upperbound,
"occupyWidth":occupyWidth,
"occupyHeight":occupyHeight
}
}
// Calculate the transformed rects.
function rectTransform(rect_configuration:any, transform:any){
let rect_x = rect_configuration["x"];
let rect_y = rect_configuration["y"];
let rect_width = rect_configuration["width"];
let rect_height = rect_configuration["height"];
let dx = transform.x;
let dy = transform.y;
let scale = transform.k;
let x = (rect_x*scale + dx) ;
let y = (rect_y*scale + dy) ;
let width = (rect_width) * scale;
let height = (rect_height) * scale;
return {
"x":x,
"y":y,
"width":width,
"height":height
}
}
// Calculate the inversed transformed rects.
function rectInverseTransform(rect_configuration:any, transform:any){
let rect_x = rect_configuration["x"];
let rect_y = rect_configuration["y"];
let rect_width = rect_configuration["width"];
let rect_height = rect_configuration["height"];
let dx = -transform.x;
let dy = -transform.y;
let scale = 1/transform.k;
let x = (rect_x + dx) * scale;
let y = (rect_y + dy) * scale;
let width = (rect_width) * scale;
let height = (rect_height) * scale;
return {
"x":x,
"y":y,
"width":width,
"height":height
}
}
// Calculate the inversed transformed of points.
function pointInverseTransform(point_configuration:any, transform:any){
let point_x = point_configuration["x"];
let point_y = point_configuration["y"];
let dx = -transform.x;
let dy = -transform.y;
let scale = 1/transform.k;
let x = (point_x + dx) * scale;
let y = (point_y + dy) * scale;
return {
"x":x,
"y":y
}
}
// Move the Overview Focused View.
function moveFocalPoint(mouse_x:number, mouse_y:number){
let ori_point = {
"x":graphWidth / 2,
"y":height / 2
}
let ori_inverse_point = pointInverseTransform(ori_point, transform);
let overview_point = {
"x": mouse_x,
"y": mouse_y
}
let overview_inverse_point = pointInverseTransform(overview_point, calTransform);
let new_x = -(overview_inverse_point["x"] - ori_inverse_point["x"])*transform.k + transform.x;
let new_y = -(overview_inverse_point["y"] - ori_inverse_point["y"])*transform.k + transform.y;
console.log({
ori_point, ori_inverse_point, overview_point, overview_inverse_point, new_x, new_y
})
transform.x = new_x;
transform.y = new_y;
updateTransform(transform);
simulationUpdate();
}
// Calculate the rect in the overview.
function rectInverseTransformAndClip(rect_configuration:any,transform:any, bounding_box:any){
let leftbound = bounding_box["leftbound"];
let upperbound = bounding_box["upperbound"];
let occupyHeight = bounding_box["occupyHeight"];
let occupyWidth = bounding_box["occupyWidth"];
let rightbound = leftbound + occupyWidth;
let lowerbound = upperbound + occupyHeight;
let inverse_transform_rect = rectInverseTransform(rect_configuration, transform);
let transformed_leftbound = inverse_transform_rect["x"];
let transformed_upperbound = inverse_transform_rect["y"];
let transformed_rightbound = inverse_transform_rect["x"]+inverse_transform_rect["width"];
let transformed_lowerbound = inverse_transform_rect["y"]+inverse_transform_rect["height"];
if(transformed_leftbound<leftbound){
transformed_leftbound = leftbound;
}
if(transformed_rightbound>rightbound){
transformed_rightbound = rightbound;
}
if(transformed_upperbound<upperbound){
transformed_upperbound = upperbound;
}
if(transformed_lowerbound>lowerbound){
transformed_lowerbound = lowerbound;
}
let clipx = transformed_leftbound;
let clipy = transformed_upperbound;
let clipwidth = transformed_rightbound - transformed_leftbound;
let clipheight = transformed_lowerbound - transformed_upperbound;
if(clipwidth < 0){
clipwidth = 0;
}else if(clipwidth>occupyWidth){
clipwidth = occupyWidth;
}
if(clipheight<0){
clipheight=0;
}else if(clipheight>occupyHeight){
clipheight = occupyHeight;
}
return {
"x":clipx,
"y":clipy,
"width":clipwidth,
"height":clipheight
}
}
function calculateTransform(canvasX:number,canvasY:number,canvasWidth:number, canvasHeight:number, bounding_box:any){
let leftbound = bounding_box["leftbound"];
let upperbound = bounding_box["upperbound"];
let occupyHeight = bounding_box["occupyHeight"];
let occupyWidth = bounding_box["occupyWidth"];
let xscale = canvasWidth / occupyWidth;
let yscale = canvasHeight / occupyHeight;
let scale = Math.min(xscale, yscale);
let dx = (canvasWidth - occupyWidth * scale)/2 - leftbound*scale + canvasX;
let dy = (canvasHeight - occupyHeight * scale)/2 - upperbound*scale + canvasY;
//console.log("canvasWidth, canvasHeight, occupyWidth, occupyHeight", canvasWidth,canvasHeight, occupyWidth,occupyHeight);
let calTransform = {
"k": scale,
"x":dx,
"y":dy
}
return calTransform;
}
// ---- The above code is reserved for overview canvas calculation. NOT IMPORTANT ---- //
// 2. Main render function.
function renderContext(context:any){
// Unfocused nodes rendering.
if(DisplayUnfocusedNodes){
tempData.links.filter((d:any)=>{
if(d.source.highlight && d.target.highlight){
return false;
}else{
return true;
}
}).forEach(function(d:any) {
// Draw Line
drawLine(context, d.color, d.source.x, d.source.y, d.target.x, d.target.y, null, d.weight);
});
// Draw the nodes
tempData.nodes.filter((d:any)=>{
return !d["highlight"];
}
).forEach(function(d:any, i:any) {
// Draw Node Glyph
//console.log("radius",d.radius);
let node_inner_radius = d.radius - radius_gap;
let node_radius = d.radius;
let node_outer_radius = d.radius * 2;
let node_outer_arc_encoded_value = d.node_weight;
let node_outer_arc_radius = node_outer_radius + radius_gap * 5;
drawNodeGlyph(context, d.color, node_inner_radius,
node_radius, node_outer_radius, d.x, d.y, false,
node_outer_arc_encoded_value, node_outer_arc_radius);
});
}
// Focused nodes rendering
tempData.links.filter((d:any)=>{
if(d.source.highlight && d.target.highlight){
return true;
}else{
return false;
}
}).forEach(function(d:any) {
drawLine(context, d.color, d.source.x, d.source.y, d.target.x, d.target.y, 5 * d.weight, d.weight);
});
tempData.nodes.filter((d:any)=>{
return d["highlight"];
}).forEach(function(d:any,i:any){
let node_inner_radius = d.radius - radius_gap;
let node_radius = d.radius;
let node_outer_radius = d.radius * 2;
let node_outer_arc_encoded_value = d.node_weight;
let node_outer_arc_radius = node_outer_radius + radius_gap * 5;
drawNodeGlyph(context, d.color, node_inner_radius,
node_radius, node_outer_radius, d.x, d.y, false,
node_outer_arc_encoded_value, node_outer_arc_radius);
})
}
// Main Function for Updating Layout.
function simulationUpdate(){
context.save();
context.clearRect(0, 0, graphWidth, height);
context.translate(transform.x, transform.y);
context.scale(transform.k, transform.k);
renderContext(context);
context.restore();
//let canvasWidth = 100 * graphWidth / height;
// ---- The following code is reserved for overview canvas calculation. NOT IMPORTANT ---- //
if(DisplayOverview){
let graph_bounding_box = calculateGraphBoundingBox();
calTransform = calculateTransform(canvasX, canvasY, canvasWidth, canvasHeight, graph_bounding_box);
let rect_configuration = {
"x":0, "y":0, "width":graphWidth, "height":height
}
let overview_configuration = {
"x":canvasX,
"y":canvasY,
"width":canvasWidth,
"height":canvasHeight
}
let overview_inverse_rect = rectInverseTransform(overview_configuration, calTransform);
let overview_bounding_box = {
"leftbound":overview_inverse_rect["x"],
"upperbound":overview_inverse_rect["y"],
"occupyWidth":overview_inverse_rect["width"],
"occupyHeight":overview_inverse_rect["height"]
}
let view_inverse_configuration = rectInverseTransformAndClip(rect_configuration, transform, overview_bounding_box);
let view_configuration = rectTransform(view_inverse_configuration, calTransform);
overview_context.save();
overview_context.clearRect(0, 0, graphWidth, height);
drawRectStroke(overview_context, canvasX, canvasY, canvasWidth, canvasHeight);
drawRect(overview_context, canvasX, canvasY, canvasWidth, canvasHeight);
overview_context.translate(calTransform.x, calTransform.y);
overview_context.scale(calTransform.k, calTransform.k);
renderContext(overview_context);
overview_context.scale(1/calTransform.k, 1/calTransform.k);
overview_context.translate(-calTransform.x, -calTransform.y);
drawRectStroke(overview_context, view_configuration["x"], view_configuration["y"], view_configuration["width"], view_configuration["height"],"#000");
drawRect(overview_context, view_configuration["x"], view_configuration["y"], view_configuration["width"], view_configuration["height"],"#ccc",0.5);
overview_context.restore();
}
// ---- The above code is reserved for overview canvas calculation. NOT IMPORTANT ---- //
handleMouseMove(middleCanvas, true);
}
// When hovering, changing middle canvas.
function middleCanvasSimulationUpdate(){
let judgeHovered = (d:any)=>{
if(d.hasOwnProperty("hovered") && d["hovered"]){
return true;
}else{
return false;
}
}
middle_context.save();
middle_context.clearRect(0, 0, graphWidth, height);
middle_context.translate(transform.x, transform.y);
middle_context.scale(transform.k, transform.k);
tempData.links.filter((d:any)=>{
if(judgeHovered(d.source) && judgeHovered(d.target)){
return true;
}else{
return false;
}
}).forEach(function(d:any) {
drawLine(middle_context, d.real_color, d.source.x, d.source.y, d.target.x, d.target.y, null, d.weight);
});
// Draw the hovered nodes
tempData.nodes.filter((d:any)=>{
return judgeHovered(d);
}).sort(order_determine).forEach(function(d:any, i:any) {
let node_inner_radius = d.radius - radius_gap;
let node_radius = d.radius;
let node_outer_radius = d.radius * 2;
let node_outer_arc_encoded_value = d.node_weight;
let node_outer_arc_radius = node_outer_radius + radius_gap * 5;
drawNodeGlyph(middle_context, d.real_color, node_inner_radius*d.hover_cons,
node_radius*d.hover_cons, node_outer_radius*d.hover_cons, d.x, d.y, true,
node_outer_arc_encoded_value, node_outer_arc_radius*d.hover_cons, false);
});
middle_context.restore();
}
}
public render() {
return (
<div id="force_directed_graph">
<canvas id="bottom" className="AbsPos" />
<canvas id="middle" className="AbsPos"/>
<canvas id="overview" className="AbsPos"/>
<svg
id="svgChart"
xmlns="http://www.w3.org/2000/svg"
className="AbsPos"
>
<g id="ForceDirectedLegend">
</g>
<g id="ForceDirectedColorLegend">
</g>
</svg>
<div id="tooltip" className="AbsPos" />
<canvas id="event" className="AbsPos"/>
</div>
)
}
} | the_stack |
import { ExpoConfig } from '@expo/config';
import { IOSConfig } from '@expo/config-plugins';
import fs from 'fs-extra';
import { vol } from 'memfs';
import os from 'os';
import { readPlistAsync } from '../../../utils/plist';
import {
BumpStrategy,
bumpVersionAsync,
bumpVersionInAppJsonAsync,
evaluateTemplateString,
getInfoPlistPath,
readBuildNumberAsync,
readShortVersionAsync,
} from '../version';
jest.mock('fs');
afterAll(async () => {
// do not remove the following line
// this fixes a weird error with tempy in @expo/image-utils
await fs.remove(os.tmpdir());
});
beforeEach(async () => {
vol.reset();
// do not remove the following line
// this fixes a weird error with tempy in @expo/image-utils
await fs.mkdirp(os.tmpdir());
});
describe(evaluateTemplateString, () => {
it('evaluates the template string when value is a number', () => {
expect(evaluateTemplateString('$(BLAH_BLAH)', { BLAH_BLAH: 123 })).toBe('123');
});
it('evaluates the template string when value is a string', () => {
expect(evaluateTemplateString('$(BLAH_BLAH)', { BLAH_BLAH: '123' })).toBe('123');
});
it('evaluates the template string when template is not the only element', () => {
expect(evaluateTemplateString('before$(BLAH_BLAH)after', { BLAH_BLAH: '123' })).toBe(
'before123after'
);
});
it('evaluates the template string when template value is double quoted', () => {
expect(evaluateTemplateString('before$(BLAH_BLAH)after', { BLAH_BLAH: '"123"' })).toBe(
'before123after'
);
});
});
// bare workflow
describe(bumpVersionAsync, () => {
it('bumps expo.ios.buildNumber and CFBundleVersion when strategy = BumpStrategy.BUILD_NUMBER', async () => {
const fakeExp = initBareWorkflowProject();
await bumpVersionAsync({
bumpStrategy: BumpStrategy.BUILD_NUMBER,
projectDir: '/repo',
exp: fakeExp,
buildSettings: {},
});
const appJSON = await fs.readJSON('/repo/app.json');
const infoPlist = (await readPlistAsync(
'/repo/ios/myproject/Info.plist'
)) as IOSConfig.InfoPlist;
expect(fakeExp.version).toBe('1.0.0');
expect(fakeExp.ios?.buildNumber).toBe('2');
expect(appJSON.expo.version).toBe('1.0.0');
expect(appJSON.expo.ios.buildNumber).toBe('2');
expect(infoPlist['CFBundleShortVersionString']).toBe('1.0.0');
expect(infoPlist['CFBundleVersion']).toBe('2');
});
it('bumps expo.ios.buildNumber and CFBundleVersion for non default Info.plist location', async () => {
const fakeExp = initBareWorkflowProject({ infoPlistName: 'Info2.plist' });
await bumpVersionAsync({
bumpStrategy: BumpStrategy.BUILD_NUMBER,
projectDir: '/repo',
exp: fakeExp,
buildSettings: {
INFOPLIST_FILE: '$(SRCROOT)/myproject/Info2.plist',
},
});
const appJSON = await fs.readJSON('/repo/app.json');
const infoPlist = (await readPlistAsync(
'/repo/ios/myproject/Info2.plist'
)) as IOSConfig.InfoPlist;
expect(fakeExp.version).toBe('1.0.0');
expect(fakeExp.ios?.buildNumber).toBe('2');
expect(appJSON.expo.version).toBe('1.0.0');
expect(appJSON.expo.ios.buildNumber).toBe('2');
expect(infoPlist['CFBundleShortVersionString']).toBe('1.0.0');
expect(infoPlist['CFBundleVersion']).toBe('2');
});
it('bumps expo.version and CFBundleShortVersionString when strategy = BumpStrategy.SHORT_VERSION', async () => {
const fakeExp = initBareWorkflowProject();
await bumpVersionAsync({
bumpStrategy: BumpStrategy.APP_VERSION,
projectDir: '/repo',
exp: fakeExp,
buildSettings: {},
});
const appJSON = await fs.readJSON('/repo/app.json');
const infoPlist = (await readPlistAsync(
'/repo/ios/myproject/Info.plist'
)) as IOSConfig.InfoPlist;
expect(fakeExp.version).toBe('1.0.1');
expect(fakeExp.ios?.buildNumber).toBe('1');
expect(appJSON.expo.version).toBe('1.0.1');
expect(appJSON.expo.ios.buildNumber).toBe('1');
expect(infoPlist['CFBundleShortVersionString']).toBe('1.0.1');
expect(infoPlist['CFBundleVersion']).toBe('1');
});
it('does not bump any version when strategy = BumpStrategy.NOOP', async () => {
const fakeExp = initBareWorkflowProject();
await bumpVersionAsync({
bumpStrategy: BumpStrategy.NOOP,
projectDir: '/repo',
exp: fakeExp,
buildSettings: {},
});
const appJSON = await fs.readJSON('/repo/app.json');
const infoPlist = (await readPlistAsync(
'/repo/ios/myproject/Info.plist'
)) as IOSConfig.InfoPlist;
expect(fakeExp.version).toBe('1.0.0');
expect(fakeExp.ios?.buildNumber).toBe('1');
expect(appJSON.expo.version).toBe('1.0.0');
expect(appJSON.expo.ios.buildNumber).toBe('1');
expect(infoPlist['CFBundleShortVersionString']).toBe('1.0.0');
expect(infoPlist['CFBundleVersion']).toBe('1');
});
});
// managed workflow
describe(bumpVersionInAppJsonAsync, () => {
it('bumps expo.ios.buildNumber when strategy = BumpStrategy.BUILD_NUMBER', async () => {
const fakeExp = initManagedProject();
await bumpVersionInAppJsonAsync({
bumpStrategy: BumpStrategy.BUILD_NUMBER,
projectDir: '/repo',
exp: fakeExp,
});
const appJSON = await fs.readJSON('/repo/app.json');
expect(fakeExp.version).toBe('1.0.0');
expect(fakeExp.ios?.buildNumber).toBe('2');
expect(appJSON.expo.version).toBe('1.0.0');
expect(appJSON.expo.ios.buildNumber).toBe('2');
});
it('bumps expo.version when strategy = BumpStrategy.SHORT_VERSION', async () => {
const fakeExp = initManagedProject();
await bumpVersionInAppJsonAsync({
bumpStrategy: BumpStrategy.APP_VERSION,
projectDir: '/repo',
exp: fakeExp,
});
const appJSON = await fs.readJSON('/repo/app.json');
expect(fakeExp.version).toBe('1.0.1');
expect(fakeExp.ios?.buildNumber).toBe('1');
expect(appJSON.expo.version).toBe('1.0.1');
expect(appJSON.expo.ios.buildNumber).toBe('1');
});
it('does not bump any version when strategy = BumpStrategy.NOOP', async () => {
const fakeExp = initManagedProject();
await bumpVersionInAppJsonAsync({
bumpStrategy: BumpStrategy.NOOP,
projectDir: '/repo',
exp: fakeExp,
});
const appJSON = await fs.readJSON('/repo/app.json');
expect(fakeExp.version).toBe('1.0.0');
expect(fakeExp.ios?.buildNumber).toBe('1');
expect(appJSON.expo.version).toBe('1.0.0');
expect(appJSON.expo.ios.buildNumber).toBe('1');
});
});
describe(readBuildNumberAsync, () => {
describe('bare project', () => {
it('reads the build number from native code', async () => {
const exp = initBareWorkflowProject();
const buildNumber = await readBuildNumberAsync('/repo', exp, {});
expect(buildNumber).toBe('1');
});
});
describe('managed project', () => {
it('reads the build number from expo config', async () => {
const exp = initManagedProject();
const buildNumber = await readBuildNumberAsync('/repo', exp, {});
expect(buildNumber).toBe('1');
});
});
});
describe(readShortVersionAsync, () => {
describe('bare project', () => {
it('reads the short version from native code', async () => {
const exp = initBareWorkflowProject();
const appVersion = await readShortVersionAsync('/repo', exp, {});
expect(appVersion).toBe('1.0.0');
});
it('evaluates interpolated build number', async () => {
const exp = initBareWorkflowProject({
appVersion: '$(CURRENT_PROJECT_VERSION)',
});
const buildNumber = await readShortVersionAsync('/repo', exp, {
CURRENT_PROJECT_VERSION: '1.0.0',
});
expect(buildNumber).toBe('1.0.0');
});
});
describe('managed project', () => {
it('reads the version from app config', async () => {
const exp = initBareWorkflowProject();
const appVersion = await readShortVersionAsync('/repo', exp, {});
expect(appVersion).toBe('1.0.0');
});
});
});
describe(getInfoPlistPath, () => {
it('returns default path if INFOPLIST_FILE is not specified', () => {
vol.fromJSON(
{
'./ios/testapp/Info.plist': '',
},
'/repo'
);
const plistPath = getInfoPlistPath('/repo', {});
expect(plistPath).toBe('/repo/ios/testapp/Info.plist');
});
it('returns INFOPLIST_FILE if specified', () => {
vol.fromJSON(
{
'./ios/testapp/Info.plist': '',
},
'/repo'
);
const plistPath = getInfoPlistPath('/repo', { INFOPLIST_FILE: './qwert/NotInfo.plist' });
expect(plistPath).toBe('/repo/ios/qwert/NotInfo.plist');
});
it('evaluates SRCROOT in Info.plist', () => {
vol.fromJSON(
{
'./ios/testapp/Info.plist': '',
},
'/repo'
);
const plistPath = getInfoPlistPath('/repo', {
INFOPLIST_FILE: '$(SRCROOT)/qwert/NotInfo.plist',
});
expect(plistPath).toBe('/repo/ios/qwert/NotInfo.plist');
});
it('evaluates BuildSettings in Info.plist', () => {
vol.fromJSON(
{
'./ios/testapp/Info.plist': '',
},
'/repo'
);
const plistPath = getInfoPlistPath('/repo', {
INFOPLIST_FILE: '$(SRCROOT)/qwert/$(TARGET_NAME).plist',
TARGET_NAME: 'NotInfo',
});
expect(plistPath).toBe('/repo/ios/qwert/NotInfo.plist');
});
});
function initBareWorkflowProject({
appVersion = '1.0.0',
version = '1',
infoPlistName = 'Info.plist',
}: { appVersion?: string; version?: string; infoPlistName?: string } = {}): ExpoConfig {
const fakeExp: ExpoConfig = {
name: 'myproject',
slug: 'myproject',
version: '1.0.0',
ios: {
buildNumber: '1',
},
};
vol.fromJSON(
{
'./app.json': JSON.stringify({
expo: fakeExp,
}),
[`./ios/myproject/${infoPlistName}`]: `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleShortVersionString</key>
<string>${appVersion}</string>
<key>CFBundleVersion</key>
<string>${version}</string>
</dict>
</plist>`,
},
'/repo'
);
return fakeExp;
}
function initManagedProject(): ExpoConfig {
const fakeExp: ExpoConfig = {
name: 'myproject',
slug: 'myproject',
version: '1.0.0',
ios: {
buildNumber: '1',
},
};
vol.fromJSON(
{
'./app.json': JSON.stringify({
expo: fakeExp,
}),
},
'/repo'
);
return fakeExp;
} | the_stack |
import { Assertion, Orbit } from '@orbit/core';
import {
buildQuery,
buildTransform,
DefaultRequestOptions,
FullRequestOptions,
FullResponse,
OperationTerm,
QueryOrExpressions,
RequestOptions,
TransformOrOperations
} from '@orbit/data';
import {
InitializedRecord,
RecordIdentity,
RecordOperation,
RecordOperationResult,
RecordOperationTerm,
RecordQuery,
RecordQueryBuilder,
RecordQueryExpression,
RecordQueryResult,
recordsReferencedByOperations,
RecordTransform,
RecordTransformBuilder,
RecordTransformBuilderFunc,
RecordTransformResult,
SyncRecordQueryable,
SyncRecordUpdatable
} from '@orbit/records';
import { deepGet, Dict, toArray } from '@orbit/utils';
import { SyncLiveQuery } from './live-query/sync-live-query';
import { SyncCacheIntegrityProcessor } from './operation-processors/sync-cache-integrity-processor';
import { SyncSchemaConsistencyProcessor } from './operation-processors/sync-schema-consistency-processor';
import { SyncSchemaValidationProcessor } from './operation-processors/sync-schema-validation-processor';
import {
SyncInverseTransformOperator,
SyncInverseTransformOperators
} from './operators/sync-inverse-transform-operators';
import {
SyncQueryOperator,
SyncQueryOperators
} from './operators/sync-query-operators';
import {
SyncTransformOperator,
SyncTransformOperators
} from './operators/sync-transform-operators';
import {
RecordChangeset,
RecordRelationshipIdentity,
SyncRecordAccessor
} from './record-accessor';
import {
RecordCache,
RecordCacheQueryOptions,
RecordCacheSettings,
RecordCacheTransformOptions
} from './record-cache';
import { RecordTransformBuffer } from './record-transform-buffer';
import { PatchResult, RecordCacheUpdateDetails } from './response';
import {
SyncOperationProcessor,
SyncOperationProcessorClass
} from './sync-operation-processor';
const { assert, deprecate } = Orbit;
export interface SyncRecordCacheSettings<
QO extends RequestOptions = RecordCacheQueryOptions,
TO extends RequestOptions = RecordCacheTransformOptions,
QB = RecordQueryBuilder,
TB = RecordTransformBuilder
> extends RecordCacheSettings<QO, TO, QB, TB> {
processors?: SyncOperationProcessorClass[];
queryOperators?: Dict<SyncQueryOperator>;
transformOperators?: Dict<SyncTransformOperator>;
inverseTransformOperators?: Dict<SyncInverseTransformOperator>;
debounceLiveQueries?: boolean;
transformBuffer?: RecordTransformBuffer;
}
export abstract class SyncRecordCache<
QO extends RequestOptions = RecordCacheQueryOptions,
TO extends RequestOptions = RecordCacheTransformOptions,
QB = RecordQueryBuilder,
TB = RecordTransformBuilder,
QueryResponseDetails = unknown,
TransformResponseDetails extends RecordCacheUpdateDetails = RecordCacheUpdateDetails
>
extends RecordCache<QO, TO, QB, TB>
implements
SyncRecordAccessor,
SyncRecordQueryable<QueryResponseDetails, QB, QO>,
SyncRecordUpdatable<TransformResponseDetails, TB, TO> {
protected _processors: SyncOperationProcessor[];
protected _queryOperators: Dict<SyncQueryOperator>;
protected _transformOperators: Dict<SyncTransformOperator>;
protected _inverseTransformOperators: Dict<SyncInverseTransformOperator>;
protected _debounceLiveQueries: boolean;
protected _transformBuffer?: RecordTransformBuffer;
constructor(settings: SyncRecordCacheSettings<QO, TO, QB, TB>) {
super(settings);
this._queryOperators = settings.queryOperators ?? SyncQueryOperators;
this._transformOperators =
settings.transformOperators ?? SyncTransformOperators;
this._inverseTransformOperators =
settings.inverseTransformOperators ?? SyncInverseTransformOperators;
this._debounceLiveQueries = settings.debounceLiveQueries !== false;
this._transformBuffer = settings.transformBuffer;
const processors: SyncOperationProcessorClass[] = settings.processors
? settings.processors
: [SyncSchemaConsistencyProcessor, SyncCacheIntegrityProcessor];
if (Orbit.debug && settings.processors === undefined) {
processors.push(SyncSchemaValidationProcessor);
}
this._processors = processors.map((Processor) => {
let processor = new Processor(this);
assert(
'Each processor must extend SyncOperationProcessor',
processor instanceof SyncOperationProcessor
);
return processor;
});
}
get processors(): SyncOperationProcessor[] {
return this._processors;
}
getQueryOperator(op: string): SyncQueryOperator {
return this._queryOperators[op];
}
getTransformOperator(op: string): SyncTransformOperator {
return this._transformOperators[op];
}
getInverseTransformOperator(op: string): SyncInverseTransformOperator {
return this._inverseTransformOperators[op];
}
// Abstract methods for getting records and relationships
abstract getRecordSync(
recordIdentity: RecordIdentity
): InitializedRecord | undefined;
abstract getRecordsSync(
typeOrIdentities?: string | RecordIdentity[]
): InitializedRecord[];
abstract getInverseRelationshipsSync(
recordIdentityOrIdentities: RecordIdentity | RecordIdentity[]
): RecordRelationshipIdentity[];
// Abstract methods for setting records and relationships
abstract setRecordSync(record: InitializedRecord): void;
abstract setRecordsSync(records: InitializedRecord[]): void;
abstract removeRecordSync(
recordIdentity: RecordIdentity
): InitializedRecord | undefined;
abstract removeRecordsSync(
recordIdentities: RecordIdentity[]
): InitializedRecord[];
abstract addInverseRelationshipsSync(
relationships: RecordRelationshipIdentity[]
): void;
abstract removeInverseRelationshipsSync(
relationships: RecordRelationshipIdentity[]
): void;
applyRecordChangesetSync(changeset: RecordChangeset): void {
const {
setRecords,
removeRecords,
addInverseRelationships,
removeInverseRelationships
} = changeset;
if (setRecords && setRecords.length > 0) {
this.setRecordsSync(setRecords);
}
if (removeRecords && removeRecords.length > 0) {
this.removeRecordsSync(removeRecords);
}
if (addInverseRelationships && addInverseRelationships.length > 0) {
this.addInverseRelationshipsSync(addInverseRelationships);
}
if (removeInverseRelationships && removeInverseRelationships.length > 0) {
this.removeInverseRelationshipsSync(removeInverseRelationships);
}
}
getRelatedRecordSync(
identity: RecordIdentity,
relationship: string
): RecordIdentity | null | undefined {
const record = this.getRecordSync(identity);
if (record) {
return deepGet(record, ['relationships', relationship, 'data']);
}
return undefined;
}
getRelatedRecordsSync(
identity: RecordIdentity,
relationship: string
): RecordIdentity[] | undefined {
const record = this.getRecordSync(identity);
if (record) {
return deepGet(record, ['relationships', relationship, 'data']);
}
return undefined;
}
/**
* Queries the cache.
*/
query<RequestData extends RecordQueryResult = RecordQueryResult>(
queryOrExpressions: QueryOrExpressions<RecordQueryExpression, QB>,
options?: DefaultRequestOptions<QO>,
id?: string
): RequestData;
query<RequestData extends RecordQueryResult = RecordQueryResult>(
queryOrExpressions: QueryOrExpressions<RecordQueryExpression, QB>,
options: FullRequestOptions<QO>,
id?: string
): FullResponse<RequestData, QueryResponseDetails, RecordOperation>;
query<RequestData extends RecordQueryResult = RecordQueryResult>(
queryOrExpressions: QueryOrExpressions<RecordQueryExpression, QB>,
options?: QO,
id?: string
):
| RequestData
| FullResponse<RequestData, QueryResponseDetails, RecordOperation> {
const query = buildQuery<RecordQueryExpression, QB>(
queryOrExpressions,
options,
id,
this._queryBuilder
);
const response = this._query<RequestData>(query, options);
if (options?.fullResponse) {
return response;
} else {
return response.data as RequestData;
}
}
/**
* Updates the cache.
*/
update<RequestData extends RecordTransformResult = RecordTransformResult>(
transformOrOperations: TransformOrOperations<RecordOperation, TB>,
options?: DefaultRequestOptions<TO>,
id?: string
): RequestData;
update<RequestData extends RecordTransformResult = RecordTransformResult>(
transformOrOperations: TransformOrOperations<RecordOperation, TB>,
options: FullRequestOptions<TO>,
id?: string
): FullResponse<RequestData, TransformResponseDetails, RecordOperation>;
update<RequestData extends RecordTransformResult = RecordTransformResult>(
transformOrOperations: TransformOrOperations<RecordOperation, TB>,
options?: TO,
id?: string
):
| RequestData
| FullResponse<RequestData, TransformResponseDetails, RecordOperation> {
const transform = buildTransform(
transformOrOperations,
options,
id,
this._transformBuilder
);
const response = this._update<RequestData>(transform, options);
if (options?.fullResponse) {
return response;
} else {
return response.data as RequestData;
}
}
/**
* Patches the cache with an operation or operations.
*
* @deprecated since v0.17
*/
patch(
operationOrOperations:
| RecordOperation
| RecordOperation[]
| RecordOperationTerm
| RecordOperationTerm[]
| RecordTransformBuilderFunc
): PatchResult {
deprecate(
'SyncRecordCache#patch has been deprecated. Use SyncRecordCache#update instead.'
);
// TODO - Why is this `this` cast necessary for TS to understand the correct
// method overload?
const { data, details } = (this as any).update(operationOrOperations, {
fullResponse: true
});
return {
inverse: details?.inverseOperations || [],
data: Array.isArray(data) ? data : [data]
};
}
liveQuery(
queryOrExpressions: QueryOrExpressions<RecordQueryExpression, QB>,
options?: DefaultRequestOptions<QO>,
id?: string
): SyncLiveQuery<QO, TO, QB, TB> {
const query = buildQuery(
queryOrExpressions,
options,
id,
this.queryBuilder
);
let debounce = options && (options as any).debounce;
if (typeof debounce !== 'boolean') {
debounce = this._debounceLiveQueries;
}
return new SyncLiveQuery<QO, TO, QB, TB>({
debounce,
cache: this,
query
});
}
/////////////////////////////////////////////////////////////////////////////
// Protected methods
/////////////////////////////////////////////////////////////////////////////
protected _query<RequestData extends RecordQueryResult = RecordQueryResult>(
query: RecordQuery,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
options?: QO
): FullResponse<RequestData, QueryResponseDetails, RecordOperation> {
let data;
if (Array.isArray(query.expressions)) {
data = [];
for (let expression of query.expressions) {
const queryOperator = this.getQueryOperator(expression.op);
if (!queryOperator) {
throw new Error(`Unable to find query operator: ${expression.op}`);
}
data.push(
queryOperator(
this,
expression,
this.getQueryOptions(query, expression)
)
);
}
} else {
const expression = query.expressions as RecordQueryExpression;
const queryOperator = this.getQueryOperator(expression.op);
if (!queryOperator) {
throw new Error(`Unable to find query operator: ${expression.op}`);
}
data = queryOperator(
this,
expression,
this.getQueryOptions(query, expression)
);
}
return { data: data as RequestData };
}
protected _update<
RequestData extends RecordTransformResult = RecordTransformResult
>(
transform: RecordTransform,
options?: TO
): FullResponse<RequestData, TransformResponseDetails, RecordOperation> {
if (this.getTransformOptions(transform)?.useBuffer) {
const buffer = this._initTransformBuffer(transform);
buffer.startTrackingChanges();
const response = buffer.update(transform, {
fullResponse: true
});
const changes = buffer.stopTrackingChanges();
this.applyRecordChangesetSync(changes);
const {
appliedOperations,
appliedOperationResults
} = response.details as TransformResponseDetails;
for (let i = 0, len = appliedOperations.length; i < len; i++) {
this.emit('patch', appliedOperations[i], appliedOperationResults[i]);
}
return response as FullResponse<
RequestData,
TransformResponseDetails,
RecordOperation
>;
} else {
const response = {
data: []
} as FullResponse<
RecordOperationResult[],
RecordCacheUpdateDetails,
RecordOperation
>;
if (options?.fullResponse) {
response.details = {
appliedOperations: [],
appliedOperationResults: [],
inverseOperations: []
};
}
let data: RecordTransformResult;
if (Array.isArray(transform.operations)) {
this._applyTransformOperations(
transform,
transform.operations,
response,
true
);
data = response.data;
} else {
this._applyTransformOperation(
transform,
transform.operations,
response,
true
);
if (Array.isArray(response.data)) {
data = response.data[0];
}
}
if (options?.fullResponse) {
response.details?.inverseOperations.reverse();
}
return {
...response,
data
} as FullResponse<RequestData, TransformResponseDetails, RecordOperation>;
}
}
protected _getTransformBuffer(): RecordTransformBuffer {
if (this._transformBuffer === undefined) {
throw new Assertion(
'transformBuffer must be provided to cache via constructor settings'
);
}
return this._transformBuffer;
}
protected _initTransformBuffer(
transform: RecordTransform
): RecordTransformBuffer {
const buffer = this._getTransformBuffer();
const records = recordsReferencedByOperations(
toArray(transform.operations)
);
const inverseRelationships = this.getInverseRelationshipsSync(records);
const relatedRecords = inverseRelationships.map((ir) => ir.record);
Array.prototype.push.apply(records, relatedRecords);
buffer.resetState();
buffer.setRecordsSync(this.getRecordsSync(records));
buffer.addInverseRelationshipsSync(inverseRelationships);
return buffer;
}
protected _applyTransformOperations(
transform: RecordTransform,
ops: RecordOperation[] | RecordOperationTerm[],
response: FullResponse<
RecordOperationResult[],
RecordCacheUpdateDetails,
RecordOperation
>,
primary = false
): void {
for (const op of ops) {
this._applyTransformOperation(transform, op, response, primary);
}
}
protected _applyTransformOperation(
transform: RecordTransform,
operation: RecordOperation | RecordOperationTerm,
response: FullResponse<
RecordOperationResult[],
RecordCacheUpdateDetails,
RecordOperation
>,
primary = false
): void {
if (operation instanceof OperationTerm) {
operation = operation.toOperation() as RecordOperation;
}
for (let processor of this._processors) {
processor.validate(operation);
}
const inverseTransformOperator = this.getInverseTransformOperator(
operation.op
);
const inverseOp: RecordOperation | undefined = inverseTransformOperator(
this,
operation,
this.getTransformOptions(transform, operation)
);
if (inverseOp) {
response.details?.inverseOperations?.push(inverseOp);
// Query and perform related `before` operations
for (let processor of this._processors) {
this._applyTransformOperations(
transform,
processor.before(operation),
response
);
}
// Query related `after` operations before performing
// the requested operation. These will be applied on success.
let preparedOps = [];
for (let processor of this._processors) {
preparedOps.push(processor.after(operation));
}
// Perform the requested operation
let transformOperator = this.getTransformOperator(operation.op);
let data = transformOperator(
this,
operation,
this.getTransformOptions(transform, operation)
);
if (primary) {
response.data?.push(data);
}
if (response.details) {
response.details.appliedOperationResults.push(data);
response.details.appliedOperations.push(operation);
}
// Query and perform related `immediate` operations
for (let processor of this._processors) {
processor.immediate(operation);
}
// Emit event
this.emit('patch', operation, data);
// Perform prepared operations after performing the requested operation
for (let ops of preparedOps) {
this._applyTransformOperations(transform, ops, response);
}
// Query and perform related `finally` operations
for (let processor of this._processors) {
this._applyTransformOperations(
transform,
processor.finally(operation),
response
);
}
} else if (primary) {
response.data?.push(undefined);
}
}
} | the_stack |
import {
IExplanationContext,
ModelTypes,
ModelExplanationUtils,
FabricStyles
} from "@responsible-ai/core-ui";
import { localization } from "@responsible-ai/localization";
import {
ChartBuilder,
AccessibleChart,
PlotlyMode,
IPlotlyProperty
} from "@responsible-ai/mlchartlib";
import _ from "lodash";
import memoize from "memoize-one";
import {
DefaultButton,
IconButton,
Callout,
ComboBox,
IComboBox,
IComboBoxOption,
IDropdownOption,
Slider
} from "office-ui-fabric-react";
import Plotly from "plotly.js";
import React from "react";
import { LoadingSpinner } from "../../SharedComponents/LoadingSpinner";
import { NoDataMessage } from "../../SharedComponents/NoDataMessage";
import { PlotlyUtils } from "../../SharedComponents/PlotlyUtils";
import { ScatterUtils } from "../Scatter/ScatterUtils";
import { beehiveStyles } from "./Beehive.styles";
import { FeatureImportanceModes } from "./FeatureImportanceModes";
import { IGlobalFeatureImportanceProps } from "./FeatureImportanceWrapper";
export interface IBeehiveState {
calloutContent?: React.ReactNode;
calloutId?: string;
selectedColorOption?: string;
plotlyProps: IPlotlyProperty | undefined;
}
interface IProjectedData {
rowIndex: string;
normalizedFeatureValue: number | undefined;
featureIndex: number;
ditheredFeatureIndex: number;
featureImportance: number;
predictedClass?: string | number;
predictedClassIndex?: number;
trueClass?: string | number;
trueClassIndex?: number;
tooltip: string;
}
export class Beehive extends React.PureComponent<
IGlobalFeatureImportanceProps,
IBeehiveState
> {
// To present all colors on a uniform color scale, the min and max of each feature are calculated
// once per dataset and
private static populateMappers: (
data: IExplanationContext
) => Array<(value: number | string) => number> = memoize(
(data: IExplanationContext): Array<(value: number | string) => number> => {
return data.modelMetadata.featureNames.map((_val, featureIndex) => {
if (data.modelMetadata.featureIsCategorical?.[featureIndex]) {
const values = _.uniq(
data.testDataset.dataset?.map((row) => row[featureIndex])
).sort();
return (value: string | number): number => {
return values.length > 1
? values.indexOf(value) / (values.length - 1)
: 0;
};
}
const featureArray =
data.testDataset.dataset?.map((row: number[]) => row[featureIndex]) ||
[];
const min = _.min(featureArray) || 0;
const max = _.max(featureArray) || 0;
const range = max - min;
return (value: string | number): number => {
return range !== 0 && typeof value === "number"
? (value - min) / range
: 0;
};
});
}
);
private static BasePlotlyProps: IPlotlyProperty = {
config: {
displaylogo: false,
displayModeBar: false,
responsive: true
},
data: [
{
datapointLevelAccessors: {
customdata: {
path: ["rowIndex"],
plotlyPath: "customdata"
},
text: {
path: ["tooltip"],
plotlyPath: "text"
}
},
hoverinfo: "text",
mode: PlotlyMode.Markers,
type: "scattergl",
xAccessor: "ditheredFeatureIndex",
yAccessor: "featureImportance"
}
],
layout: {
autosize: true,
dragmode: false,
font: {
size: 10
},
hovermode: "closest",
margin: {
b: 30,
t: 10
},
showlegend: false,
xaxis: {
automargin: true
},
yaxis: {
automargin: true,
title: localization.Interpret.featureImportance
}
}
};
private static maxFeatures = 30;
private static generateSortVector: (data: IExplanationContext) => number[] =
memoize((data: IExplanationContext): number[] => {
return data.globalExplanation?.perClassFeatureImportances
? ModelExplanationUtils.buildSortedVector(
data.globalExplanation.perClassFeatureImportances
)
: [];
});
private static projectData: (
data: IExplanationContext,
sortVector: number[]
) => IProjectedData[] = memoize(
(data: IExplanationContext, sortVector: number[]): IProjectedData[] => {
const mappers: Array<(value: string | number) => number> | undefined =
data.testDataset.dataset !== undefined
? Beehive.populateMappers(data)
: undefined;
const isClassifier =
data.modelMetadata.modelType !== ModelTypes.Regression;
return sortVector
.map((featureIndex, sortVectorIndex) => {
return (
data.localExplanation?.flattenedValues?.map((row, rowIndex) => {
const predictedClassIndex = data.testDataset.predictedY
? data.testDataset.predictedY[rowIndex]
: undefined;
const predictedClass = Beehive.getPredictedClass(
data,
isClassifier,
predictedClassIndex
);
const trueClassIndex = data.testDataset.trueY
? data.testDataset.trueY[rowIndex]
: undefined;
const trueClass = Beehive.getTrueClass(
data,
isClassifier,
trueClassIndex
);
return {
ditheredFeatureIndex:
sortVectorIndex + (0.2 * Math.random() - 0.1),
featureImportance: row[featureIndex],
featureIndex: sortVectorIndex,
normalizedFeatureValue:
mappers !== undefined &&
data.testDataset.dataset?.[rowIndex][featureIndex]
? mappers[featureIndex](
data.testDataset.dataset[rowIndex][featureIndex]
)
: undefined,
predictedClass,
predictedClassIndex,
rowIndex: rowIndex.toString(),
tooltip: Beehive.buildTooltip(data, rowIndex, featureIndex),
trueClass,
trueClassIndex
};
}) || []
);
})
.reduce((prev, curr) => {
prev.push(...curr);
return prev;
}, []);
},
_.isEqual.bind(window)
);
private static buildPlotlyProps: (
explanationContext: IExplanationContext,
sortVector: number[],
selectedOption: IComboBoxOption | undefined
) => IPlotlyProperty = memoize(
(
explanationContext: IExplanationContext,
sortVector: number[],
selectedOption: IComboBoxOption | undefined
): IPlotlyProperty => {
const plotlyProps = _.cloneDeep(Beehive.BasePlotlyProps);
const rows = Beehive.projectData(explanationContext, sortVector);
_.set(
plotlyProps,
"layout.xaxis.ticktext",
sortVector.map(
(i) => explanationContext.modelMetadata.featureNamesAbridged[i]
)
);
_.set(
plotlyProps,
"layout.xaxis.tickvals",
sortVector.map((_, index) => index)
);
if (explanationContext.modelMetadata.modelType === ModelTypes.Binary) {
_.set(
plotlyProps,
"layout.yaxis.title",
`${localization.Interpret.featureImportance}<br> ${localization.Interpret.ExplanationScatter.class} ${explanationContext.modelMetadata.classNames[0]}`
);
}
if (selectedOption === undefined || selectedOption.key === "none") {
PlotlyUtils.clearColorProperties(plotlyProps);
} else {
PlotlyUtils.setColorProperty(
plotlyProps,
selectedOption,
explanationContext.modelMetadata,
selectedOption.text
);
if (selectedOption.data.isNormalized && plotlyProps.data[0].marker) {
plotlyProps.data[0].marker.colorscale = [
[0, "rgba(0,0,255,0.5)"],
[1, "rgba(255,0,0,0.5)"]
];
_.set(plotlyProps.data[0], "marker.colorbar.tickvals", [0, 1]);
_.set(plotlyProps.data[0], "marker.colorbar.ticktext", [
localization.Interpret.AggregateImportance.low,
localization.Interpret.AggregateImportance.high
]);
} else {
_.set(plotlyProps.data[0], "marker.opacity", 0.6);
}
}
plotlyProps.data = ChartBuilder.buildPlotlySeries(
plotlyProps.data[0],
rows
);
return plotlyProps;
},
_.isEqual.bind(window)
);
private readonly _crossClassIconId = "cross-class-icon-id";
private readonly _globalSortIconId = "global-sort-icon-id";
private colorOptions: IDropdownOption[];
private rowCount: number;
public constructor(props: IGlobalFeatureImportanceProps) {
super(props);
this.colorOptions = this.buildColorOptions();
this.rowCount =
this.props.dashboardContext.explanationContext.localExplanation
?.flattenedValues?.length || 0;
const selectedColorIndex =
this.colorOptions.length > 1 && this.rowCount < 500 ? 1 : 0;
this.state = {
plotlyProps: undefined,
selectedColorOption: this.colorOptions[selectedColorIndex].key as string
};
}
private static getTrueClass(
data: IExplanationContext,
isClassifier: boolean,
trueClassIndex: number | undefined
): string | number | undefined {
if (data.testDataset.trueY) {
if (isClassifier && trueClassIndex !== undefined) {
return (
data.modelMetadata.classNames[trueClassIndex] ||
`class ${trueClassIndex}`
);
}
return trueClassIndex;
}
return undefined;
}
private static getPredictedClass(
data: IExplanationContext,
isClassifier: boolean,
predictedClassIndex: number | undefined
): string | number | undefined {
if (data.testDataset.predictedY) {
if (isClassifier && predictedClassIndex !== undefined) {
return (
data.modelMetadata.classNames[predictedClassIndex] ||
`class ${predictedClassIndex}`
);
}
return predictedClassIndex;
}
return undefined;
}
private static getFormattedImportance(
data: IExplanationContext,
rowIndex: number,
featureIndex: number
): string | number {
if (!data.localExplanation?.flattenedValues) {
return "";
}
if ((data.localExplanation?.flattenedValues?.length || 0) > 500) {
return data.localExplanation.flattenedValues[rowIndex][featureIndex];
}
return data.localExplanation.flattenedValues[rowIndex][
featureIndex
].toLocaleString(undefined, {
minimumFractionDigits: 3
});
}
private static buildTooltip(
data: IExplanationContext,
rowIndex: number,
featureIndex: number
): string {
const result = [];
// The formatString imputes are keys to loc object. This is because format string tries to use them as keys first, and only uses the passed in string after
// trowing an exception in a try block. This is very slow for repeated calls.
result.push(
localization.formatString(
"AggregateImportance.featureLabel",
data.modelMetadata.featureNames[featureIndex]
)
);
if (data.testDataset.dataset) {
result.push(
localization.formatString(
"AggregateImportance.valueLabel",
data.testDataset.dataset[rowIndex][featureIndex]
)
);
}
// formatting strings is slow, only do for small numbers
const formattedImportance = Beehive.getFormattedImportance(
data,
rowIndex,
featureIndex
);
result.push(
localization.formatString(
"AggregateImportance.importanceLabel",
formattedImportance
)
);
if (data.modelMetadata.modelType === ModelTypes.Regression) {
if (data.testDataset.predictedY) {
result.push(
localization.formatString(
"AggregateImportance.predictedOutputTooltip",
data.testDataset.predictedY[rowIndex]
)
);
}
if (data.testDataset.trueY) {
result.push(
localization.formatString(
"AggregateImportance.trueOutputTooltip",
data.testDataset.trueY[rowIndex]
)
);
}
} else {
if (data.testDataset.predictedY) {
const classIndex = data.testDataset.predictedY[rowIndex];
const className =
data.modelMetadata.classNames[classIndex] || "unknown class";
result.push(
localization.formatString(
"AggregateImportance.predictedClassTooltip",
className
)
);
}
if (data.testDataset.trueY) {
const classIndex = data.testDataset.trueY[rowIndex];
const className =
data.modelMetadata.classNames[classIndex] || "unknown class";
result.push(
localization.formatString(
"AggregateImportance.trueClassTooltip",
className
)
);
}
}
return result.join("<br>");
}
public render(): React.ReactNode {
if (
this.props.dashboardContext.explanationContext.testDataset !==
undefined &&
this.props.dashboardContext.explanationContext.localExplanation !==
undefined &&
this.props.dashboardContext.explanationContext.localExplanation.values !==
undefined
) {
if (this.rowCount > 10000) {
return (
<NoDataMessage
explanationStrings={[
{
displayText:
localization.Interpret.AggregateImportance.tooManyRows,
format: "text"
}
]}
/>
);
}
if (this.state.plotlyProps === undefined) {
this.loadProps();
return <LoadingSpinner />;
}
let plotlyProps = this.state.plotlyProps;
const weightContext = this.props.dashboardContext.weightContext;
const relayoutArg: Partial<Plotly.Layout> = {
"xaxis.range": [-0.5, this.props.config.topK - 0.5]
};
_.set(plotlyProps, "layout.xaxis.range", [
-0.5,
this.props.config.topK - 0.5
]);
plotlyProps = ScatterUtils.updatePropsForSelections(
plotlyProps,
this.props.selectedRow
);
return (
<div className={beehiveStyles.aggregateChart}>
<div className={beehiveStyles.topControls}>
<ComboBox
label={localization.Interpret.FeatureImportanceWrapper.chartType}
className={beehiveStyles.pathSelector}
selectedKey={FeatureImportanceModes.Beehive}
onChange={this.setChart}
options={this.props.chartTypeOptions}
ariaLabel={"chart type picker"}
useComboBoxAsMenuWidth
styles={FabricStyles.smallDropdownStyle}
/>
{this.colorOptions.length > 1 && (
<ComboBox
label={localization.Interpret.ExplanationScatter.colorValue}
className={beehiveStyles.pathSelector}
selectedKey={this.state.selectedColorOption}
onChange={this.setColor}
options={this.colorOptions}
ariaLabel={"color picker"}
useComboBoxAsMenuWidth
styles={FabricStyles.smallDropdownStyle}
/>
)}
<div className={beehiveStyles.sliderControl}>
<div className={beehiveStyles.sliderLabel}>
<span className={beehiveStyles.labelText}>
{localization.Interpret.AggregateImportance.topKFeatures}
</span>
{this.props.dashboardContext.explanationContext
.isGlobalDerived && (
<IconButton
id={this._globalSortIconId}
iconProps={{ iconName: "Info" }}
title={localization.Interpret.AggregateImportance.topKInfo}
onClick={this.showGlobalSortInfo}
styles={{
root: { color: "rgb(0, 120, 212)", marginBottom: -3 }
}}
/>
)}
</div>
<Slider
className={beehiveStyles.featureSlider}
ariaLabel={
localization.Interpret.AggregateImportance.topKFeatures
}
max={Math.min(
Beehive.maxFeatures,
this.props.dashboardContext.explanationContext.modelMetadata
.featureNames.length
)}
min={1}
step={1}
value={this.props.config.topK}
onChange={(value: number): void => this.setK(value)}
showValue
/>
</div>
{this.props.dashboardContext.explanationContext.modelMetadata
.modelType === ModelTypes.Multiclass && (
<div>
<div className={beehiveStyles.selectorLabel}>
<span>{localization.Interpret.CrossClass.label}</span>
<IconButton
id={this._crossClassIconId}
iconProps={{ iconName: "Info" }}
title={localization.Interpret.CrossClass.info}
onClick={this.showCrossClassInfo}
styles={{
root: { color: "rgb(0, 120, 212)", marginBottom: -3 }
}}
/>
</div>
<ComboBox
className={beehiveStyles.pathSelector}
selectedKey={weightContext.selectedKey}
onChange={weightContext.onSelection}
options={weightContext.options}
ariaLabel={"Cross-class weighting selector"}
useComboBoxAsMenuWidth
styles={FabricStyles.smallDropdownStyle}
/>
</div>
)}
</div>
{this.state.calloutContent && (
<Callout
target={`#${this.state.calloutId}`}
setInitialFocus
onDismiss={this.onDismiss}
role="alertdialog"
>
<div className={beehiveStyles.calloutInfo}>
{this.state.calloutContent}
<DefaultButton
onClick={this.onDismiss}
className={beehiveStyles.calloutButton}
>
{localization.Interpret.CrossClass.close}
</DefaultButton>
</div>
</Callout>
)}
<AccessibleChart
plotlyProps={plotlyProps}
onClickHandler={this.handleClick}
theme={this.props.theme}
relayoutArg={relayoutArg}
/>
</div>
);
}
if (
this.props.dashboardContext.explanationContext.localExplanation &&
this.props.dashboardContext.explanationContext.localExplanation
.percentComplete !== undefined
) {
return <LoadingSpinner />;
}
const explanationStrings = this.props.messages
? this.props.messages.LocalExpAndTestReq
: undefined;
return <NoDataMessage explanationStrings={explanationStrings} />;
}
private loadProps(): void {
setTimeout(() => {
const sortVector = Beehive.generateSortVector(
this.props.dashboardContext.explanationContext
)
.slice(-1 * Beehive.maxFeatures)
.reverse();
const props = Beehive.buildPlotlyProps(
this.props.dashboardContext.explanationContext,
sortVector,
this.colorOptions.find(
(option) => option.key === this.state.selectedColorOption
)
);
this.setState({ plotlyProps: props });
}, 1);
}
private handleClick = (data: any): void => {
const clickedId = (data.points[0] as any).customdata;
const selections: string[] =
this.props.selectionContext.selectedIds.slice();
const existingIndex = selections.indexOf(clickedId);
if (existingIndex !== -1) {
selections.splice(existingIndex, 1);
} else {
selections.push(clickedId);
}
this.props.selectionContext.onSelect(selections);
};
private showCrossClassInfo = (): void => {
if (this.state.calloutContent) {
this.onDismiss();
} else {
const calloutContent = (
<div>
<span>{localization.Interpret.CrossClass.overviewInfo}</span>
<ul>
<li>{localization.Interpret.CrossClass.absoluteValInfo}</li>
<li>{localization.Interpret.CrossClass.predictedClassInfo}</li>
<li>{localization.Interpret.CrossClass.enumeratedClassInfo}</li>
</ul>
</div>
);
this.setState({ calloutContent, calloutId: this._crossClassIconId });
}
};
private showGlobalSortInfo = (): void => {
if (this.state.calloutContent) {
this.onDismiss();
} else {
const calloutContent = (
<div>
<span>
{
localization.Interpret.FeatureImportanceWrapper
.globalImportanceExplanation
}
</span>
{this.props.dashboardContext.explanationContext.modelMetadata
.modelType === ModelTypes.Multiclass && (
<span>
{
localization.Interpret.FeatureImportanceWrapper
.multiclassImportanceAddendum
}
</span>
)}
<div>
<br />
</div>
</div>
);
this.setState({ calloutContent, calloutId: this._globalSortIconId });
}
};
private buildColorOptions(): IComboBoxOption[] {
const isRegression =
this.props.dashboardContext.explanationContext.modelMetadata.modelType ===
ModelTypes.Regression;
const result: IComboBoxOption[] = [
{
key: "none",
text: localization.Interpret.AggregateImportance.noColor
}
];
if (this.props.dashboardContext.explanationContext.testDataset.dataset) {
result.push({
data: { isCategorical: false, isNormalized: true },
key: "normalizedFeatureValue",
text: localization.Interpret.AggregateImportance.scaledFeatureValue
});
}
if (this.props.dashboardContext.explanationContext.testDataset.predictedY) {
result.push({
data: {
isCategorical: !isRegression,
sortProperty: !isRegression ? "predictedClassIndex" : undefined
},
key: "predictedClass",
text: isRegression
? localization.Interpret.AggregateImportance.predictedValue
: localization.Interpret.AggregateImportance.predictedClass
});
}
if (this.props.dashboardContext.explanationContext.testDataset.trueY) {
result.push({
data: {
isCategorical: !isRegression,
sortProperty: !isRegression ? "trueClassIndex" : undefined
},
key: "trueClass",
text: isRegression
? localization.Interpret.AggregateImportance.trueValue
: localization.Interpret.AggregateImportance.trueClass
});
}
return result;
}
private setChart = (
_event?: React.FormEvent<IComboBox>,
item?: IComboBoxOption
): void => {
if (!item?.key) {
return;
}
const newConfig = _.cloneDeep(this.props.config);
newConfig.displayMode = item.key as any;
this.props.onChange(newConfig, this.props.config.id);
};
private onDismiss = (): void => {
this.setState({ calloutContent: undefined, calloutId: undefined });
};
private setColor = (
_event?: React.FormEvent<IComboBox>,
item?: IComboBoxOption
): void => {
if (!item?.key) {
return;
}
this.setState({
plotlyProps: undefined,
selectedColorOption: item.key as string
});
};
private setK = (newValue: number): void => {
const newConfig = _.cloneDeep(this.props.config);
newConfig.topK = newValue;
this.props.onChange(newConfig, this.props.config.id);
};
} | the_stack |
import React from "react"
import { disposeOnUnmount, observer } from "../src"
import { render } from "@testing-library/react"
import { MockedComponentClass } from "react-dom/test-utils"
interface ClassC extends MockedComponentClass {
methodA?: any
methodB?: any
methodC?: any
methodD?: any
}
function testComponent(C: ClassC, afterMount?: Function, afterUnmount?: Function) {
const ref = React.createRef<ClassC>()
const { unmount } = render(<C ref={ref} />)
let cref = ref.current
expect(cref?.methodA).not.toHaveBeenCalled()
expect(cref?.methodB).not.toHaveBeenCalled()
if (afterMount) {
afterMount(cref)
}
unmount()
expect(cref?.methodA).toHaveBeenCalledTimes(1)
expect(cref?.methodB).toHaveBeenCalledTimes(1)
if (afterUnmount) {
afterUnmount(cref)
}
}
describe("without observer", () => {
test("class without componentWillUnmount", async () => {
class C extends React.Component {
@disposeOnUnmount
methodA = jest.fn()
@disposeOnUnmount
methodB = jest.fn()
@disposeOnUnmount
methodC = null
@disposeOnUnmount
methodD = undefined
render() {
return null
}
}
testComponent(C)
})
test("class with componentWillUnmount in the prototype", () => {
let called = 0
class C extends React.Component {
@disposeOnUnmount
methodA = jest.fn()
@disposeOnUnmount
methodB = jest.fn()
@disposeOnUnmount
methodC = null
@disposeOnUnmount
methodD = undefined
render() {
return null
}
componentWillUnmount() {
called++
}
}
testComponent(
C,
() => {
expect(called).toBe(0)
},
() => {
expect(called).toBe(1)
}
)
})
test("class with componentWillUnmount as an arrow function", () => {
let called = 0
class C extends React.Component {
@disposeOnUnmount
methodA = jest.fn()
@disposeOnUnmount
methodB = jest.fn()
@disposeOnUnmount
methodC = null
@disposeOnUnmount
methodD = undefined
render() {
return null
}
componentWillUnmount = () => {
called++
}
}
testComponent(
C,
() => {
expect(called).toBe(0)
},
() => {
expect(called).toBe(1)
}
)
})
test("class without componentWillUnmount using non decorator version", () => {
let methodC = jest.fn()
let methodD = jest.fn()
class C extends React.Component {
render() {
return null
}
methodA = disposeOnUnmount(this, jest.fn())
methodB = disposeOnUnmount(this, jest.fn())
constructor(props) {
super(props)
disposeOnUnmount(this, [methodC, methodD])
}
}
testComponent(
C,
() => {
expect(methodC).not.toHaveBeenCalled()
expect(methodD).not.toHaveBeenCalled()
},
() => {
expect(methodC).toHaveBeenCalledTimes(1)
expect(methodD).toHaveBeenCalledTimes(1)
}
)
})
})
describe("with observer", () => {
test("class without componentWillUnmount", () => {
@observer
class C extends React.Component {
@disposeOnUnmount
methodA = jest.fn()
@disposeOnUnmount
methodB = jest.fn()
@disposeOnUnmount
methodC = null
@disposeOnUnmount
methodD = undefined
render() {
return null
}
}
testComponent(C)
})
test("class with componentWillUnmount in the prototype", () => {
let called = 0
@observer
class C extends React.Component {
@disposeOnUnmount
methodA = jest.fn()
@disposeOnUnmount
methodB = jest.fn()
@disposeOnUnmount
methodC = null
@disposeOnUnmount
methodD = undefined
render() {
return null
}
componentWillUnmount() {
called++
}
}
testComponent(
C,
() => {
expect(called).toBe(0)
},
() => {
expect(called).toBe(1)
}
)
})
test("class with componentWillUnmount as an arrow function", () => {
let called = 0
@observer
class C extends React.Component {
@disposeOnUnmount
methodA = jest.fn()
@disposeOnUnmount
methodB = jest.fn()
@disposeOnUnmount
methodC = null
@disposeOnUnmount
methodD = undefined
render() {
return null
}
componentWillUnmount = () => {
called++
}
}
testComponent(
C,
() => {
expect(called).toBe(0)
},
() => {
expect(called).toBe(1)
}
)
})
test("class without componentWillUnmount using non decorator version", () => {
let methodC = jest.fn()
let methodD = jest.fn()
@observer
class C extends React.Component {
render() {
return null
}
methodA = disposeOnUnmount(this, jest.fn())
methodB = disposeOnUnmount(this, jest.fn())
constructor(props) {
super(props)
disposeOnUnmount(this, [methodC, methodD])
}
}
testComponent(
C,
() => {
expect(methodC).not.toHaveBeenCalled()
expect(methodD).not.toHaveBeenCalled()
},
() => {
expect(methodC).toHaveBeenCalledTimes(1)
expect(methodD).toHaveBeenCalledTimes(1)
}
)
})
})
it("componentDidMount should be different between components", () => {
function doTest(withObserver) {
const events: Array<string> = []
class A extends React.Component {
didMount
willUnmount
componentDidMount() {
this.didMount = "A"
events.push("mountA")
}
componentWillUnmount() {
this.willUnmount = "A"
events.push("unmountA")
}
render() {
return null
}
}
class B extends React.Component {
didMount
willUnmount
componentDidMount() {
this.didMount = "B"
events.push("mountB")
}
componentWillUnmount() {
this.willUnmount = "B"
events.push("unmountB")
}
render() {
return null
}
}
if (withObserver) {
// @ts-ignore
// eslint-disable-next-line no-class-assign
A = observer(A)
// @ts-ignore
// eslint-disable-next-line no-class-assign
B = observer(B)
}
const aRef = React.createRef<A>()
const { rerender, unmount } = render(<A ref={aRef} />)
const caRef = aRef.current
expect(caRef?.didMount).toBe("A")
expect(caRef?.willUnmount).toBeUndefined()
expect(events).toEqual(["mountA"])
const bRef = React.createRef<B>()
rerender(<B ref={bRef} />)
const cbRef = bRef.current
expect(caRef?.didMount).toBe("A")
expect(caRef?.willUnmount).toBe("A")
expect(cbRef?.didMount).toBe("B")
expect(cbRef?.willUnmount).toBeUndefined()
expect(events).toEqual(["mountA", "unmountA", "mountB"])
unmount()
expect(caRef?.didMount).toBe("A")
expect(caRef?.willUnmount).toBe("A")
expect(cbRef?.didMount).toBe("B")
expect(cbRef?.willUnmount).toBe("B")
expect(events).toEqual(["mountA", "unmountA", "mountB", "unmountB"])
}
doTest(true)
doTest(false)
})
test("base cWU should not be called if overriden", () => {
let baseCalled = 0
let dCalled = 0
let oCalled = 0
class C extends React.Component {
componentWillUnmount() {
baseCalled++
}
constructor(props) {
super(props)
this.componentWillUnmount = () => {
oCalled++
}
}
render() {
return null
}
@disposeOnUnmount
fn() {
dCalled++
}
}
const { unmount } = render(<C />)
unmount()
expect(dCalled).toBe(1)
expect(oCalled).toBe(1)
expect(baseCalled).toBe(0)
})
test("should error on inheritance", () => {
class C extends React.Component {
render() {
return null
}
}
expect(() => {
// eslint-disable-next-line no-unused-vars
class B extends C {
@disposeOnUnmount
fn() {}
}
}).toThrow("disposeOnUnmount only supports direct subclasses")
})
test("should error on inheritance - 2", () => {
class C extends React.Component {
render() {
return null
}
}
class B extends C {
fn
constructor(props) {
super(props)
expect(() => {
this.fn = disposeOnUnmount(this, function() {})
}).toThrow("disposeOnUnmount only supports direct subclasses")
}
}
render(<B />)
})
describe("should work with arrays", () => {
test("as a function", () => {
class C extends React.Component {
methodA = jest.fn()
methodB = jest.fn()
componentDidMount() {
disposeOnUnmount(this, [this.methodA, this.methodB])
}
render() {
return null
}
}
testComponent(C)
})
test("as a decorator", () => {
class C extends React.Component {
methodA = jest.fn()
methodB = jest.fn()
@disposeOnUnmount
disposers = [this.methodA, this.methodB]
render() {
return null
}
}
testComponent(C)
})
})
it("runDisposersOnUnmount only runs disposers from the declaring instance", () => {
class A extends React.Component {
@disposeOnUnmount
a = jest.fn()
b = jest.fn()
constructor(props) {
super(props)
disposeOnUnmount(this, this.b)
}
render() {
return null
}
}
const ref1 = React.createRef<A>()
const ref2 = React.createRef<A>()
const { unmount } = render(<A ref={ref1} />)
render(<A ref={ref2} />)
const inst1 = ref1.current
const inst2 = ref2.current
unmount()
expect(inst1?.a).toHaveBeenCalledTimes(1)
expect(inst1?.b).toHaveBeenCalledTimes(1)
expect(inst2?.a).toHaveBeenCalledTimes(0)
expect(inst2?.b).toHaveBeenCalledTimes(0)
}) | the_stack |
import * as fs from "fs"
import * as path from "path"
import * as fse from "fs-extra";
import * as jsdom from "jsdom";
import { exit } from "process";
import * as readlineSync from "readline-sync";
const { JSDOM } = jsdom
/*
builds the browser website
actually this does only parses the given sites and places all
script
link
tag targets into the dist folder...
*/
// console.log(__dirname)
//see output of console.log(__dirname)
const pathModPath = `../../../browser/`
const basePath = path.join(__dirname, pathModPath)
const distPath = path.join(basePath, `dist`)
const assetsPrefixDir = `assets`
const assetsDistPath = path.join(distPath, assetsPrefixDir)
const sourceMapLineRegex = /^\/\/# sourceMappingURL=(.*)$/gm
type PathNameTuple = {
outputName: string
originalFullPath: string
}
//because we collapse the paths to only start with assets/[NAME]
//we could get name collisions... we use these vars to indicate duplicate names and throw an error (must be fixed manually somehow)
const jsScriptPathNames = new Map<string, PathNameTuple>()
const cssLinkPathNames = new Map<string, PathNameTuple>()
const imgPathNames = new Map<string, PathNameTuple>()
//this is relative to csvEditorHtml/browser/
const htmlFilePathsToBuild: string[] = [
`indexBrowser.html`,
`legalNotice.html`,
`privacy.html`,
]
//this is relative to csvEditorHtml/browser/
//directories ends with /
const justCopyPaths = [
[`../../thirdParty/fortawesome/fontawesome-free/webfonts/`, `webfonts/`]
]
//we inject the hash into the file name and .htaccess should rewrite the urls...
const buildHash = uuidv4()
function main() {
const ensureDistDirAndAssetsExists = () => {
try {
if (fs.existsSync(distPath)) {
console.log(`[INFO] dist path exists ${distPath}`)
} else {
console.log(`[INFO] dist path does NOT exist ... creating dir ${distPath}`)
fs.mkdirSync(distPath)
}
} catch (error) {
console.log(`[ERROR] could not check or create dist path ${distPath}`)
console.log(`[ERROR] error`, error)
exit(1)
return
}
try {
if (fs.existsSync(assetsDistPath)) {
console.log(`[INFO] dist path assets exists ${assetsDistPath}`)
} else {
console.log(`[INFO] dist assets path does NOT exist ... creating dir ${assetsDistPath}`)
fs.mkdirSync(assetsDistPath)
}
} catch (error) {
console.log(`[ERROR] could not check or create dist assets path ${assetsDistPath}`)
console.log(`[ERROR] error`, error)
exit(1)
return
}
}
ensureDistDirAndAssetsExists()
let _distEntries: string[] = []
try {
_distEntries = fs.readdirSync(distPath)
} catch (error) {
//this is ok if the dist path does not exists
console.log(`[ERROR] could not check if the dist dist dir is empty ${distPath}`)
console.log(`[ERROR] error`, error)
exit(1)
return
}
if (_distEntries.length > 0) {
console.log(`[INFO] dist dir: ${distPath}`)
const should = readlineSync.question(`[QUESTION] the dist dir already contains output, do you want to clear it (else we just overwrite)? (y/n) (default n)`)
if (should === 'y') {
try {
fse.removeSync(distPath)
} catch (error) {
console.log(`[ERROR] could not delete dist dir content ${distPath}`)
console.log(`[ERROR] error`, error)
exit(1)
return
}
//after we deleted everything, we need to re-create the dirs
ensureDistDirAndAssetsExists()
}
}
//--- just copy section
console.log()
console.log(`[INFO] --- just copying ---`)
console.log()
{
for (let i = 0; i < justCopyPaths.length; i++) {
const justCopyPath = justCopyPaths[i];
const sourcePath = path.join(basePath, justCopyPath[0])
const outputPath = path.join(distPath, justCopyPath[1])
console.log(`[INFO] copying recursively from ${sourcePath} to ${outputPath}`)
try {
fse.copySync(sourcePath, outputPath)
} catch (error) {
console.log(`[ERROR] could not copy from ${sourcePath} to ${outputPath}`)
console.log(`[ERROR] error`, error)
exit(1)
}
}
}
console.log()
console.log(`[INFO] --- processing html files ---`)
console.log()
for (let i = 0; i < htmlFilePathsToBuild.length; i++) {
const htmlFilePath = htmlFilePathsToBuild[i]
const absoluteHtmlFilePath = path.join(basePath, htmlFilePath)
try {
const stat = fs.statSync(absoluteHtmlFilePath)
if (!stat.isFile()) {
console.log(`[ERROR] file: ${absoluteHtmlFilePath} is not a file (found directory)`)
exit(1)
continue
}
} catch (error) {
console.log(`[ERROR] could not find file: ${absoluteHtmlFilePath}`)
console.log(`[ERROR] error: `, error)
exit(1)
continue
}
//read file
let content = ''
try {
content = fs.readFileSync(absoluteHtmlFilePath, 'utf8')
} catch (error) {
console.log(`[ERROR] could not read file: ${absoluteHtmlFilePath}`)
console.log(`[ERROR] error: `, error)
exit(1)
continue
}
console.log(``)
console.log(``)
console.log(`[INFO] read file ${absoluteHtmlFilePath}`)
console.log(``)
console.log(``)
const dom = new JSDOM(content)
const { document } = dom.window
const links = getAllCssLinkElements(document)
const scripts = getAllScriptElements(document)
const imgs = getAllImgElements(document)
const allAnchors = getAllAnchorElements(document)
const comments = getAllCommentElements(document, dom)
//--- now copy files to dist dir
console.log()
console.log(`[INFO] --- removing comments (${comments.length}) ---`)
for (let j = 0; j < comments.length; j++) {
const commentNode = comments[j]
commentNode.remove()
console.log(`[INFO] removed comment: ${commentNode.textContent}`)
}
// const afterCopiedHandlers: Array<() => void> = []
console.log()
console.log(`[INFO] --- css files (${links.length}) ---`)
for (let j = 0; j < links.length; j++) {
const cssLink = links[j]
let fileName = path.basename(cssLink.href)
let fileParts = getFilePars(fileName)
let hrefPath = cssLink.href.substr(0, cssLink.href.length - fileName.length)
const newFileName = `${fileParts.namePart}.${buildHash}.${fileParts.extensionPart}`
const cssLinkSourcePath = path.join(basePath, cssLink.href)
const outputPath = path.join(assetsDistPath, fileName)
console.log(`[INFO] found candidate css file (${j + 1}) relative path: ${cssLink.href}, absolute path: ${cssLinkSourcePath} ...`)
checkAndAddCssFilePath(fileName, cssLinkSourcePath)
//copy is step 1
try {
fs.copyFileSync(cssLinkSourcePath, outputPath)
console.log(`[INFO] ... copyied css file ${cssLinkSourcePath} to ${outputPath}`)
} catch (error) {
console.log(`[ERROR] ... error copying css file ${cssLinkSourcePath} to ${outputPath}`)
throw error
}
//now we need to replace the path in the html file...
const _pathKeepDepth = cssLink.getAttribute('data-path-keep-depth')
if (!_pathKeepDepth) {
cssLink.href = path.join(assetsPrefixDir, newFileName)
} else {
const pathKeepDepth = parseInt(_pathKeepDepth)
if (isNaN(pathKeepDepth)) {
console.log(`[ERROR] invalid data-path-keep-depth value`)
exit(1)
return
}
cssLink.removeAttribute('data-path-keep-depth')
let dirPaths: string[] = []
for (let k = 0; k < pathKeepDepth; k++) {
let dirName = path.basename(hrefPath)
dirPaths.unshift(dirName)
hrefPath = hrefPath.substr(0, hrefPath.length - dirName.length - 1) //1 because the trailing /
}
//now we need to replace the path in the html file...
cssLink.href = path.join(...dirPaths, newFileName)
}
}
console.log()
console.log(`[INFO] --- script files (${scripts.length}) ---`)
for (let j = 0; j < scripts.length; j++) {
const scriptTag = scripts[j]
const scriptSourceSrcPath = path.join(basePath, scriptTag.src)
let fileName = path.basename(scriptSourceSrcPath)
let fileParts = getFilePars(fileName)
const newFileName = `${fileParts.namePart}.${buildHash}.${fileParts.extensionPart}`
const outputPath = path.join(assetsDistPath, fileName)
console.log(`[INFO] found candidate script file (${j + 1}) relative path: ${scriptTag.src}, absolute path: ${scriptSourceSrcPath}`)
checkAndAddJsFilePath(fileName, scriptSourceSrcPath)
//copy is step 1
try {
copyFileSyncAndChangeContent(scriptSourceSrcPath, outputPath, replaceJsSourceMapLine)
console.log(`[INFO] ... copyied script file ${scriptSourceSrcPath} to ${outputPath}`)
} catch (error) {
console.log(`[ERROR] ... error copying script file ${scriptSourceSrcPath} to ${outputPath}`)
throw error
}
//now we need to replace the path in the html file...
scriptTag.src = path.join(assetsPrefixDir, newFileName)
}
console.log()
console.log(`[INFO] --- img files (${imgs.length}) ---`)
for (let j = 0; j < imgs.length; j++) {
const imgTag = imgs[j]
const imgSourceSrcPath = path.join(basePath, imgTag.src)
let fileName = path.basename(imgTag.src)
let fileParts = getFilePars(fileName)
const newFileName = `${fileParts.namePart}.${buildHash}.${fileParts.extensionPart}`
const outputPath = path.join(assetsDistPath, fileName)
console.log(`[INFO] found candidate img file (${j + 1}) relative path: ${imgTag.src}, absolute path: ${imgSourceSrcPath} ...`)
checkAndAddImgFilePath(fileName, imgSourceSrcPath)
//copy is step 1
try {
fs.copyFileSync(imgSourceSrcPath, outputPath)
console.log(`[INFO] ... copyied img file ${imgSourceSrcPath} to ${outputPath}`)
} catch (error) {
console.log(`[ERROR] ... error copying img file ${imgSourceSrcPath} to ${outputPath}`)
throw error
}
//now we need to replace the path in the html file...
imgTag.src = path.join(assetsPrefixDir, newFileName)
}
//--- all fiels are copied now create html file with replaced paths
//make sure all anchors use no
{
for (let j = 0; j < allAnchors.length; j++) {
const anchor = allAnchors[j]
anchor.rel = `noopener noreferrer`
}
}
const outputHtml = dom.serialize()
const htmlOutputPath = path.join(distPath, path.basename(absoluteHtmlFilePath))
console.log(`[IFNO] writing re-written html file to ${htmlOutputPath}`)
fs.writeFileSync(htmlOutputPath, outputHtml, 'utf8')
}
console.log(``)
console.log(`[INFO] finished`)
}
main()
/**
* returns all css linkls that have a href
* use data-path-keep-depth attribute to keep the number of dirs from the path (from target to root), then we don't use the assets prefix dir
* @param document
*/
function getAllCssLinkElements(document: Document): HTMLLinkElement[] {
const cssLinkElements: HTMLLinkElement[] = []
const allCssLinks = document.querySelectorAll(`link`)
for (let j = 0; j < allCssLinks.length; j++) {
const cssLink = allCssLinks.item(j)
if (!cssLink.href) continue
cssLinkElements.push(cssLink)
}
return cssLinkElements
}
/**
* returns all script tags that have a src
* @param document
*/
function getAllScriptElements(document: Document): HTMLScriptElement[] {
const scriptElements: HTMLScriptElement[] = []
const allScripts = document.querySelectorAll(`script`)
for (let j = 0; j < allScripts.length; j++) {
const scriptTag = allScripts.item(j)
if (!scriptTag.src) continue
//external scripts
if (scriptTag.src.startsWith("http")) continue
scriptElements.push(scriptTag)
}
return scriptElements
}
/**
* returns all img tags that have a src
* @param document
*/
function getAllImgElements(document: Document): HTMLImageElement[] {
const imgElements: HTMLImageElement[] = []
const allImgs = document.querySelectorAll(`img`)
for (let j = 0; j < allImgs.length; j++) {
const imgTag = allImgs.item(j)
if (!imgTag.src) continue
imgElements.push(imgTag)
}
return imgElements
}
/**
* returns all a tags that have a href
* @param document
*/
function getAllAnchorElements(document: Document): HTMLAnchorElement[] {
const elements: HTMLAnchorElement[] = []
const allTags = document.querySelectorAll(`a`)
for (let j = 0; j < allTags.length; j++) {
const imgTag = allTags.item(j)
if (!imgTag.href) continue
elements.push(imgTag)
}
return elements
}
/**
* returns all comment nodes
* @param document
*/
function getAllCommentElements(document: Document, dom: jsdom.JSDOM): Comment[] {
const elements: Comment[] = []
const commentIterator = document.createNodeIterator(document,
dom.window.NodeFilter.SHOW_COMMENT, {
acceptNode: (node) => dom.window.NodeFilter.FILTER_ACCEPT
})
while (commentIterator.nextNode()) {
const commentNode = commentIterator.referenceNode as Comment
elements.push(commentNode)
}
return elements
}
function copyFileSyncAndChangeContent(filePath: string, outputPath: string, replaceFunc: (content: string) => string) {
try {
const content = fs.readFileSync(filePath, 'utf8')
const newContent = replaceFunc(content)
fs.writeFileSync(outputPath, newContent, 'utf8')
} catch (error) {
throw error
}
}
function replaceJsSourceMapLine(jsFileContent: string): string {
const cleanJs = jsFileContent.replace(sourceMapLineRegex, '\n')
return cleanJs
}
/**
* used for cache busting, see https://css-tricks.com/strategies-for-cache-busting-css/
* better not use query string ... better: file.hash.ext
* see https://stackoverflow.com/questions/105034/how-to-create-guid-uuid
*/
function uuidv4(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8)
return v.toString(16);
})
}
type FileParts = {
namePart: string
extensionPart: string
}
/**
* returns the parts (name, extension) of a file name (not a path!)
*/
function getFilePars(fileName: string): FileParts {
if (fileName.indexOf("/") !== -1 || fileName.indexOf("\\") !== -1) throw new Error(`only file names are allowed`)
const parts = fileName.split('.')
return {
namePart: parts[0],
extensionPart: parts.slice(1).join('.')
}
}
function checkAndAddCssFilePath(cssFileName: string, fullCssLinkSourcePath: string) {
if (cssLinkPathNames.has(cssFileName)) {
const otherFile = cssLinkPathNames.get(cssFileName)
//this can actually happen if we use the exact same css file twice e.g. with preloading
if (otherFile?.originalFullPath !== fullCssLinkSourcePath) {
//we already got this file name... throw
throw new Error(`[ERROR] other CSS file has the same output name '${cssFileName}'! The other file full path is '${otherFile?.originalFullPath}', the current file full path is '${fullCssLinkSourcePath}'`)
}
}
cssLinkPathNames.set(cssFileName, {
outputName: cssFileName,
originalFullPath: fullCssLinkSourcePath
})
}
function checkAndAddJsFilePath(jsFileName: string, fullJsLinkSourcePath: string) {
if (cssLinkPathNames.has(jsFileName)) {
const otherFile = jsScriptPathNames.get(jsFileName)
//we already got this file name... throw
throw new Error(`[ERROR] other JS file has the same output name '${jsFileName}'! The other file full path is '${otherFile?.originalFullPath}', the current file full path is '${fullJsLinkSourcePath}'`)
}
jsScriptPathNames.set(jsFileName, {
outputName: jsFileName,
originalFullPath: fullJsLinkSourcePath
})
}
function checkAndAddImgFilePath(imgFileName: string, fullImgLinkSourcePath: string) {
if (cssLinkPathNames.has(imgFileName)) {
const otherFile = imgPathNames.get(imgFileName)
//we already got this file name... throw
throw new Error(`[ERROR] other IMG file has the same output name '${imgFileName}'! The other file full path is '${otherFile?.originalFullPath}', the current file full path is '${fullImgLinkSourcePath}'`)
}
imgPathNames.set(imgFileName, {
outputName: imgFileName,
originalFullPath: fullImgLinkSourcePath
})
} | the_stack |
import { $, $$ } from 'common-sk/modules/dom';
import 'codemirror/mode/clike/clike'; // Syntax highlighting for c-like languages.
import { define } from 'elements-sk/define';
import { html, TemplateResult } from 'lit-html';
import { unsafeHTML } from 'lit-html/directives/unsafe-html';
import { errorMessage } from 'elements-sk/errorMessage';
import CodeMirror from 'codemirror';
import { stateReflector } from 'common-sk/modules/stateReflector';
import { HintableObject } from 'common-sk/modules/hintable';
import { isDarkMode } from '../../../infra-sk/modules/theme-chooser-sk/theme-chooser-sk';
import type {
CanvasKit,
CanvasKitInit as CKInit,
Surface,
Canvas,
Paint,
} from '../../build/canvaskit/canvaskit';
import 'elements-sk/error-toast-sk';
import 'elements-sk/styles/buttons';
import 'elements-sk/styles/select';
import 'elements-sk/icon/edit-icon-sk';
import 'elements-sk/icon/add-icon-sk';
import 'elements-sk/icon/delete-icon-sk';
import '../../../infra-sk/modules/theme-chooser-sk';
import { SKIA_VERSION } from '../../build/version';
import { ElementSk } from '../../../infra-sk/modules/ElementSk/ElementSk';
import '../../../infra-sk/modules/uniform-fps-sk';
import '../../../infra-sk/modules/uniform-time-sk';
import '../../../infra-sk/modules/uniform-generic-sk';
import '../../../infra-sk/modules/uniform-dimensions-sk';
import '../../../infra-sk/modules/uniform-slider-sk';
import '../../../infra-sk/modules/uniform-mouse-sk';
import '../../../infra-sk/modules/uniform-color-sk';
import '../../../infra-sk/modules/uniform-imageresolution-sk';
import { UniformControl } from '../../../infra-sk/modules/uniform/uniform';
import { DimensionsChangedEventDetail } from '../../../infra-sk/modules/uniform-dimensions-sk/uniform-dimensions-sk';
import {
defaultScrapBody,
defaultShader, numPredefinedUniformLines, predefinedUniforms, ShaderNode,
} from '../shadernode';
import { EditChildShaderSk } from '../edit-child-shader-sk/edit-child-shader-sk';
import '../edit-child-shader-sk';
// It is assumed that canvaskit.js has been loaded and this symbol is available globally.
declare const CanvasKitInit: typeof CKInit;
// This element might be loaded from a different site, and that means we need
// to be careful about how we construct the URL back to the canvas.wasm file.
// Start by recording the script origin.
const scriptOrigin = new URL((document!.currentScript as HTMLScriptElement).src).origin;
const kitReady = CanvasKitInit({
locateFile: (file: string) => `${scriptOrigin}/dist/${file}`,
});
const DEFAULT_SIZE = 512;
type stateChangedCallback = ()=> void;
// This works around a TS lint rule included in Bazel rules which requires promises be awaited
// on. We do not necessarily want to await on errorMessage, especially when we tell the error
// message to be up indefinitely.
// eslint-disable-next-line @typescript-eslint/no-empty-function,@typescript-eslint/no-unused-vars
function doNotWait(_: Promise<unknown>) {}
// State represents data reflected to/from the URL.
interface State {
id: string;
}
const defaultState: State = {
id: '@default',
};
// CodeMirror likes mode definitions as maps to bools, but a string of space
// separated words is easier to edit, so we convert between the two format.
function words(str: string): {[key: string]: boolean} {
const obj: any = {};
str.split(/\s+/).forEach((word) => {
if (!word) {
return;
}
obj[word] = true;
});
return obj;
}
// See the design doc for the list of keywords. http://go/shaders.skia.org.
const keywords = `const attribute uniform varying break continue
discard return for while do if else struct in out inout uniform layout`;
const blockKeywords = 'case do else for if switch while struct enum union';
const defKeywords = 'struct enum union';
const builtins = `radians degrees
sin cos tan asin acos atan
pow exp log exp2 log2
sqrt inversesqrt
abs sign floor ceil fract mod
min max clamp saturate
mix step smoothstep
length distance dot cross normalize
faceforward reflect refract
matrixCompMult inverse
lessThan lessThanEqual greaterThan greaterThanEqual equal notEqual
any all not
sample unpremul `;
const types = `int long char short double float unsigned
signed void bool float float2 float3 float4
float2x2 float3x3 float4x4
half half2 half3 half4
half2x2 half3x3 half4x4
bool bool2 bool3 bool4
int int2 int3 int4
fragmentProcessor shader
vec2 vec3 vec4
ivec2 ivec3 ivec4
bvec2 bvec3 bvec4
mat2 mat3 mat4`;
// Define a new mode and mime-type for SkSL shaders. We follow the shader naming
// covention found in CodeMirror.
CodeMirror.defineMIME('x-shader/x-sksl', {
name: 'clike',
keywords: words(keywords),
types: words(types),
builtin: words(builtins),
blockKeywords: words(blockKeywords),
defKeywords: words(defKeywords),
typeFirstDefinitions: true,
atoms: words('sk_FragCoord true false'),
modeProps: { fold: ['brace', 'include'] },
});
/** requestAnimationFrame id if requestAnimationFrame is not running. */
const RAF_NOT_RUNNING = -1;
export class ShadersAppSk extends ElementSk {
private width: number = DEFAULT_SIZE;
private height: number = DEFAULT_SIZE;
private codeMirror: CodeMirror.Editor | null = null;
private canvasEle: HTMLCanvasElement | null = null;
private kit: CanvasKit | null = null;
private surface: Surface | null = null;
private canvas: Canvas | null = null;
private paint: Paint | null = null;
private rootShaderNode: ShaderNode | null = null;
private currentNode: ShaderNode | null = null;
/**
* Records the lines that have been marked as having errors. We keep these
* around so we can clear the error annotations efficiently.
*/
private compileErrorLines: CodeMirror.TextMarker[] = [];
private state: State = defaultState;
/** The requestAnimationFrame id if we are running, otherwise we are not running. */
private rafID: number = RAF_NOT_RUNNING;
/** stateReflector update function. */
private stateChanged: stateChangedCallback | null = null;
private uniformControlsNeedingRAF: UniformControl[] = [];
/**
* Calculated when we render, it count the number of controls that are for
* predefined uniforms, as opposed to user uniform controls.
*/
private numPredefinedUniformControls: number = 0;
private editChildShaderControl: EditChildShaderSk | null = null;
constructor() {
super(ShadersAppSk.template);
}
private static deleteButton = (ele: ShadersAppSk, parentNode: ShaderNode | null, node: ShaderNode, index: number): TemplateResult => {
if (ele.rootShaderNode === node || parentNode === null) {
return html``;
}
return html`
<button
class=deleteButton
title="Delete child shader."
@click=${(e: Event) => ele.removeChildShader(e, parentNode, index)}>
<delete-icon-sk></delete-icon-sk>
</button>
`;
}
private static editButton = (ele: ShadersAppSk, parentNode: ShaderNode | null, node: ShaderNode, index: number): TemplateResult => {
if (ele.rootShaderNode === node || parentNode === null) {
return html``;
}
return html`
<button
class=editButton
title="Edit child shader uniform name."
@click=${(e: Event) => ele.editChildShader(e, parentNode, index)}>
<edit-icon-sk></edit-icon-sk>
</button>
`;
}
private static displayShaderTreeImpl = (ele: ShadersAppSk, parentNode: ShaderNode | null, node: ShaderNode, depth: number = 0, name: string = '/', childIndex: number = 0): TemplateResult[] => {
let ret: TemplateResult[] = [];
// Prepend some fixed width spaces based on the depth so we get a nested
// directory type of layout. See https://en.wikipedia.org/wiki/Figure_space.
const prefix = new Array(depth).fill('  ').join('');
ret.push(html`
<p
class="childShader"
@click=${() => ele.childShaderClick(node)}>
<span>
${unsafeHTML(prefix)}
<span class=linkish>${name}</span>
${(ele.rootShaderNode!.children.length > 0 && ele.currentNode === node) ? '*' : ''}
</span>
<span>
${ShadersAppSk.deleteButton(ele, parentNode, node, childIndex)}
${ShadersAppSk.editButton(ele, parentNode, node, childIndex)}
<button
class=addButton
title="Append a new child shader."
@click=${(e: Event) => ele.appendChildShader(e, node)}>
<add-icon-sk></add-icon-sk>
</button>
</span>
</p>`);
node.children.forEach((childNode, index) => {
ret = ret.concat(ShadersAppSk.displayShaderTreeImpl(ele, node, childNode, depth + 1, node.getChildShaderUniformName(index), index));
});
return ret;
}
private static displayShaderTree = (ele: ShadersAppSk): TemplateResult[] => {
if (!ele.rootShaderNode) {
return [
html``,
];
}
return ShadersAppSk.displayShaderTreeImpl(ele, null, ele.rootShaderNode);
}
private static uniformControls = (ele: ShadersAppSk): TemplateResult[] => {
const ret: TemplateResult[] = [
html`<uniform-fps-sk></uniform-fps-sk>`, // Always start with the fps control.
];
ele.numPredefinedUniformControls = 1;
const node = ele.currentNode;
if (!node) {
return ret;
}
for (let i = 0; i < node.getUniformCount(); i++) {
const uniform = node.getUniform(i);
if (!uniform.name.startsWith('i')) {
continue;
}
switch (uniform.name) {
case 'iTime':
ele.numPredefinedUniformControls++;
ret.push(html`<uniform-time-sk .uniform=${uniform}></uniform-time-sk>`);
break;
case 'iMouse':
ele.numPredefinedUniformControls++;
ret.push(html`<uniform-mouse-sk .uniform=${uniform} .elementToMonitor=${ele.canvasEle}></uniform-mouse-sk>`);
break;
case 'iResolution':
ele.numPredefinedUniformControls++;
ret.push(html`
<uniform-dimensions-sk
.uniform=${uniform}
@dimensions-changed=${ele.dimensionsChanged}
></uniform-dimensions-sk>`);
break;
case 'iImageResolution':
// No-op. This is no longer handled via uniform control, the
// dimensions are handed directly into the ShaderNode from the image
// measurements.
break;
default:
if (uniform.name.toLowerCase().indexOf('color') !== -1) {
ret.push(html`<uniform-color-sk .uniform=${uniform}></uniform-color-sk>`);
} else if (uniform.rows === 1 && uniform.columns === 1) {
ret.push(html`<uniform-slider-sk .uniform=${uniform}></uniform-slider-sk>`);
} else {
ret.push(html`<uniform-generic-sk .uniform=${uniform}></uniform-generic-sk>`);
}
break;
}
}
return ret;
}
private static template = (ele: ShadersAppSk) => html`
<header>
<h2><a href="/">SkSL Shaders</a></h2>
<span>
<a
id="githash"
href="https://skia.googlesource.com/skia/+show/${SKIA_VERSION}"
>
${SKIA_VERSION.slice(0, 7)}
</a>
<theme-chooser-sk></theme-chooser-sk>
</span>
</header>
<main>
<div>
<p id=examples @click=${ele.fastLoad}>
Examples:
<a href="/?id=@inputs">Uniforms</a>
<a href="/?id=@iResolution">iResolution</a>
<a href="/?id=@iTime">iTime</a>
<a href="/?id=@iMouse">iMouse</a>
<a href="/?id=@iImage">iImage</a>
</p>
<canvas
id="player"
width=${ele.width}
height=${ele.height}
>
Your browser does not support the canvas tag.
</canvas>
<div>
${ShadersAppSk.displayShaderTree(ele)}
</div>
</div>
<div>
<details id=shaderinputs>
<summary>Shader Inputs</summary>
<textarea rows=${numPredefinedUniformLines} cols=75 readonly id="predefinedShaderInputs">${predefinedUniforms}</textarea>
<div id=imageSources>
<figure>
${ele.currentNode?.inputImageElement}
<figcaption>iImage1</figcaption>
</figure>
<details id=image_edit>
<summary><edit-icon-sk></edit-icon-sk></summary>
<div id=image_edit_dialog>
<label for=image_url>
Change the URL used for the source image.
</label>
<div>
<input type=url id=image_url placeholder="URL of image to use." .value="${ele.currentNode?.getSafeImageURL() || ''}">
<button @click=${ele.imageURLChanged}>Use</button>
</div>
<label for=image_upload>
Or upload an image to <em>temporarily</em> try as a source for the shader. Uploaded images are not saved.
</label>
<div>
<input @change=${ele.imageUploaded} type=file id=image_upload accept="image/*">
</div>
</div>
</details>
</div>
</details>
<textarea style="display: ${ele.currentNode?.children.length ? 'block' : 'none'}" rows=${ele.currentNode?.children.length || 0} cols=75>${ele.currentNode?.getChildShaderUniforms() || ''}</textarea>
<div id="codeEditor"></div>
<div ?hidden=${!ele.currentNode?.compileErrorMessage} id="compileErrors">
<h3>Errors</h3>
<pre>${ele.currentNode?.compileErrorMessage}</pre>
</div>
</div>
<div id=shaderControls>
<div id=uniformControls @input=${ele.uniformControlsChange} @change=${ele.uniformControlsChange}>
${ShadersAppSk.uniformControls(ele)}
</div>
<button
?hidden=${!ele.rootShaderNode?.needsCompile()}
@click=${ele.runClick}
class=action
>
Run
</button>
<button
?hidden=${!ele.rootShaderNode?.needsSave()}
@click=${ele.saveClick}
class=action
>
Save
</button>
</div>
</main>
<footer>
<edit-child-shader-sk></edit-child-shader-sk>
<error-toast-sk></error-toast-sk>
</footer>
`;
/** Returns the CodeMirror theme based on the state of the page's darkmode.
*
* For this to work the associated CSS themes must be loaded. See
* shaders-app-sk.scss.
*/
private static themeFromCurrentMode = () => (isDarkMode() ? 'ambiance' : 'base16-light');
connectedCallback(): void {
super.connectedCallback();
this._render();
this.canvasEle = $$<HTMLCanvasElement>('#player', this);
this.codeMirror = CodeMirror($$<HTMLDivElement>('#codeEditor', this)!, {
lineNumbers: true,
mode: 'x-shader/x-sksl',
theme: ShadersAppSk.themeFromCurrentMode(),
viewportMargin: Infinity,
scrollbarStyle: 'native',
});
this.codeMirror.on('change', () => this.codeChange());
this.editChildShaderControl = $$('edit-child-shader-sk', this);
// Listen for theme changes.
document.addEventListener('theme-chooser-toggle', () => {
this.codeMirror!.setOption('theme', ShadersAppSk.themeFromCurrentMode());
});
// Continue the setup once CanvasKit WASM has loaded.
kitReady.then(async (ck: CanvasKit) => {
this.kit = ck;
this.paint = new this.kit.Paint();
try {
this.stateChanged = stateReflector(
/* getState */ () => (this.state as unknown) as HintableObject,
/* setState */ async (newState: HintableObject) => {
this.state = (newState as unknown) as State;
this.rootShaderNode = new ShaderNode(this.kit!);
this.currentNode = this.rootShaderNode;
if (!this.state.id) {
await this.rootShaderNode.setScrap(defaultScrapBody);
this.run();
} else {
await this.loadShaderIfNecessary();
}
},
);
} catch (error) {
doNotWait(errorMessage(error, 0));
}
});
}
private dimensionsChanged(e: Event) {
const newDims = (e as CustomEvent<DimensionsChangedEventDetail>).detail;
this.width = newDims.width;
this.height = newDims.height;
this.run();
}
private monitorIfDevicePixelRatioChanges() {
// Use matchMedia to detect if the screen resolution changes from the current value.
// See https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio#monitoring_screen_resolution_or_zoom_level_changes
const mqString = `(resolution: ${window.devicePixelRatio}dppx)`;
matchMedia(mqString).addEventListener('change', () => this.run());
}
private async loadShaderIfNecessary() {
if (!this.state.id) {
return;
}
try {
await this.rootShaderNode!.loadScrap(this.state.id);
this._render();
this.setUniformValuesToControls();
this.run();
} catch (error) {
doNotWait(errorMessage(error, 0));
// Return to the default view.
this.state = Object.assign({}, defaultState);
this.stateChanged!();
}
}
private run() {
this.monitorIfDevicePixelRatioChanges();
// Cancel any pending drawFrames.
if (this.rafID !== RAF_NOT_RUNNING) {
cancelAnimationFrame(this.rafID);
this.rafID = RAF_NOT_RUNNING;
}
// TODO(jcgregorio) In the long run maybe store scrollInfo and cursorPos
// temporarily for each child shader so we restore the right view as the
// user moves between child shaders?
// Save the scroll info and the cursor position before updating the code.
const scrollInfo = this.codeMirror!.getScrollInfo();
const cursorPos = this.codeMirror!.getCursor();
// Set code.
this.codeMirror!.setValue(this.currentNode?.shaderCode || defaultShader);
// Restore scroll info and cursor position.
this.codeMirror!.setCursor(cursorPos);
// Oddly CodeMirror TS doesn't have a Type defined for this shape.
const scrollPosition = {
left: scrollInfo.left,
top: scrollInfo.top,
right: scrollInfo.left + scrollInfo.width,
bottom: scrollInfo.top + scrollInfo.height,
};
this.codeMirror!.scrollIntoView(scrollPosition);
// eslint-disable-next-line no-unused-expressions
this.surface?.delete();
this.surface = this.kit!.MakeCanvasSurface(this.canvasEle!);
if (!this.surface) {
doNotWait(errorMessage('Could not make Surface.', 0));
return;
}
// We don't need to call .delete() on the canvas because
// the parent surface will do that for us.
this.canvas = this.surface.getCanvas();
this.clearAllEditorErrorAnnotations();
this.rootShaderNode!.compile();
// Set CodeMirror errors if the run failed.
this.currentNode!.compileErrorLineNumbers.forEach((lineNumber: number) => {
this.setEditorErrorLineAnnotation(lineNumber);
});
// Render so the uniform controls get displayed.
this._render();
this.drawFrame();
}
private clearAllEditorErrorAnnotations(): void {
// eslint-disable-next-line no-unused-expressions
this.compileErrorLines?.forEach((textMarker) => {
textMarker.clear();
});
}
private setEditorErrorLineAnnotation(lineNumber: number): void {
// Set the class of that line to 'cm-error'.
this.compileErrorLines.push(this.codeMirror!.markText(
{ line: lineNumber - 1, ch: 0 },
{ line: lineNumber - 1, ch: 200 }, // Some large number for the character offset.
{
className: 'cm-error', // See the base16-dark.css file in CodeMirror for the class name.
},
));
}
/** Populate the uniforms values from the controls. */
private getUserUniformValuesFromControls(): number[] {
const uniforms: number[] = new Array(this.currentNode!.getUniformFloatCount()).fill(0);
$('#uniformControls > *').slice(this.numPredefinedUniformControls).forEach((control) => {
(control as unknown as UniformControl).applyUniformValues(uniforms);
});
return uniforms.slice(this.currentNode?.numPredefinedUniformValues || 0);
}
private getPredefinedUniformValuesFromControls(): number[] {
const uniforms: number[] = new Array(this.currentNode!.getUniformFloatCount()).fill(0);
$('#uniformControls > *').slice(0, this.numPredefinedUniformControls).forEach((control) => {
(control as unknown as UniformControl).applyUniformValues(uniforms);
});
return uniforms;
}
/** Populate the control values from the uniforms. */
private setUniformValuesToControls(): void {
const predefinedUniformValues = new Array(this.currentNode!.numPredefinedUniformValues).fill(0);
const uniforms = predefinedUniformValues.concat(this.currentNode!.currentUserUniformValues);
$('#uniformControls > *').forEach((control) => {
(control as unknown as UniformControl).restoreUniformValues(uniforms);
});
this.findAllUniformControlsThatNeedRAF();
}
private findAllUniformControlsThatNeedRAF(): void {
this.uniformControlsNeedingRAF = [];
$('#uniformControls > *').forEach((control) => {
const uniformControl = (control as unknown as UniformControl);
if (uniformControl.needsRAF()) {
this.uniformControlsNeedingRAF.push(uniformControl);
}
});
}
private uniformControlsChange() {
this.currentNode!.currentUserUniformValues = this.getUserUniformValuesFromControls();
this._render();
}
private drawFrame() {
const shader = this.currentNode!.getShader(this.getPredefinedUniformValuesFromControls());
if (!shader) {
return;
}
// Allow uniform controls to update, such as uniform-timer-sk.
this.uniformControlsNeedingRAF.forEach((element) => {
element.onRAF();
});
// Draw the shader.
this.canvas!.clear(this.kit!.BLACK);
this.paint!.setShader(shader);
const rect = this.kit!.XYWHRect(0, 0, this.width, this.height);
this.canvas!.drawRect(rect, this.paint!);
this.surface!.flush();
this.rafID = requestAnimationFrame(() => {
this.drawFrame();
});
}
private async runClick() {
this.run();
await this.saveClick();
}
private async saveClick() {
try {
this.state.id = await this.rootShaderNode!.saveScrap();
this.stateChanged!();
this._render();
} catch (error) {
doNotWait(errorMessage(`${error}`, 0));
}
}
private imageUploaded(e: Event) {
const input = e.target as HTMLInputElement;
if (!input.files?.length) {
return;
}
const file = input.files.item(0)!;
this.setCurrentImageURL(URL.createObjectURL(file));
}
private imageURLChanged(): void {
const input = $$<HTMLInputElement>('#image_url', this)!;
if (!input.value) {
return;
}
this.setCurrentImageURL(input.value);
}
private codeChange() {
if (!this.currentNode) {
return;
}
this.currentNode.shaderCode = this.codeMirror!.getValue();
this._render();
}
private async appendChildShader(e: Event, node: ShaderNode) {
e.stopPropagation();
try {
await node.appendNewChildShader();
this._render();
await this.runClick();
} catch (error) {
doNotWait(errorMessage(error));
}
}
private async removeChildShader(e: Event, parentNode: ShaderNode, index: number) {
e.stopPropagation();
// We could write a bunch of complicated logic to track which current shader
// is selected and restore that correctly on delete, or we can just always
// shove the focus back to rootShaderNode which will always work, so we do
// the latter.
this.childShaderClick(this.rootShaderNode!);
parentNode.removeChildShader(index);
this._render();
await this.runClick();
}
private async editChildShader(e: Event, parentNode: ShaderNode, index: number) {
e.stopPropagation();
const editedChildShader = await this.editChildShaderControl!.show(parentNode.getChildShader(index));
if (!editedChildShader) {
return;
}
await parentNode.setChildShaderUniformName(index, editedChildShader.UniformName);
this._render();
await this.runClick();
}
private childShaderClick(node: ShaderNode) {
this.currentNode = node;
this.codeMirror!.setValue(this.currentNode?.shaderCode || defaultShader);
this._render();
this.setUniformValuesToControls();
}
/**
* Load example by changing state rather than actually following the links.
*/
private async fastLoad(e: Event): Promise<void> {
const ele = (e.target as HTMLLinkElement);
if (ele.tagName !== 'A') {
return;
}
e.preventDefault();
// When switching shaders clear the file upload.
$$<HTMLInputElement>('#image_upload')!.value = '';
const id = new URL(ele.href).searchParams.get('id') || '';
this.state.id = id;
this.stateChanged!();
await this.loadShaderIfNecessary();
}
private setCurrentImageURL(url: string): void {
const oldURL = this.currentNode!.getCurrentImageURL();
// Release unused memory.
if (oldURL.startsWith('blob:')) {
URL.revokeObjectURL(oldURL);
}
this.currentNode!.setCurrentImageURL(url).then(() => this._render());
}
}
define('shaders-app-sk', ShadersAppSk); | the_stack |
export default Aigle;
export { Aigle };
declare class Aigle<R> implements PromiseLike<R> {
constructor(
executor: (
resolve: (thenableOrResult?: R | PromiseLike<R>) => void,
reject: (error?: any) => void,
onCancel?: (callback: () => void) => void
) => void
);
static get [Symbol.species](): typeof Aigle;
then<T>(
onFulfill?: (value: R) => Aigle.ReturnType<T>,
onReject?: (error: any) => Aigle.ReturnType<T>
): Aigle<T>;
then<TResult1 = R, TResult2 = never>(
onfulfilled?: ((value: R) => Aigle.ReturnType<TResult1>) | null,
onrejected?: ((reason: any) => Aigle.ReturnType<TResult2>) | null
): Aigle<TResult1 | TResult2>;
/* catch */
catch(onReject: (error: any) => Aigle.ReturnType<R>): Aigle<R>;
catch<T>(onReject: ((error: any) => Aigle.ReturnType<T>) | undefined | null): Aigle<T | R>;
catch<E1>(filter1: Aigle.CatchFilter<E1>, onReject: (error: E1) => Aigle.ReturnType<R>): Aigle<R>;
catch<E1, E2>(
filter1: Aigle.CatchFilter<E1>,
filter2: Aigle.CatchFilter<E2>,
onReject: (error: E1 | E2) => Aigle.ReturnType<R>
): Aigle<R>;
catch<E1, E2, E3>(
filter1: Aigle.CatchFilter<E1>,
filter2: Aigle.CatchFilter<E2>,
filter3: Aigle.CatchFilter<E3>,
onReject: (error: E1 | E2 | E3) => Aigle.ReturnType<R>
): Aigle<R>;
catch<E1, E2, E3, E4>(
filter1: Aigle.CatchFilter<E1>,
filter2: Aigle.CatchFilter<E2>,
filter3: Aigle.CatchFilter<E3>,
filter4: Aigle.CatchFilter<E4>,
onReject: (error: E1 | E2 | E3 | E4) => Aigle.ReturnType<R>
): Aigle<R>;
catch<E1, E2, E3, E4, E5>(
filter1: Aigle.CatchFilter<E1>,
filter2: Aigle.CatchFilter<E2>,
filter3: Aigle.CatchFilter<E3>,
filter4: Aigle.CatchFilter<E4>,
filter5: Aigle.CatchFilter<E5>,
onReject: (error: E1 | E2 | E3 | E4 | E5) => Aigle.ReturnType<R>
): Aigle<R>;
catch<T, E1>(
filter1: Aigle.CatchFilter<E1>,
onReject: (error: E1) => Aigle.ReturnType<T>
): Aigle<T | R>;
catch<T, E1, E2>(
filter1: Aigle.CatchFilter<E1>,
filter2: Aigle.CatchFilter<E2>,
onReject: (error: E1 | E2) => Aigle.ReturnType<T>
): Aigle<T | R>;
catch<T, E1, E2, E3>(
filter1: Aigle.CatchFilter<E1>,
filter2: Aigle.CatchFilter<E2>,
filter3: Aigle.CatchFilter<E3>,
onReject: (error: E1 | E2 | E3) => Aigle.ReturnType<T>
): Aigle<T | R>;
catch<T, E1, E2, E3, E4>(
filter1: Aigle.CatchFilter<E1>,
filter2: Aigle.CatchFilter<E2>,
filter3: Aigle.CatchFilter<E3>,
filter4: Aigle.CatchFilter<E4>,
onReject: (error: E1 | E2 | E3 | E4) => Aigle.ReturnType<T>
): Aigle<T | R>;
catch<T, E1, E2, E3, E4, E5>(
filter1: Aigle.CatchFilter<E1>,
filter2: Aigle.CatchFilter<E2>,
filter3: Aigle.CatchFilter<E3>,
filter4: Aigle.CatchFilter<E4>,
filter5: Aigle.CatchFilter<E5>,
onReject: (error: E1 | E2 | E3 | E4 | E5) => Aigle.ReturnType<T>
): Aigle<T | R>;
/* finally */
finally<T>(handler: () => Aigle.ReturnType<T>): Aigle<R>;
/* all */
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
* resolve, or rejected when any Promise is rejected.
* @param values An array of Promises.
* @returns A new Aigle.
*/
all<T1>(this: Aigle<[T1 | PromiseLike<T1>]>): Aigle<[T1]>;
all<T1, T2>(this: Aigle<[T1 | PromiseLike<T1>, T2 | PromiseLike<T2>]>): Aigle<[T1, T2]>;
all<T1, T2, T3>(
this: Aigle<[T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>]>
): Aigle<[T1, T2, T3]>;
all<T1, T2, T3, T4>(
this: Aigle<
[T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>]
>
): Aigle<[T1, T2, T3, T4]>;
all<T1, T2, T3, T4, T5>(
this: Aigle<
[
T1 | PromiseLike<T1>,
T2 | PromiseLike<T2>,
T3 | PromiseLike<T3>,
T4 | PromiseLike<T4>,
T5 | PromiseLike<T5>
]
>
): Aigle<[T1, T2, T3, T4, T5]>;
all<T1, T2, T3, T4, T5, T6>(
this: Aigle<
[
T1 | PromiseLike<T1>,
T2 | PromiseLike<T2>,
T3 | PromiseLike<T3>,
T4 | PromiseLike<T4>,
T5 | PromiseLike<T5>,
T6 | PromiseLike<T6>
]
>
): Aigle<[T1, T2, T3, T4, T5, T6]>;
all<T1, T2, T3, T4, T5, T6, T7>(
this: Aigle<
[
T1 | PromiseLike<T1>,
T2 | PromiseLike<T2>,
T3 | PromiseLike<T3>,
T4 | PromiseLike<T4>,
T5 | PromiseLike<T5>,
T6 | PromiseLike<T6>,
T7 | PromiseLike<T7>
]
>
): Aigle<[T1, T2, T3, T4, T5, T6, T7]>;
all<T1, T2, T3, T4, T5, T6, T7, T8>(
this: Aigle<
[
T1 | PromiseLike<T1>,
T2 | PromiseLike<T2>,
T3 | PromiseLike<T3>,
T4 | PromiseLike<T4>,
T5 | PromiseLike<T5>,
T6 | PromiseLike<T6>,
T7 | PromiseLike<T7>,
T8 | PromiseLike<T8>
]
>
): Aigle<[T1, T2, T3, T4, T5, T6, T7, T8]>;
all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
this: Aigle<
[
T1 | PromiseLike<T1>,
T2 | PromiseLike<T2>,
T3 | PromiseLike<T3>,
T4 | PromiseLike<T4>,
T5 | PromiseLike<T5>,
T6 | PromiseLike<T6>,
T7 | PromiseLike<T7>,
T8 | PromiseLike<T8>,
T9 | PromiseLike<T9>
]
>
): Aigle<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
this: Aigle<
[
T1 | PromiseLike<T1>,
T2 | PromiseLike<T2>,
T3 | PromiseLike<T3>,
T4 | PromiseLike<T4>,
T5 | PromiseLike<T5>,
T6 | PromiseLike<T6>,
T7 | PromiseLike<T7>,
T8 | PromiseLike<T8>,
T9 | PromiseLike<T9>,
T10 | PromiseLike<T10>
]
>
): Aigle<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
all<T>(this: Aigle<(T | PromiseLike<T>)[]>): Aigle<T[]>;
/* allSettled */
allSettled<T1>(
this: Aigle<[T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>]>
): Aigle<[Aigle.AllSettledResponse<T1>]>;
allSettled<T1, T2>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>
]
>
): Aigle<[Aigle.AllSettledResponse<T1>, Aigle.AllSettledResponse<T2>]>;
allSettled<T1, T2, T3>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>
]
>
): Aigle<
[Aigle.AllSettledResponse<T1>, Aigle.AllSettledResponse<T2>, Aigle.AllSettledResponse<T3>]
>;
allSettled<T1, T2, T3, T4>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>
]
>
): Aigle<
[
Aigle.AllSettledResponse<T1>,
Aigle.AllSettledResponse<T2>,
Aigle.AllSettledResponse<T3>,
Aigle.AllSettledResponse<T4>
]
>;
allSettled<T1, T2, T3, T4, T5>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>
]
>
): Aigle<
[
Aigle.AllSettledResponse<T1>,
Aigle.AllSettledResponse<T2>,
Aigle.AllSettledResponse<T3>,
Aigle.AllSettledResponse<T4>,
Aigle.AllSettledResponse<T5>
]
>;
allSettled<T1, T2, T3, T4, T5, T6>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>
]
>
): Aigle<
[
Aigle.AllSettledResponse<T1>,
Aigle.AllSettledResponse<T2>,
Aigle.AllSettledResponse<T3>,
Aigle.AllSettledResponse<T4>,
Aigle.AllSettledResponse<T5>,
Aigle.AllSettledResponse<T6>
]
>;
allSettled<T1, T2, T3, T4, T5, T6, T7>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>
]
>
): Aigle<
[
Aigle.AllSettledResponse<T1>,
Aigle.AllSettledResponse<T2>,
Aigle.AllSettledResponse<T3>,
Aigle.AllSettledResponse<T4>,
Aigle.AllSettledResponse<T5>,
Aigle.AllSettledResponse<T6>,
Aigle.AllSettledResponse<T7>
]
>;
allSettled<T1, T2, T3, T4, T5, T6, T7, T8>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>,
T8 | PromiseLike<T8> | Aigle.PromiseCallback<T8>
]
>
): Aigle<
[
Aigle.AllSettledResponse<T1>,
Aigle.AllSettledResponse<T2>,
Aigle.AllSettledResponse<T3>,
Aigle.AllSettledResponse<T4>,
Aigle.AllSettledResponse<T5>,
Aigle.AllSettledResponse<T6>,
Aigle.AllSettledResponse<T7>,
Aigle.AllSettledResponse<T8>
]
>;
allSettled<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>,
T8 | PromiseLike<T8> | Aigle.PromiseCallback<T8>,
T9 | PromiseLike<T9> | Aigle.PromiseCallback<T9>
]
>
): Aigle<
[
Aigle.AllSettledResponse<T1>,
Aigle.AllSettledResponse<T2>,
Aigle.AllSettledResponse<T3>,
Aigle.AllSettledResponse<T4>,
Aigle.AllSettledResponse<T5>,
Aigle.AllSettledResponse<T6>,
Aigle.AllSettledResponse<T7>,
Aigle.AllSettledResponse<T8>,
Aigle.AllSettledResponse<T9>
]
>;
allSettled<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>,
T8 | PromiseLike<T8> | Aigle.PromiseCallback<T8>,
T9 | PromiseLike<T9> | Aigle.PromiseCallback<T9>,
T10 | PromiseLike<T10> | Aigle.PromiseCallback<T10>
]
>
): Aigle<
[
Aigle.AllSettledResponse<T1>,
Aigle.AllSettledResponse<T2>,
Aigle.AllSettledResponse<T3>,
Aigle.AllSettledResponse<T4>,
Aigle.AllSettledResponse<T5>,
Aigle.AllSettledResponse<T6>,
Aigle.AllSettledResponse<T7>,
Aigle.AllSettledResponse<T8>,
Aigle.AllSettledResponse<T9>,
Aigle.AllSettledResponse<T10>
]
>;
allSettled<T>(
this: Aigle<(T | PromiseLike<T> | Aigle.PromiseCallback<T>)[]>
): Aigle<Aigle.AllSettledResponse<T>[]>;
/* race */
/**
* Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
* or rejected.
* @param values An array of Promises.
* @returns A new Aigle.
*/
race<T1>(this: Aigle<[T1 | PromiseLike<T1>]>): Aigle<T1>;
race<T1, T2>(this: Aigle<[T1 | PromiseLike<T1>, T2 | PromiseLike<T2>]>): Aigle<T1 | T2>;
race<T1, T2, T3>(
this: Aigle<[T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>]>
): Aigle<T1 | T2 | T3>;
race<T1, T2, T3, T4>(
this: Aigle<
[T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>]
>
): Aigle<T1 | T2 | T3 | T4>;
race<T1, T2, T3, T4, T5>(
this: Aigle<
[
T1 | PromiseLike<T1>,
T2 | PromiseLike<T2>,
T3 | PromiseLike<T3>,
T4 | PromiseLike<T4>,
T5 | PromiseLike<T5>
]
>
): Aigle<T1 | T2 | T3 | T4 | T5>;
race<T1, T2, T3, T4, T5, T6>(
this: Aigle<
[
T1 | PromiseLike<T1>,
T2 | PromiseLike<T2>,
T3 | PromiseLike<T3>,
T4 | PromiseLike<T4>,
T5 | PromiseLike<T5>,
T6 | PromiseLike<T6>
]
>
): Aigle<T1 | T2 | T3 | T4 | T5 | T6>;
race<T1, T2, T3, T4, T5, T6, T7>(
this: Aigle<
[
T1 | PromiseLike<T1>,
T2 | PromiseLike<T2>,
T3 | PromiseLike<T3>,
T4 | PromiseLike<T4>,
T5 | PromiseLike<T5>,
T6 | PromiseLike<T6>,
T7 | PromiseLike<T7>
]
>
): Aigle<T1 | T2 | T3 | T4 | T5 | T6 | T7>;
race<T1, T2, T3, T4, T5, T6, T7, T8>(
this: Aigle<
[
T1 | PromiseLike<T1>,
T2 | PromiseLike<T2>,
T3 | PromiseLike<T3>,
T4 | PromiseLike<T4>,
T5 | PromiseLike<T5>,
T6 | PromiseLike<T6>,
T7 | PromiseLike<T7>,
T8 | PromiseLike<T8>
]
>
): Aigle<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8>;
race<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
this: Aigle<
[
T1 | PromiseLike<T1>,
T2 | PromiseLike<T2>,
T3 | PromiseLike<T3>,
T4 | PromiseLike<T4>,
T5 | PromiseLike<T5>,
T6 | PromiseLike<T6>,
T7 | PromiseLike<T7>,
T8 | PromiseLike<T8>,
T9 | PromiseLike<T9>
]
>
): Aigle<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9>;
race<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
this: Aigle<
[
T1 | PromiseLike<T1>,
T2 | PromiseLike<T2>,
T3 | PromiseLike<T3>,
T4 | PromiseLike<T4>,
T5 | PromiseLike<T5>,
T6 | PromiseLike<T6>,
T7 | PromiseLike<T7>,
T8 | PromiseLike<T8>,
T9 | PromiseLike<T9>,
T10 | PromiseLike<T10>
]
>
): Aigle<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9 | T10>;
race<T>(this: Aigle<(T | PromiseLike<T>)[]>): Aigle<T>;
/* prpps */
props<K, V>(this: Aigle<Map<K, PromiseLike<V> | V>>): Aigle<Map<K, V>>;
props<T>(this: Aigle<Aigle.ResolvableProps<T>>): Aigle<T>;
/* series */
series<T1>(this: Aigle<[T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>]>): Aigle<[T1]>;
series<T1, T2>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>
]
>
): Aigle<[T1, T2]>;
series<T1, T2, T3>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>
]
>
): Aigle<[T1, T2, T3]>;
series<T1, T2, T3, T4>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>
]
>
): Aigle<[T1, T2, T3, T4]>;
series<T1, T2, T3, T4, T5>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>
]
>
): Aigle<[T1, T2, T3, T4, T5]>;
series<T1, T2, T3, T4, T5, T6>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>
]
>
): Aigle<[T1, T2, T3, T4, T5, T6]>;
series<T1, T2, T3, T4, T5, T6, T7>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>
]
>
): Aigle<[T1, T2, T3, T4, T5, T6, T7]>;
series<T1, T2, T3, T4, T5, T6, T7, T8>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>,
T8 | PromiseLike<T8> | Aigle.PromiseCallback<T8>
]
>
): Aigle<[T1, T2, T3, T4, T5, T6, T7, T8]>;
series<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>,
T8 | PromiseLike<T8> | Aigle.PromiseCallback<T8>,
T9 | PromiseLike<T9> | Aigle.PromiseCallback<T9>
]
>
): Aigle<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
series<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>,
T8 | PromiseLike<T8> | Aigle.PromiseCallback<T8>,
T9 | PromiseLike<T9> | Aigle.PromiseCallback<T9>,
T10 | PromiseLike<T10> | Aigle.PromiseCallback<T10>
]
>
): Aigle<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
series<T>(this: Aigle<(T | PromiseLike<T> | Aigle.PromiseCallback<T>)[]>): Aigle<T[]>;
/* parallel */
parallel<T1>(this: Aigle<[T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>]>): Aigle<[T1]>;
parallel<T1, T2>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>
]
>
): Aigle<[T1, T2]>;
parallel<T1, T2, T3>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>
]
>
): Aigle<[T1, T2, T3]>;
parallel<T1, T2, T3, T4>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>
]
>
): Aigle<[T1, T2, T3, T4]>;
parallel<T1, T2, T3, T4, T5>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>
]
>
): Aigle<[T1, T2, T3, T4, T5]>;
parallel<T1, T2, T3, T4, T5, T6>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>
]
>
): Aigle<[T1, T2, T3, T4, T5, T6]>;
parallel<T1, T2, T3, T4, T5, T6, T7>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>
]
>
): Aigle<[T1, T2, T3, T4, T5, T6, T7]>;
parallel<T1, T2, T3, T4, T5, T6, T7, T8>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>,
T8 | PromiseLike<T8> | Aigle.PromiseCallback<T8>
]
>
): Aigle<[T1, T2, T3, T4, T5, T6, T7, T8]>;
parallel<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>,
T8 | PromiseLike<T8> | Aigle.PromiseCallback<T8>,
T9 | PromiseLike<T9> | Aigle.PromiseCallback<T9>
]
>
): Aigle<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
parallel<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>,
T8 | PromiseLike<T8> | Aigle.PromiseCallback<T8>,
T9 | PromiseLike<T9> | Aigle.PromiseCallback<T9>,
T10 | PromiseLike<T10> | Aigle.PromiseCallback<T10>
]
>
): Aigle<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
parallel<T>(this: Aigle<(T | PromiseLike<T> | Aigle.PromiseCallback<T>)[]>): Aigle<T[]>;
/* parallelLimit */
parallelLimit<T1>(
this: Aigle<[T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>]>,
limit?: number
): Aigle<[T1]>;
parallelLimit<T1, T2>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>
]
>,
limit?: number
): Aigle<[T1, T2]>;
parallelLimit<T1, T2, T3>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>
]
>,
limit?: number
): Aigle<[T1, T2, T3]>;
parallelLimit<T1, T2, T3, T4>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>
]
>,
limit?: number
): Aigle<[T1, T2, T3, T4]>;
parallelLimit<T1, T2, T3, T4, T5>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>
]
>,
limit?: number
): Aigle<[T1, T2, T3, T4, T5]>;
parallelLimit<T1, T2, T3, T4, T5, T6>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>
]
>,
limit?: number
): Aigle<[T1, T2, T3, T4, T5, T6]>;
parallelLimit<T1, T2, T3, T4, T5, T6, T7>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>
]
>,
limit?: number
): Aigle<[T1, T2, T3, T4, T5, T6, T7]>;
parallelLimit<T1, T2, T3, T4, T5, T6, T7, T8>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>,
T8 | PromiseLike<T8> | Aigle.PromiseCallback<T8>
]
>,
limit?: number
): Aigle<[T1, T2, T3, T4, T5, T6, T7, T8]>;
parallelLimit<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>,
T8 | PromiseLike<T8> | Aigle.PromiseCallback<T8>,
T9 | PromiseLike<T9> | Aigle.PromiseCallback<T9>
]
>,
limit?: number
): Aigle<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
parallelLimit<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
this: Aigle<
[
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>,
T8 | PromiseLike<T8> | Aigle.PromiseCallback<T8>,
T9 | PromiseLike<T9> | Aigle.PromiseCallback<T9>,
T10 | PromiseLike<T10> | Aigle.PromiseCallback<T10>
]
>,
limit?: number
): Aigle<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
parallelLimit<T>(
this: Aigle<(T | PromiseLike<T> | Aigle.PromiseCallback<T>)[]>,
limit?: number
): Aigle<T[]>;
/* each/forEach */
each<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, any>): Aigle<T[]>;
each<T>(this: Aigle<Aigle.List<T>>, iterator?: Aigle.ListIterator<T, any>): Aigle<Aigle.List<T>>;
each<T extends object>(this: Aigle<T>, iterator?: Aigle.ObjectIterator<T, any>): Aigle<T>;
forEach<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, any>): Aigle<T[]>;
forEach<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T, any>
): Aigle<Aigle.List<T>>;
forEach<T extends object>(this: Aigle<T>, iterator?: Aigle.ObjectIterator<T, any>): Aigle<T>;
/* eachSeries/forEachSeries */
eachSeries<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, any>): Aigle<T[]>;
eachSeries<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T, any>
): Aigle<Aigle.List<T>>;
eachSeries<T extends object>(this: Aigle<T>, iterator?: Aigle.ObjectIterator<T, any>): Aigle<T>;
forEachSeries<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, any>): Aigle<T[]>;
forEachSeries<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T, any>
): Aigle<Aigle.List<T>>;
forEachSeries<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, any>
): Aigle<T>;
/* eachLimit/forEachLimit */
eachLimit<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, any>): Aigle<T[]>;
eachLimit<T>(this: Aigle<T[]>, limit: number, iterator: Aigle.ArrayIterator<T, any>): Aigle<T[]>;
eachLimit<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T, any>
): Aigle<Aigle.List<T>>;
eachLimit<T>(
this: Aigle<Aigle.List<T>>,
limit: number,
iterator: Aigle.ListIterator<T, any>
): Aigle<Aigle.List<T>>;
eachLimit<T extends object>(this: Aigle<T>, iterator?: Aigle.ObjectIterator<T, any>): Aigle<T>;
eachLimit<T extends object>(
this: Aigle<T>,
limit: number,
iterator: Aigle.ObjectIterator<T, any>
): Aigle<T>;
forEachLimit<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, any>): Aigle<T[]>;
forEachLimit<T>(
this: Aigle<T[]>,
limit: number,
iterator: Aigle.ArrayIterator<T, any>
): Aigle<T[]>;
forEachLimit<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T, any>
): Aigle<Aigle.List<T>>;
forEachLimit<T>(
this: Aigle<Aigle.List<T>>,
limit: number,
iterator: Aigle.ListIterator<T, any>
): Aigle<Aigle.List<T>>;
forEachLimit<T extends object>(this: Aigle<T>, iterator?: Aigle.ObjectIterator<T, any>): Aigle<T>;
forEachLimit<T extends object>(
this: Aigle<T>,
limit: number,
iterator: Aigle.ObjectIterator<T, any>
): Aigle<T>;
/* map */
map<T, R>(this: Aigle<T[]>, iterator: Aigle.ArrayIterator<T, R>): Aigle<R[]>;
map<T, R>(this: Aigle<Aigle.List<T>>, iterator: Aigle.ListIterator<T, R>): Aigle<R[]>;
map<T extends object, R>(this: Aigle<T>, iterator: Aigle.ObjectIterator<T, R>): Aigle<R[]>;
/* mapSeries */
mapSeries<T, R>(this: Aigle<T[]>, iterator: Aigle.ArrayIterator<T, R>): Aigle<R[]>;
mapSeries<T, R>(this: Aigle<Aigle.List<T>>, iterator: Aigle.ListIterator<T, R>): Aigle<R[]>;
mapSeries<T extends object, R>(this: Aigle<T>, iterator: Aigle.ObjectIterator<T, R>): Aigle<R[]>;
/* mapLimit */
mapLimit<T, R>(this: Aigle<T[]>, iterator: Aigle.ArrayIterator<T, R>): Aigle<R[]>;
mapLimit<T, R>(this: Aigle<T[]>, limit: number, iterator: Aigle.ArrayIterator<T, R>): Aigle<R[]>;
mapLimit<T, R>(this: Aigle<Aigle.List<T>>, iterator: Aigle.ListIterator<T, R>): Aigle<R[]>;
mapLimit<T, R>(
this: Aigle<Aigle.List<T>>,
limit: number,
iterator: Aigle.ListIterator<T, R>
): Aigle<R[]>;
mapLimit<T extends object, R>(this: Aigle<T>, iterator: Aigle.ObjectIterator<T, R>): Aigle<R[]>;
mapLimit<T extends object, R>(
this: Aigle<T>,
limit: number,
iterator: Aigle.ObjectIterator<T, R>
): Aigle<R[]>;
/* mapValues */
mapValues<T, R>(
this: Aigle<T[]>,
iterator?: Aigle.ArrayIterator<T, R>
): Aigle<Aigle.Dictionary<R>>;
mapValues<T, R>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T, R>
): Aigle<Aigle.Dictionary<R>>;
mapValues<T extends object, R>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, R>
): Aigle<Record<keyof T, R>>;
/* mapValuesSeries */
mapValuesSeries<T, R>(
this: Aigle<T[]>,
iterator?: Aigle.ArrayIterator<T, R>
): Aigle<Aigle.Dictionary<R>>;
mapValuesSeries<T, R>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T, R>
): Aigle<Aigle.Dictionary<R>>;
mapValuesSeries<T extends object, R>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, R>
): Aigle<Record<keyof T, R>>;
/* mapValuesLimit */
mapValuesLimit<T, R>(
this: Aigle<T[]>,
iterator?: Aigle.ArrayIterator<T, R>
): Aigle<Aigle.Dictionary<R>>;
mapValuesLimit<T, R>(
this: Aigle<T[]>,
limit: number,
iterator: Aigle.ArrayIterator<T, R>
): Aigle<Aigle.Dictionary<R>>;
mapValuesLimit<T, R>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T, R>
): Aigle<Aigle.Dictionary<R>>;
mapValuesLimit<T, R>(
this: Aigle<Aigle.List<T>>,
limit: number,
iterator: Aigle.ListIterator<T, R>
): Aigle<Aigle.Dictionary<R>>;
mapValuesLimit<T extends object, R>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, R>
): Aigle<Record<keyof T, R>>;
mapValuesLimit<T extends object, R>(
this: Aigle<T>,
limit: number,
iterator: Aigle.ObjectIterator<T, R>
): Aigle<Record<keyof T, R>>;
/* concat */
concat<T, R>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, R | R[]>): Aigle<R[]>;
concat<T, R>(this: Aigle<Aigle.List<T>>, iterator?: Aigle.ListIterator<T, R | R[]>): Aigle<R[]>;
concat<T extends object, R>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, R | R[]>
): Aigle<R[]>;
/* concatSeries */
concatSeries<T, R>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, R | R[]>): Aigle<R[]>;
concatSeries<T, R>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T, R | R[]>
): Aigle<R[]>;
concatSeries<T extends object, R>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, R | R[]>
): Aigle<R[]>;
/* concatLimit */
concatLimit<T, R>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, R | R[]>): Aigle<R[]>;
concatLimit<T, R>(
this: Aigle<T[]>,
limit: number,
iterator: Aigle.ArrayIterator<T, R | R[]>
): Aigle<R[]>;
concatLimit<T, R>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T, R | R[]>
): Aigle<R[]>;
concatLimit<T, R>(
this: Aigle<Aigle.List<T>>,
limit: number,
iterator: Aigle.ListIterator<T, R | R[]>
): Aigle<R[]>;
concatLimit<T extends object, R>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, R | R[]>
): Aigle<R[]>;
concatLimit<T extends object, R>(
this: Aigle<T>,
limit: number,
iterator: Aigle.ObjectIterator<T, R | R[]>
): Aigle<R[]>;
/* every */
every<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<boolean>;
every<T>(this: Aigle<Aigle.List<T>>, iterator?: Aigle.ListIterator<T, boolean>): Aigle<boolean>;
every<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<boolean>;
/* everySeries */
everySeries<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<boolean>;
everySeries<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<boolean>;
everySeries<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<boolean>;
/* everyLimit */
everyLimit<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<boolean>;
everyLimit<T>(
this: Aigle<T[]>,
limit: number,
iterator: Aigle.ArrayIterator<T, boolean>
): Aigle<boolean>;
everyLimit<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<boolean>;
everyLimit<T>(
this: Aigle<Aigle.List<T>>,
limit: number,
iterator: Aigle.ListIterator<T, boolean>
): Aigle<boolean>;
everyLimit<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<boolean>;
everyLimit<T extends object>(
this: Aigle<T>,
limit: number,
iterator: Aigle.ObjectIterator<T, boolean>
): Aigle<boolean>;
/* some */
some<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<boolean>;
some<T>(this: Aigle<Aigle.List<T>>, iterator?: Aigle.ListIterator<T, boolean>): Aigle<boolean>;
some<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<boolean>;
/* someSeries */
someSeries<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<boolean>;
someSeries<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<boolean>;
someSeries<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<boolean>;
/* someLimit */
someLimit<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<boolean>;
someLimit<T>(
this: Aigle<T[]>,
limit: number,
iterator: Aigle.ArrayIterator<T, boolean>
): Aigle<boolean>;
someLimit<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<boolean>;
someLimit<T>(
this: Aigle<Aigle.List<T>>,
limit: number,
iterator: Aigle.ListIterator<T, boolean>
): Aigle<boolean>;
someLimit<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<boolean>;
someLimit<T extends object>(
this: Aigle<T>,
limit: number,
iterator: Aigle.ObjectIterator<T, boolean>
): Aigle<boolean>;
/* filter */
filter<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<T[]>;
filter<T>(this: Aigle<Aigle.List<T>>, iterator?: Aigle.ListIterator<T, boolean>): Aigle<T[]>;
filter<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<Array<T[keyof T]>>;
/* filterSeries */
filterSeries<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<T[]>;
filterSeries<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<T[]>;
filterSeries<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<Array<T[keyof T]>>;
/* filterLimit */
filterLimit<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<T[]>;
filterLimit<T>(
this: Aigle<T[]>,
limit: number,
iterator: Aigle.ArrayIterator<T, boolean>
): Aigle<T[]>;
filterLimit<T>(this: Aigle<Aigle.List<T>>, iterator?: Aigle.ListIterator<T, boolean>): Aigle<T[]>;
filterLimit<T>(
this: Aigle<Aigle.List<T>>,
limit: number,
iterator: Aigle.ListIterator<T, boolean>
): Aigle<T[]>;
filterLimit<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<Array<T[keyof T]>>;
filterLimit<T extends object>(
this: Aigle<T>,
limit: number,
iterator: Aigle.ObjectIterator<T, boolean>
): Aigle<Array<T[keyof T]>>;
/* reject */
reject<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<T[]>;
reject<T>(this: Aigle<Aigle.List<T>>, iterator?: Aigle.ListIterator<T, boolean>): Aigle<T[]>;
reject<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<Array<T[keyof T]>>;
/* rejectSeries */
rejectSeries<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<T[]>;
rejectSeries<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<T[]>;
rejectSeries<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<Array<T[keyof T]>>;
/* rejectLimit */
rejectLimit<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<T[]>;
rejectLimit<T>(
this: Aigle<T[]>,
limit: number,
iterator: Aigle.ArrayIterator<T, boolean>
): Aigle<T[]>;
rejectLimit<T>(this: Aigle<Aigle.List<T>>, iterator?: Aigle.ListIterator<T, boolean>): Aigle<T[]>;
rejectLimit<T>(
this: Aigle<Aigle.List<T>>,
limit: number,
iterator: Aigle.ListIterator<T, boolean>
): Aigle<T[]>;
rejectLimit<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<Array<T[keyof T]>>;
rejectLimit<T extends object>(
this: Aigle<T>,
limit: number,
iterator: Aigle.ObjectIterator<T, boolean>
): Aigle<Array<T[keyof T]>>;
/* sortBy */
sortBy<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T>): Aigle<T[]>;
sortBy<T>(this: Aigle<Aigle.List<T>>, iterator?: Aigle.ListIterator<T>): Aigle<T[]>;
sortBy<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T>
): Aigle<Array<T[keyof T]>>;
/* sortBySeries */
sortBySeries<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T>): Aigle<T[]>;
sortBySeries<T>(this: Aigle<Aigle.List<T>>, iterator?: Aigle.ListIterator<T>): Aigle<T[]>;
sortBySeries<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T>
): Aigle<Array<T[keyof T]>>;
/* sortByLimit */
sortByLimit<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T>): Aigle<T[]>;
sortByLimit<T>(this: Aigle<T[]>, limit: number, iterator: Aigle.ArrayIterator<T>): Aigle<T[]>;
sortByLimit<T>(this: Aigle<Aigle.List<T>>, iterator?: Aigle.ListIterator<T>): Aigle<T[]>;
sortByLimit<T>(
this: Aigle<Aigle.List<T>>,
limit: number,
iterator: Aigle.ListIterator<T>
): Aigle<T[]>;
sortByLimit<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T>
): Aigle<Array<T[keyof T]>>;
sortByLimit<T extends object>(
this: Aigle<T>,
limit: number,
iterator: Aigle.ObjectIterator<T>
): Aigle<Array<T[keyof T]>>;
/* find / detect */
find<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<T>;
find<T>(this: Aigle<Aigle.List<T>>, iterator?: Aigle.ListIterator<T, boolean>): Aigle<T>;
find<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<T[keyof T]>;
detect<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<T>;
detect<T>(this: Aigle<Aigle.List<T>>, iterator?: Aigle.ListIterator<T, boolean>): Aigle<T>;
detect<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<T[keyof T]>;
/* findSeries / detectSeries */
findSeries<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<T>;
findSeries<T>(this: Aigle<Aigle.List<T>>, iterator?: Aigle.ListIterator<T, boolean>): Aigle<T>;
findSeries<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<T[keyof T]>;
detectSeries<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<T>;
detectSeries<T>(this: Aigle<Aigle.List<T>>, iterator?: Aigle.ListIterator<T, boolean>): Aigle<T>;
detectSeries<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<T[keyof T]>;
/* findLimit / detectLimit */
findLimit<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<T>;
findLimit<T>(
this: Aigle<T[]>,
limit: number,
iterator: Aigle.ArrayIterator<T, boolean>
): Aigle<T>;
findLimit<T>(this: Aigle<Aigle.List<T>>, iterator?: Aigle.ListIterator<T, boolean>): Aigle<T>;
findLimit<T>(
this: Aigle<Aigle.List<T>>,
limit: number,
iterator: Aigle.ListIterator<T, boolean>
): Aigle<T>;
findLimit<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<T[keyof T]>;
findLimit<T extends object>(
this: Aigle<T>,
limit: number,
iterator: Aigle.ObjectIterator<T, boolean>
): Aigle<T[keyof T]>;
detectLimit<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<T>;
detectLimit<T>(
this: Aigle<T[]>,
limit: number,
iterator: Aigle.ArrayIterator<T, boolean>
): Aigle<T>;
detectLimit<T>(this: Aigle<Aigle.List<T>>, iterator?: Aigle.ListIterator<T, boolean>): Aigle<T>;
detectLimit<T>(
this: Aigle<Aigle.List<T>>,
limit: number,
iterator: Aigle.ListIterator<T, boolean>
): Aigle<T>;
detectLimit<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<T[keyof T]>;
detectLimit<T extends object>(
this: Aigle<T>,
limit: number,
iterator: Aigle.ObjectIterator<T, boolean>
): Aigle<T[keyof T]>;
/* findIndex */
findIndex<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<number>;
findIndex<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<number>;
findIndex<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<number>;
/* findIndexSeries */
findIndexSeries<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<number>;
findIndexSeries<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<number>;
findIndexSeries<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<number>;
/* findIndexLimit */
findIndexLimit<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<number>;
findIndexLimit<T>(
this: Aigle<T[]>,
limit: number,
iterator: Aigle.ArrayIterator<T, boolean>
): Aigle<number>;
findIndexLimit<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<number>;
findIndexLimit<T>(
this: Aigle<Aigle.List<T>>,
limit: number,
iterator: Aigle.ListIterator<T, boolean>
): Aigle<number>;
findIndexLimit<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<number>;
findIndexLimit<T extends object>(
this: Aigle<T>,
limit: number,
iterator: Aigle.ObjectIterator<T, boolean>
): Aigle<number>;
/* findKey */
findKey<T>(
this: Aigle<T[]>,
iterator?: Aigle.ArrayIterator<T, boolean>
): Aigle<string | undefined>;
findKey<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<string | undefined>;
findKey<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<string | undefined>;
/* findKeySeries */
findKeySeries<T>(
this: Aigle<T[]>,
iterator?: Aigle.ArrayIterator<T, boolean>
): Aigle<string | undefined>;
findKeySeries<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<string | undefined>;
findKeySeries<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<string | undefined>;
/* findKeyLimit */
findKeyLimit<T>(
this: Aigle<T[]>,
iterator?: Aigle.ArrayIterator<T, boolean>
): Aigle<string | undefined>;
findKeyLimit<T>(
this: Aigle<T[]>,
limit: number,
iterator: Aigle.ArrayIterator<T, boolean>
): Aigle<string | undefined>;
findKeyLimit<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<string | undefined>;
findKeyLimit<T>(
this: Aigle<Aigle.List<T>>,
limit: number,
iterator: Aigle.ListIterator<T, boolean>
): Aigle<string | undefined>;
findKeyLimit<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<string | undefined>;
findKeyLimit<T extends object>(
this: Aigle<T>,
limit: number,
iterator: Aigle.ObjectIterator<T, boolean>
): Aigle<string | undefined>;
/* groupBy */
groupBy<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T>): Aigle<Aigle.Dictionary<T[]>>;
groupBy<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T>
): Aigle<Aigle.Dictionary<T[]>>;
groupBy<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T>
): Aigle<Aigle.Dictionary<T[]>>;
/* groupBySeries */
groupBySeries<T>(
this: Aigle<T[]>,
iterator?: Aigle.ArrayIterator<T>
): Aigle<Aigle.Dictionary<T[]>>;
groupBySeries<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T>
): Aigle<Aigle.Dictionary<T[]>>;
groupBySeries<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T>
): Aigle<Aigle.Dictionary<T[]>>;
/* groupByLimit */
groupByLimit<T>(
this: Aigle<T[]>,
iterator?: Aigle.ArrayIterator<T>
): Aigle<Aigle.Dictionary<T[]>>;
groupByLimit<T>(
this: Aigle<T[]>,
limit: number,
iterator: Aigle.ArrayIterator<T>
): Aigle<Aigle.Dictionary<T[]>>;
groupByLimit<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T>
): Aigle<Aigle.Dictionary<T[]>>;
groupByLimit<T>(
this: Aigle<Aigle.List<T>>,
limit: number,
iterator: Aigle.ListIterator<T>
): Aigle<Aigle.Dictionary<T[]>>;
groupByLimit<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T>
): Aigle<Aigle.Dictionary<T[]>>;
groupByLimit<T extends object>(
this: Aigle<T>,
limit: number,
iterator: Aigle.ObjectIterator<T>
): Aigle<Aigle.Dictionary<T[]>>;
/* omit */
omit<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T>): Aigle<Aigle.Dictionary<T>>;
omit<T>(this: Aigle<Aigle.List<T>>, iterator?: Aigle.ListIterator<T>): Aigle<Aigle.Dictionary<T>>;
omit<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T>
): Aigle<Aigle.Dictionary<T>>;
/* omitBy */
omitBy<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T>): Aigle<Aigle.Dictionary<T>>;
omitBy<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T>
): Aigle<Aigle.Dictionary<T>>;
omitBy<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T>
): Aigle<Aigle.Dictionary<T>>;
/* omitSeries / omitBySeries */
omitSeries<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T>): Aigle<Aigle.Dictionary<T>>;
omitSeries<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T>
): Aigle<Aigle.Dictionary<T>>;
omitSeries<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T>
): Aigle<Aigle.Dictionary<T>>;
omitBySeries<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T>): Aigle<Aigle.Dictionary<T>>;
omitBySeries<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T>
): Aigle<Aigle.Dictionary<T>>;
omitBySeries<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T>
): Aigle<Aigle.Dictionary<T>>;
/* omitLimit / omitByLimit */
omitLimit<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T>): Aigle<Aigle.Dictionary<T>>;
omitLimit<T>(
this: Aigle<T[]>,
limit: number,
iterator: Aigle.ArrayIterator<T>
): Aigle<Aigle.Dictionary<T>>;
omitLimit<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T>
): Aigle<Aigle.Dictionary<T>>;
omitLimit<T>(
this: Aigle<Aigle.List<T>>,
limit: number,
iterator: Aigle.ListIterator<T>
): Aigle<Aigle.Dictionary<T>>;
omitLimit<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T>
): Aigle<Aigle.Dictionary<T>>;
omitLimit<T extends object>(
this: Aigle<T>,
limit: number,
iterator: Aigle.ObjectIterator<T>
): Aigle<Aigle.Dictionary<T>>;
omitByLimit<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T>): Aigle<Aigle.Dictionary<T>>;
omitByLimit<T>(
this: Aigle<T[]>,
limit: number,
iterator: Aigle.ArrayIterator<T>
): Aigle<Aigle.Dictionary<T>>;
omitByLimit<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T>
): Aigle<Aigle.Dictionary<T>>;
omitByLimit<T>(
this: Aigle<Aigle.List<T>>,
limit: number,
iterator: Aigle.ListIterator<T>
): Aigle<Aigle.Dictionary<T>>;
omitByLimit<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T>
): Aigle<Aigle.Dictionary<T>>;
omitByLimit<T extends object>(
this: Aigle<T>,
limit: number,
iterator: Aigle.ObjectIterator<T>
): Aigle<Aigle.Dictionary<T>>;
/* pick */
pick<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T>): Aigle<Aigle.Dictionary<T>>;
pick<T>(this: Aigle<Aigle.List<T>>, iterator?: Aigle.ListIterator<T>): Aigle<Aigle.Dictionary<T>>;
pick<T extends object>(this: Aigle<T>, iterator?: Aigle.ObjectIterator<T>): Aigle<Partial<T>>;
/* pickBy */
pickBy<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T>): Aigle<Aigle.Dictionary<T>>;
pickBy<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T>
): Aigle<Aigle.Dictionary<T>>;
pickBy<T extends object>(this: Aigle<T>, iterator?: Aigle.ObjectIterator<T>): Aigle<Partial<T>>;
/* pickSeries / pickBySeries */
pickSeries<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T>): Aigle<Aigle.Dictionary<T>>;
pickSeries<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T>
): Aigle<Aigle.Dictionary<T>>;
pickSeries<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T>
): Aigle<Partial<T>>;
pickBySeries<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T>): Aigle<Aigle.Dictionary<T>>;
pickBySeries<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T>
): Aigle<Aigle.Dictionary<T>>;
pickBySeries<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T>
): Aigle<Partial<T>>;
/* pickLimit / pickByLimit */
pickLimit<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T>): Aigle<Aigle.Dictionary<T>>;
pickLimit<T>(
this: Aigle<T[]>,
limit: number,
iterator: Aigle.ArrayIterator<T>
): Aigle<Aigle.Dictionary<T>>;
pickLimit<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T>
): Aigle<Aigle.Dictionary<T>>;
pickLimit<T>(
this: Aigle<Aigle.List<T>>,
limit: number,
iterator: Aigle.ListIterator<T>
): Aigle<Aigle.Dictionary<T>>;
pickLimit<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T>
): Aigle<Partial<T>>;
pickLimit<T extends object>(
this: Aigle<T>,
limit: number,
iterator: Aigle.ObjectIterator<T>
): Aigle<Partial<T>>;
pickByLimit<T>(this: Aigle<T[]>, iterator?: Aigle.ArrayIterator<T>): Aigle<Aigle.Dictionary<T>>;
pickByLimit<T>(
this: Aigle<T[]>,
limit: number,
iterator: Aigle.ArrayIterator<T>
): Aigle<Aigle.Dictionary<T>>;
pickByLimit<T>(
this: Aigle<Aigle.List<T>>,
iterator?: Aigle.ListIterator<T>
): Aigle<Aigle.Dictionary<T>>;
pickByLimit<T>(
this: Aigle<Aigle.List<T>>,
limit: number,
iterator: Aigle.ListIterator<T>
): Aigle<Aigle.Dictionary<T>>;
pickByLimit<T extends object>(
this: Aigle<T>,
iterator?: Aigle.ObjectIterator<T>
): Aigle<Partial<T>>;
pickByLimit<T extends object>(
this: Aigle<T>,
limit: number,
iterator: Aigle.ObjectIterator<T>
): Aigle<Partial<T>>;
/* transform */
transform<T, R>(
this: Aigle<T[]>,
iterator: Aigle.MemoArrayIterator<T, R[]>,
accumulator?: R[]
): Aigle<R[]>;
transform<T, R>(
this: Aigle<T[]>,
iterator: Aigle.MemoArrayIterator<T, Aigle.Dictionary<R>>,
accumulator: Aigle.Dictionary<R>
): Aigle<Aigle.Dictionary<R>>;
transform<T, R>(
this: Aigle<Aigle.List<T>>,
iterator: Aigle.MemoListIterator<T, R[]>,
accumulator?: R[]
): Aigle<R[]>;
transform<T, R>(
this: Aigle<Aigle.List<T>>,
iterator: Aigle.MemoListIterator<T, Aigle.Dictionary<R>>,
accumulator?: Aigle.Dictionary<R>
): Aigle<Aigle.Dictionary<R>>;
transform<T extends object, R>(
this: Aigle<T>,
iterator: Aigle.MemoObjectIterator<T, Aigle.Dictionary<R>>,
accumulator?: Aigle.Dictionary<R>
): Aigle<Aigle.Dictionary<R>>;
transform<T extends object, R>(
this: Aigle<T>,
iterator: Aigle.MemoObjectIterator<T, R[]>,
accumulator: R[]
): Aigle<R[]>;
/* transformSeries */
transformSeries<T, R>(
this: Aigle<T[]>,
iterator: Aigle.MemoArrayIterator<T, R[]>,
accumulator?: R[]
): Aigle<R[]>;
transformSeries<T, R>(
this: Aigle<T[]>,
iterator: Aigle.MemoArrayIterator<T, Aigle.Dictionary<R>>,
accumulator: Aigle.Dictionary<R>
): Aigle<Aigle.Dictionary<R>>;
transformSeries<T, R>(
this: Aigle<Aigle.List<T>>,
iterator: Aigle.MemoListIterator<T, R[]>,
accumulator?: R[]
): Aigle<R[]>;
transformSeries<T, R>(
this: Aigle<Aigle.List<T>>,
iterator: Aigle.MemoListIterator<T, Aigle.Dictionary<R>>,
accumulator?: Aigle.Dictionary<R>
): Aigle<Aigle.Dictionary<R>>;
transformSeries<T extends object, R>(
this: Aigle<T>,
iterator: Aigle.MemoObjectIterator<T, Aigle.Dictionary<R>>,
accumulator?: Aigle.Dictionary<R>
): Aigle<Aigle.Dictionary<R>>;
transformSeries<T extends object, R>(
this: Aigle<T>,
iterator: Aigle.MemoObjectIterator<T, R[]>,
accumulator: R[]
): Aigle<R[]>;
/* transformLimit */
transformLimit<T, R>(
this: Aigle<T[]>,
iterator: Aigle.MemoArrayIterator<T, R[]>,
accumulator?: R[]
): Aigle<R[]>;
transformLimit<T, R>(
this: Aigle<T[]>,
limit: number,
iterator: Aigle.MemoArrayIterator<T, R[]>,
accumulator?: R[]
): Aigle<R[]>;
transformLimit<T, R>(
this: Aigle<T[]>,
iterator: Aigle.MemoArrayIterator<T, Aigle.Dictionary<R>>,
accumulator: Aigle.Dictionary<R>
): Aigle<Aigle.Dictionary<R>>;
transformLimit<T, R>(
this: Aigle<T[]>,
limit: number,
iterator: Aigle.MemoArrayIterator<T, Aigle.Dictionary<R>>,
accumulator: Aigle.Dictionary<R>
): Aigle<Aigle.Dictionary<R>>;
transformLimit<T, R>(
this: Aigle<Aigle.List<T>>,
iterator: Aigle.MemoListIterator<T, R[]>,
accumulator?: R[]
): Aigle<R[]>;
transformLimit<T, R>(
this: Aigle<Aigle.List<T>>,
limit: number,
iterator: Aigle.MemoListIterator<T, R[]>,
accumulator?: R[]
): Aigle<R[]>;
transformLimit<T, R>(
this: Aigle<Aigle.List<T>>,
iterator: Aigle.MemoListIterator<T, Aigle.Dictionary<R>>,
accumulator?: Aigle.Dictionary<R>
): Aigle<Aigle.Dictionary<R>>;
transformLimit<T, R>(
this: Aigle<Aigle.List<T>>,
limit: number,
iterator: Aigle.MemoListIterator<T, Aigle.Dictionary<R>>,
accumulator?: Aigle.Dictionary<R>
): Aigle<Aigle.Dictionary<R>>;
transformLimit<T extends object, R>(
this: Aigle<T>,
iterator: Aigle.MemoObjectIterator<T, Aigle.Dictionary<R>>,
accumulator?: Aigle.Dictionary<R>
): Aigle<Aigle.Dictionary<R>>;
transformLimit<T extends object, R>(
this: Aigle<T>,
limit: number,
iterator: Aigle.MemoObjectIterator<T, Aigle.Dictionary<R>>,
accumulator?: Aigle.Dictionary<R>
): Aigle<Aigle.Dictionary<R>>;
transformLimit<T extends object, R>(
this: Aigle<T>,
iterator: Aigle.MemoObjectIterator<T, R[]>,
accumulator: R[]
): Aigle<R[]>;
transformLimit<T extends object, R>(
this: Aigle<T>,
limit: number,
iterator: Aigle.MemoObjectIterator<T, R[]>,
accumulator: R[]
): Aigle<R[]>;
/* reduce */
reduce<T, R>(
this: Aigle<T[]>,
iterator: Aigle.MemoArrayIterator<T, R, R>,
accumulator?: R
): Aigle<R>;
reduce<T, R>(
this: Aigle<Aigle.List<T>>,
iterator: Aigle.MemoListIterator<T, R, R>,
accumulator?: R
): Aigle<R>;
reduce<T extends object, R>(
this: Aigle<T>,
iterator: Aigle.MemoObjectIterator<T, R, R>,
accumulator?: R
): Aigle<R>;
/* delay */
delay(ms: number): Aigle<R>;
/* tap */
tap(intercepter: (value: R) => Aigle.ReturnType<any>): Aigle<R>;
/* thru */
thru<T>(intercepter: (value: R) => Aigle.ReturnType<T>): Aigle<T>;
/* times */
times<T>(this: Aigle<number>, iterator?: (num: number) => Aigle.ReturnType<T>): Aigle<T[]>;
/* timesSeries */
timesSeries<T>(this: Aigle<number>, iterator?: (num: number) => Aigle.ReturnType<T>): Aigle<T[]>;
/* timesLimit */
timesLimit<T>(this: Aigle<number>, iterator?: (num: number) => Aigle.ReturnType<T>): Aigle<T[]>;
timesLimit<T>(
this: Aigle<number>,
limit: number,
iterator: (num: number) => Aigle.ReturnType<T>
): Aigle<T[]>;
/* doUntil */
doUntil<T>(
this: Aigle<T>,
iterator: (value: T) => Aigle.ReturnType<T>,
tester: (value: T) => Aigle.ReturnType<boolean>
): Aigle<T>;
/* doWhilst */
doWhilst<T>(
this: Aigle<T>,
iterator: (value: T) => Aigle.ReturnType<T>,
tester: (value: T) => Aigle.ReturnType<boolean>
): Aigle<T>;
/* until */
until<T>(
this: Aigle<T>,
tester: (value: T) => Aigle.ReturnType<boolean>,
iterator: (value: T) => Aigle.ReturnType<T>
): Aigle<T>;
/* whilst */
whilst<T>(
this: Aigle<T>,
tester: (value: T) => Aigle.ReturnType<boolean>,
iterator: (value: T) => Aigle.ReturnType<T>
): Aigle<T>;
/* isCancelled */
isCancelled(): boolean;
/* isFulfilled */
isFulfilled(): boolean;
/* isPending */
isPending(): boolean;
/* isRejected */
isRejected(): boolean;
/* value */
value(): any;
/* reason */
reason(): any;
/* cancel */
cancel(): void;
/* disposer */
disposer(fn: (value: R) => any): Aigle.Disposer<R>;
/* suppressUnhandledRejections */
suppressUnhandledRejections(): void;
/* timeout */
timeout(ms: number, message?: string | Error): Aigle<R>;
/* toString */
toString(): string;
/** static **/
/* core functions */
static resolve(): Aigle<void>;
static resolve<T>(value: Aigle.ReturnType<T>): Aigle<T>;
static reject(reason: any): Aigle<never>;
static join<T>(...values: T[]): Aigle<T[]>;
static join<T>(...values: PromiseLike<T>[]): Aigle<T[]>;
/* all */
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
* resolve, or rejected when any Promise is rejected.
* @param values An array of Promises.
* @returns A new Aigle.
*/
static all<T1>(values: [Aigle.ReturnType<T1>]): Aigle<[T1]>;
static all<T1, T2>(values: [Aigle.ReturnType<T1>, Aigle.ReturnType<T2>]): Aigle<[T1, T2]>;
static all<T1, T2, T3>(
values: [Aigle.ReturnType<T1>, Aigle.ReturnType<T2>, Aigle.ReturnType<T3>]
): Aigle<[T1, T2, T3]>;
static all<T1, T2, T3, T4>(
values: [Aigle.ReturnType<T1>, Aigle.ReturnType<T2>, Aigle.ReturnType<T3>, Aigle.ReturnType<T4>]
): Aigle<[T1, T2, T3, T4]>;
static all<T1, T2, T3, T4, T5>(
values: [
Aigle.ReturnType<T1>,
Aigle.ReturnType<T2>,
Aigle.ReturnType<T3>,
Aigle.ReturnType<T4>,
Aigle.ReturnType<T5>
]
): Aigle<[T1, T2, T3, T4, T5]>;
static all<T1, T2, T3, T4, T5, T6>(
values: [
Aigle.ReturnType<T1>,
Aigle.ReturnType<T2>,
Aigle.ReturnType<T3>,
Aigle.ReturnType<T4>,
Aigle.ReturnType<T5>,
Aigle.ReturnType<T6>
]
): Aigle<[T1, T2, T3, T4, T5, T6]>;
static all<T1, T2, T3, T4, T5, T6, T7>(
values: [
Aigle.ReturnType<T1>,
Aigle.ReturnType<T2>,
Aigle.ReturnType<T3>,
Aigle.ReturnType<T4>,
Aigle.ReturnType<T5>,
Aigle.ReturnType<T6>,
Aigle.ReturnType<T7>
]
): Aigle<[T1, T2, T3, T4, T5, T6, T7]>;
static all<T1, T2, T3, T4, T5, T6, T7, T8>(
values: [
Aigle.ReturnType<T1>,
Aigle.ReturnType<T2>,
Aigle.ReturnType<T3>,
Aigle.ReturnType<T4>,
Aigle.ReturnType<T5>,
Aigle.ReturnType<T6>,
Aigle.ReturnType<T7>,
Aigle.ReturnType<T8>
]
): Aigle<[T1, T2, T3, T4, T5, T6, T7, T8]>;
static all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
values: [
Aigle.ReturnType<T1>,
Aigle.ReturnType<T2>,
Aigle.ReturnType<T3>,
Aigle.ReturnType<T4>,
Aigle.ReturnType<T5>,
Aigle.ReturnType<T6>,
Aigle.ReturnType<T7>,
Aigle.ReturnType<T8>,
Aigle.ReturnType<T9>
]
): Aigle<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
static all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
values: [
Aigle.ReturnType<T1>,
Aigle.ReturnType<T2>,
Aigle.ReturnType<T3>,
Aigle.ReturnType<T4>,
Aigle.ReturnType<T5>,
Aigle.ReturnType<T6>,
Aigle.ReturnType<T7>,
Aigle.ReturnType<T8>,
Aigle.ReturnType<T9>,
Aigle.ReturnType<T10>
]
): Aigle<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
static all<T>(values: Aigle.ReturnType<T>[]): Aigle<T[]>;
/* allSettled */
static allSettled<T1>(
values: [T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>]
): Aigle<[Aigle.AllSettledResponse<T1>]>;
static allSettled<T1, T2>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>
]
): Aigle<[Aigle.AllSettledResponse<T1>, Aigle.AllSettledResponse<T2>]>;
static allSettled<T1, T2, T3>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>
]
): Aigle<
[Aigle.AllSettledResponse<T1>, Aigle.AllSettledResponse<T2>, Aigle.AllSettledResponse<T3>]
>;
static allSettled<T1, T2, T3, T4>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>
]
): Aigle<
[
Aigle.AllSettledResponse<T1>,
Aigle.AllSettledResponse<T2>,
Aigle.AllSettledResponse<T3>,
Aigle.AllSettledResponse<T4>
]
>;
static allSettled<T1, T2, T3, T4, T5>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>
]
): Aigle<
[
Aigle.AllSettledResponse<T1>,
Aigle.AllSettledResponse<T2>,
Aigle.AllSettledResponse<T3>,
Aigle.AllSettledResponse<T4>,
Aigle.AllSettledResponse<T5>
]
>;
static allSettled<T1, T2, T3, T4, T5, T6>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>
]
): Aigle<
[
Aigle.AllSettledResponse<T1>,
Aigle.AllSettledResponse<T2>,
Aigle.AllSettledResponse<T3>,
Aigle.AllSettledResponse<T4>,
Aigle.AllSettledResponse<T5>,
Aigle.AllSettledResponse<T6>
]
>;
static allSettled<T1, T2, T3, T4, T5, T6, T7>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>
]
): Aigle<
[
Aigle.AllSettledResponse<T1>,
Aigle.AllSettledResponse<T2>,
Aigle.AllSettledResponse<T3>,
Aigle.AllSettledResponse<T4>,
Aigle.AllSettledResponse<T5>,
Aigle.AllSettledResponse<T6>,
Aigle.AllSettledResponse<T7>
]
>;
static allSettled<T1, T2, T3, T4, T5, T6, T7, T8>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>,
T8 | PromiseLike<T8> | Aigle.PromiseCallback<T8>
]
): Aigle<
[
Aigle.AllSettledResponse<T1>,
Aigle.AllSettledResponse<T2>,
Aigle.AllSettledResponse<T3>,
Aigle.AllSettledResponse<T4>,
Aigle.AllSettledResponse<T5>,
Aigle.AllSettledResponse<T6>,
Aigle.AllSettledResponse<T7>,
Aigle.AllSettledResponse<T8>
]
>;
static allSettled<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>,
T8 | PromiseLike<T8> | Aigle.PromiseCallback<T8>,
T9 | PromiseLike<T9> | Aigle.PromiseCallback<T9>
]
): Aigle<
[
Aigle.AllSettledResponse<T1>,
Aigle.AllSettledResponse<T2>,
Aigle.AllSettledResponse<T3>,
Aigle.AllSettledResponse<T4>,
Aigle.AllSettledResponse<T5>,
Aigle.AllSettledResponse<T6>,
Aigle.AllSettledResponse<T7>,
Aigle.AllSettledResponse<T8>,
Aigle.AllSettledResponse<T9>
]
>;
static allSettled<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>,
T8 | PromiseLike<T8> | Aigle.PromiseCallback<T8>,
T9 | PromiseLike<T9> | Aigle.PromiseCallback<T9>,
T10 | PromiseLike<T10> | Aigle.PromiseCallback<T10>
]
): Aigle<
[
Aigle.AllSettledResponse<T1>,
Aigle.AllSettledResponse<T2>,
Aigle.AllSettledResponse<T3>,
Aigle.AllSettledResponse<T4>,
Aigle.AllSettledResponse<T5>,
Aigle.AllSettledResponse<T6>,
Aigle.AllSettledResponse<T7>,
Aigle.AllSettledResponse<T8>,
Aigle.AllSettledResponse<T9>,
Aigle.AllSettledResponse<T10>
]
>;
static allSettled<T>(
values: (T | PromiseLike<T> | Aigle.PromiseCallback<T>)[]
): Aigle<Aigle.AllSettledResponse<T>[]>;
/* rase */
/**
* Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
* or rejected.
* @param values An array of Promises.
* @returns A new Aigle.
*/
static race<T1>(values: [Aigle.ReturnType<T1>]): Aigle<T1>;
static race<T1, T2>(values: [Aigle.ReturnType<T1>, Aigle.ReturnType<T2>]): Aigle<T1 | T2>;
static race<T1, T2, T3>(
values: [Aigle.ReturnType<T1>, Aigle.ReturnType<T2>, Aigle.ReturnType<T3>]
): Aigle<T1 | T2 | T3>;
static race<T1, T2, T3, T4>(
values: [Aigle.ReturnType<T1>, Aigle.ReturnType<T2>, Aigle.ReturnType<T3>, Aigle.ReturnType<T4>]
): Aigle<T1 | T2 | T3 | T4>;
static race<T1, T2, T3, T4, T5>(
values: [
Aigle.ReturnType<T1>,
Aigle.ReturnType<T2>,
Aigle.ReturnType<T3>,
Aigle.ReturnType<T4>,
Aigle.ReturnType<T5>
]
): Aigle<T1 | T2 | T3 | T4 | T5>;
static race<T1, T2, T3, T4, T5, T6>(
values: [
Aigle.ReturnType<T1>,
Aigle.ReturnType<T2>,
Aigle.ReturnType<T3>,
Aigle.ReturnType<T4>,
Aigle.ReturnType<T5>,
Aigle.ReturnType<T6>
]
): Aigle<T1 | T2 | T3 | T4 | T5 | T6>;
static race<T1, T2, T3, T4, T5, T6, T7>(
values: [
Aigle.ReturnType<T1>,
Aigle.ReturnType<T2>,
Aigle.ReturnType<T3>,
Aigle.ReturnType<T4>,
Aigle.ReturnType<T5>,
Aigle.ReturnType<T6>,
Aigle.ReturnType<T7>
]
): Aigle<T1 | T2 | T3 | T4 | T5 | T6 | T7>;
static race<T1, T2, T3, T4, T5, T6, T7, T8>(
values: [
Aigle.ReturnType<T1>,
Aigle.ReturnType<T2>,
Aigle.ReturnType<T3>,
Aigle.ReturnType<T4>,
Aigle.ReturnType<T5>,
Aigle.ReturnType<T6>,
Aigle.ReturnType<T7>,
Aigle.ReturnType<T8>
]
): Aigle<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8>;
static race<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
values: [
Aigle.ReturnType<T1>,
Aigle.ReturnType<T2>,
Aigle.ReturnType<T3>,
Aigle.ReturnType<T4>,
Aigle.ReturnType<T5>,
Aigle.ReturnType<T6>,
Aigle.ReturnType<T7>,
Aigle.ReturnType<T8>,
Aigle.ReturnType<T9>
]
): Aigle<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9>;
static race<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
values: [
Aigle.ReturnType<T1>,
Aigle.ReturnType<T2>,
Aigle.ReturnType<T3>,
Aigle.ReturnType<T4>,
Aigle.ReturnType<T5>,
Aigle.ReturnType<T6>,
Aigle.ReturnType<T7>,
Aigle.ReturnType<T8>,
Aigle.ReturnType<T9>,
Aigle.ReturnType<T10>
]
): Aigle<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9 | T10>;
static race<T>(values: Aigle.ReturnType<T>[]): Aigle<T>;
/* props */
static props<K, V>(
map: PromiseLike<Map<K, PromiseLike<V> | V>> | Map<K, PromiseLike<V> | V>
): Aigle<Map<K, V>>;
static props<T>(
object: Aigle.ResolvableProps<T> | PromiseLike<Aigle.ResolvableProps<T>>
): Aigle<T>;
/* series */
static series<T1>(values: [T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>]): Aigle<[T1]>;
static series<T1, T2>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>
]
): Aigle<[T1, T2]>;
static series<T1, T2, T3>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>
]
): Aigle<[T1, T2, T3]>;
static series<T1, T2, T3, T4>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>
]
): Aigle<[T1, T2, T3, T4]>;
static series<T1, T2, T3, T4, T5>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>
]
): Aigle<[T1, T2, T3, T4, T5]>;
static series<T1, T2, T3, T4, T5, T6>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>
]
): Aigle<[T1, T2, T3, T4, T5, T6]>;
static series<T1, T2, T3, T4, T5, T6, T7>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>
]
): Aigle<[T1, T2, T3, T4, T5, T6, T7]>;
static series<T1, T2, T3, T4, T5, T6, T7, T8>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>,
T8 | PromiseLike<T8> | Aigle.PromiseCallback<T8>
]
): Aigle<[T1, T2, T3, T4, T5, T6, T7, T8]>;
static series<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>,
T8 | PromiseLike<T8> | Aigle.PromiseCallback<T8>,
T9 | PromiseLike<T9> | Aigle.PromiseCallback<T9>
]
): Aigle<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
static series<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>,
T8 | PromiseLike<T8> | Aigle.PromiseCallback<T8>,
T9 | PromiseLike<T9> | Aigle.PromiseCallback<T9>,
T10 | PromiseLike<T10> | Aigle.PromiseCallback<T10>
]
): Aigle<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
static series<T>(values: (T | PromiseLike<T> | Aigle.PromiseCallback<T>)[]): Aigle<T[]>;
/* parallel */
static parallel<T1>(values: [T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>]): Aigle<[T1]>;
static parallel<T1, T2>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>
]
): Aigle<[T1, T2]>;
static parallel<T1, T2, T3>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>
]
): Aigle<[T1, T2, T3]>;
static parallel<T1, T2, T3, T4>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>
]
): Aigle<[T1, T2, T3, T4]>;
static parallel<T1, T2, T3, T4, T5>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>
]
): Aigle<[T1, T2, T3, T4, T5]>;
static parallel<T1, T2, T3, T4, T5, T6>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>
]
): Aigle<[T1, T2, T3, T4, T5, T6]>;
static parallel<T1, T2, T3, T4, T5, T6, T7>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>
]
): Aigle<[T1, T2, T3, T4, T5, T6, T7]>;
static parallel<T1, T2, T3, T4, T5, T6, T7, T8>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>,
T8 | PromiseLike<T8> | Aigle.PromiseCallback<T8>
]
): Aigle<[T1, T2, T3, T4, T5, T6, T7, T8]>;
static parallel<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>,
T8 | PromiseLike<T8> | Aigle.PromiseCallback<T8>,
T9 | PromiseLike<T9> | Aigle.PromiseCallback<T9>
]
): Aigle<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
static parallel<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>,
T8 | PromiseLike<T8> | Aigle.PromiseCallback<T8>,
T9 | PromiseLike<T9> | Aigle.PromiseCallback<T9>,
T10 | PromiseLike<T10> | Aigle.PromiseCallback<T10>
]
): Aigle<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
static parallel<T>(values: (T | PromiseLike<T> | Aigle.PromiseCallback<T>)[]): Aigle<T[]>;
/* parallelLimit */
static parallelLimit<T1>(
values: [T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>],
limit?: number
): Aigle<[T1]>;
static parallelLimit<T1, T2>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>
],
limit?: number
): Aigle<[T1, T2]>;
static parallelLimit<T1, T2, T3>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>
],
limit?: number
): Aigle<[T1, T2, T3]>;
static parallelLimit<T1, T2, T3, T4>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>
],
limit?: number
): Aigle<[T1, T2, T3, T4]>;
static parallelLimit<T1, T2, T3, T4, T5>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>
],
limit?: number
): Aigle<[T1, T2, T3, T4, T5]>;
static parallelLimit<T1, T2, T3, T4, T5, T6>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>
],
limit?: number
): Aigle<[T1, T2, T3, T4, T5, T6]>;
static parallelLimit<T1, T2, T3, T4, T5, T6, T7>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>
],
limit?: number
): Aigle<[T1, T2, T3, T4, T5, T6, T7]>;
static parallelLimit<T1, T2, T3, T4, T5, T6, T7, T8>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>,
T8 | PromiseLike<T8> | Aigle.PromiseCallback<T8>
],
limit?: number
): Aigle<[T1, T2, T3, T4, T5, T6, T7, T8]>;
static parallelLimit<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>,
T8 | PromiseLike<T8> | Aigle.PromiseCallback<T8>,
T9 | PromiseLike<T9> | Aigle.PromiseCallback<T9>
],
limit?: number
): Aigle<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
static parallelLimit<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
values: [
T1 | PromiseLike<T1> | Aigle.PromiseCallback<T1>,
T2 | PromiseLike<T2> | Aigle.PromiseCallback<T2>,
T3 | PromiseLike<T3> | Aigle.PromiseCallback<T3>,
T4 | PromiseLike<T4> | Aigle.PromiseCallback<T4>,
T5 | PromiseLike<T5> | Aigle.PromiseCallback<T5>,
T6 | PromiseLike<T6> | Aigle.PromiseCallback<T6>,
T7 | PromiseLike<T7> | Aigle.PromiseCallback<T7>,
T8 | PromiseLike<T8> | Aigle.PromiseCallback<T8>,
T9 | PromiseLike<T9> | Aigle.PromiseCallback<T9>,
T10 | PromiseLike<T10> | Aigle.PromiseCallback<T10>
],
limit?: number
): Aigle<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
static parallelLimit<T>(
values: (T | PromiseLike<T> | Aigle.PromiseCallback<T>)[],
limit?: number
): Aigle<T[]>;
/* each/forEach */
static each<T>(collection: T[], iterator?: Aigle.ArrayIterator<T, any>): Aigle<T[]>;
static each<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, any>
): Aigle<Aigle.List<T>>;
static each<T extends object>(collection: T, iterator?: Aigle.ObjectIterator<T, any>): Aigle<T>;
static forEach<T>(collection: T[], iterator?: Aigle.ArrayIterator<T, any>): Aigle<T[]>;
static forEach<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, any>
): Aigle<Aigle.List<T>>;
static forEach<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, any>
): Aigle<T>;
/* eachSeries/forEachSeries */
static eachSeries<T>(collection: T[], iterator?: Aigle.ArrayIterator<T, any>): Aigle<T[]>;
static eachSeries<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, any>
): Aigle<Aigle.List<T>>;
static eachSeries<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, any>
): Aigle<T>;
static forEachSeries<T>(collection: T[], iterator?: Aigle.ArrayIterator<T, any>): Aigle<T[]>;
static forEachSeries<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, any>
): Aigle<Aigle.List<T>>;
static forEachSeries<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, any>
): Aigle<T>;
/* eachLimit/forEachLimit */
static eachLimit<T>(collection: T[], iterator?: Aigle.ArrayIterator<T, any>): Aigle<T[]>;
static eachLimit<T>(
collection: T[],
limit: number,
iterator: Aigle.ArrayIterator<T, any>
): Aigle<T[]>;
static eachLimit<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, any>
): Aigle<Aigle.List<T>>;
static eachLimit<T>(
collection: Aigle.List<T>,
limit: number,
iterator: Aigle.ListIterator<T, any>
): Aigle<Aigle.List<T>>;
static eachLimit<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, any>
): Aigle<T>;
static eachLimit<T extends object>(
collection: T,
limit: number,
iterator: Aigle.ObjectIterator<T, any>
): Aigle<T>;
static forEachLimit<T>(collection: T[], iterator?: Aigle.ArrayIterator<T, any>): Aigle<T[]>;
static forEachLimit<T>(
collection: T[],
limit: number,
iterator: Aigle.ArrayIterator<T, any>
): Aigle<T[]>;
static forEachLimit<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, any>
): Aigle<Aigle.List<T>>;
static forEachLimit<T>(
collection: Aigle.List<T>,
limit: number,
iterator: Aigle.ListIterator<T, any>
): Aigle<Aigle.List<T>>;
static forEachLimit<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, any>
): Aigle<T>;
static forEachLimit<T extends object>(
collection: T,
limit: number,
iterator: Aigle.ObjectIterator<T, any>
): Aigle<T>;
/* map */
static map<T, R>(collection: T[], iterator: Aigle.ArrayIterator<T, R>): Aigle<R[]>;
static map<T, R>(collection: Aigle.List<T>, iterator: Aigle.ListIterator<T, R>): Aigle<R[]>;
static map<T extends object, R>(collection: T, iterator: Aigle.ObjectIterator<T, R>): Aigle<R[]>;
/* mapSeries */
static mapSeries<T, R>(collection: T[], iterator: Aigle.ArrayIterator<T, R>): Aigle<R[]>;
static mapSeries<T, R>(collection: Aigle.List<T>, iterator: Aigle.ListIterator<T, R>): Aigle<R[]>;
static mapSeries<T extends object, R>(
collection: T,
iterator: Aigle.ObjectIterator<T, R>
): Aigle<R[]>;
/* mapLimit */
static mapLimit<T, R>(collection: T[], iterator: Aigle.ArrayIterator<T, R>): Aigle<R[]>;
static mapLimit<T, R>(
collection: T[],
limit: number,
iterator: Aigle.ArrayIterator<T, R>
): Aigle<R[]>;
static mapLimit<T, R>(collection: Aigle.List<T>, iterator: Aigle.ListIterator<T, R>): Aigle<R[]>;
static mapLimit<T, R>(
collection: Aigle.List<T>,
limit: number,
iterator: Aigle.ListIterator<T, R>
): Aigle<R[]>;
static mapLimit<T extends object, R>(
collection: T,
iterator: Aigle.ObjectIterator<T, R>
): Aigle<R[]>;
static mapLimit<T extends object, R>(
collection: T,
limit: number,
iterator: Aigle.ObjectIterator<T, R>
): Aigle<R[]>;
/* mapValues */
static mapValues<T, R>(
collection: T[],
iterator?: Aigle.ArrayIterator<T, R>
): Aigle<Aigle.Dictionary<R>>;
static mapValues<T, R>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, R>
): Aigle<Aigle.Dictionary<R>>;
static mapValues<T extends object, R>(
collection: T,
iterator?: Aigle.ObjectIterator<T, R>
): Aigle<Record<keyof T, R>>;
/* mapValuesSeries */
static mapValuesSeries<T, R>(
collection: T[],
iterator?: Aigle.ArrayIterator<T, R>
): Aigle<Aigle.Dictionary<R>>;
static mapValuesSeries<T, R>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, R>
): Aigle<Aigle.Dictionary<R>>;
static mapValuesSeries<T extends object, R>(
collection: T,
iterator?: Aigle.ObjectIterator<T, R>
): Aigle<Record<keyof T, R>>;
/* mapValuesLimit */
static mapValuesLimit<T, R>(
collection: T[],
iterator?: Aigle.ArrayIterator<T, R>
): Aigle<Aigle.Dictionary<R>>;
static mapValuesLimit<T, R>(
collection: T[],
limit: number,
iterator: Aigle.ArrayIterator<T, R>
): Aigle<Aigle.Dictionary<R>>;
static mapValuesLimit<T, R>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, R>
): Aigle<Aigle.Dictionary<R>>;
static mapValuesLimit<T, R>(
collection: Aigle.List<T>,
limit: number,
iterator: Aigle.ListIterator<T, R>
): Aigle<Aigle.Dictionary<R>>;
static mapValuesLimit<T extends object, R>(
collection: T,
iterator?: Aigle.ObjectIterator<T, R>
): Aigle<Record<keyof T, R>>;
static mapValuesLimit<T extends object, R>(
collection: T,
limit: number,
iterator: Aigle.ObjectIterator<T, R>
): Aigle<Record<keyof T, R>>;
/* concat */
static concat<T, R>(collection: T[], iterator?: Aigle.ArrayIterator<T, R | R[]>): Aigle<R[]>;
static concat<T, R>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, R | R[]>
): Aigle<R[]>;
static concat<T extends object, R>(
collection: T,
iterator?: Aigle.ObjectIterator<T, R | R[]>
): Aigle<R[]>;
/* concatSeries */
static concatSeries<T, R>(
collection: T[],
iterator?: Aigle.ArrayIterator<T, R | R[]>
): Aigle<R[]>;
static concatSeries<T, R>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, R | R[]>
): Aigle<R[]>;
static concatSeries<T extends object, R>(
collection: T,
iterator?: Aigle.ObjectIterator<T, R | R[]>
): Aigle<R[]>;
/* concatLimit */
static concatLimit<T, R>(collection: T[], iterator?: Aigle.ArrayIterator<T, R | R[]>): Aigle<R[]>;
static concatLimit<T, R>(
collection: T[],
limit: number,
iterator: Aigle.ArrayIterator<T, R | R[]>
): Aigle<R[]>;
static concatLimit<T, R>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, R | R[]>
): Aigle<R[]>;
static concatLimit<T, R>(
collection: Aigle.List<T>,
limit: number,
iterator: Aigle.ListIterator<T, R | R[]>
): Aigle<R[]>;
static concatLimit<T extends object, R>(
collection: T,
iterator?: Aigle.ObjectIterator<T, R | R[]>
): Aigle<R[]>;
static concatLimit<T extends object, R>(
collection: T,
limit: number,
iterator: Aigle.ObjectIterator<T, R | R[]>
): Aigle<R[]>;
/* every */
static every<T>(collection: T[], iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<boolean>;
static every<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<boolean>;
static every<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<boolean>;
/* everySeries */
static everySeries<T>(
collection: T[],
iterator?: Aigle.ArrayIterator<T, boolean>
): Aigle<boolean>;
static everySeries<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<boolean>;
static everySeries<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<boolean>;
/* everyLimit */
static everyLimit<T>(collection: T[], iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<boolean>;
static everyLimit<T>(
collection: T[],
limit: number,
iterator: Aigle.ArrayIterator<T, boolean>
): Aigle<boolean>;
static everyLimit<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<boolean>;
static everyLimit<T>(
collection: Aigle.List<T>,
limit: number,
iterator: Aigle.ListIterator<T, boolean>
): Aigle<boolean>;
static everyLimit<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<boolean>;
static everyLimit<T extends object>(
collection: T,
limit: number,
iterator: Aigle.ObjectIterator<T, boolean>
): Aigle<boolean>;
/* some */
static some<T>(collection: T[], iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<boolean>;
static some<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<boolean>;
static some<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<boolean>;
/* someSeries */
static someSeries<T>(collection: T[], iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<boolean>;
static someSeries<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<boolean>;
static someSeries<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<boolean>;
/* someLimit */
static someLimit<T>(collection: T[], iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<boolean>;
static someLimit<T>(
collection: T[],
limit: number,
iterator: Aigle.ArrayIterator<T, boolean>
): Aigle<boolean>;
static someLimit<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<boolean>;
static someLimit<T>(
collection: Aigle.List<T>,
limit: number,
iterator: Aigle.ListIterator<T, boolean>
): Aigle<boolean>;
static someLimit<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<boolean>;
static someLimit<T extends object>(
collection: T,
limit: number,
iterator: Aigle.ObjectIterator<T, boolean>
): Aigle<boolean>;
/* filter */
static filter<T>(collection: T[], iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<T[]>;
static filter<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<T[]>;
static filter<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<Array<T[keyof T]>>;
/* filterSeries */
static filterSeries<T>(collection: T[], iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<T[]>;
static filterSeries<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<T[]>;
static filterSeries<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<Array<T[keyof T]>>;
/* filterLimit */
static filterLimit<T>(collection: T[], iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<T[]>;
static filterLimit<T>(
collection: T[],
limit: number,
iterator: Aigle.ArrayIterator<T, boolean>
): Aigle<T[]>;
static filterLimit<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<T[]>;
static filterLimit<T>(
collection: Aigle.List<T>,
limit: number,
iterator: Aigle.ListIterator<T, boolean>
): Aigle<T[]>;
static filterLimit<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<Array<T[keyof T]>>;
static filterLimit<T extends object>(
collection: T,
limit: number,
iterator: Aigle.ObjectIterator<T, boolean>
): Aigle<Array<T[keyof T]>>;
/* reject */
static reject<T>(collection: T[], iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<T[]>; // tslint:disable-line:adjacent-overload-signatures
static reject<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<T[]>;
static reject<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<Array<T[keyof T]>>;
/* rejectSeries */
static rejectSeries<T>(collection: T[], iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<T[]>;
static rejectSeries<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<T[]>;
static rejectSeries<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<Array<T[keyof T]>>;
/* rejectLimit */
static rejectLimit<T>(collection: T[], iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<T[]>;
static rejectLimit<T>(
collection: T[],
limit: number,
iterator: Aigle.ArrayIterator<T, boolean>
): Aigle<T[]>;
static rejectLimit<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<T[]>;
static rejectLimit<T>(
collection: Aigle.List<T>,
limit: number,
iterator: Aigle.ListIterator<T, boolean>
): Aigle<T[]>;
static rejectLimit<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<Array<T[keyof T]>>;
static rejectLimit<T extends object>(
collection: T,
limit: number,
iterator: Aigle.ObjectIterator<T, boolean>
): Aigle<Array<T[keyof T]>>;
/* sortBy */
static sortBy<T>(collection: T[], iterator?: Aigle.ArrayIterator<T>): Aigle<T[]>;
static sortBy<T>(collection: Aigle.List<T>, iterator?: Aigle.ListIterator<T>): Aigle<T[]>;
static sortBy<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T>
): Aigle<Array<T[keyof T]>>;
/* sortBySeries */
static sortBySeries<T>(collection: T[], iterator?: Aigle.ArrayIterator<T>): Aigle<T[]>;
static sortBySeries<T>(collection: Aigle.List<T>, iterator?: Aigle.ListIterator<T>): Aigle<T[]>;
static sortBySeries<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T>
): Aigle<Array<T[keyof T]>>;
/* sortByLimit */
static sortByLimit<T>(collection: T[], iterator?: Aigle.ArrayIterator<T>): Aigle<T[]>;
static sortByLimit<T>(
collection: T[],
limit: number,
iterator: Aigle.ArrayIterator<T>
): Aigle<T[]>;
static sortByLimit<T>(collection: Aigle.List<T>, iterator?: Aigle.ListIterator<T>): Aigle<T[]>;
static sortByLimit<T>(
collection: Aigle.List<T>,
limit: number,
iterator: Aigle.ListIterator<T>
): Aigle<T[]>;
static sortByLimit<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T>
): Aigle<Array<T[keyof T]>>;
static sortByLimit<T extends object>(
collection: T,
limit: number,
iterator: Aigle.ObjectIterator<T>
): Aigle<Array<T[keyof T]>>;
/* find / detect */
static find<T>(collection: T[], iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<T>;
static find<T>(collection: Aigle.List<T>, iterator?: Aigle.ListIterator<T, boolean>): Aigle<T>;
static find<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<T[keyof T]>;
static detect<T>(collection: T[], iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<T>;
static detect<T>(collection: Aigle.List<T>, iterator?: Aigle.ListIterator<T, boolean>): Aigle<T>;
static detect<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<T[keyof T]>;
/* findSeries / detectSeries */
static findSeries<T>(collection: T[], iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<T>;
static findSeries<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<T>;
static findSeries<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<T[keyof T]>;
static detectSeries<T>(collection: T[], iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<T>;
static detectSeries<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<T>;
static detectSeries<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<T[keyof T]>;
/* findLimit / detectLimit */
static findLimit<T>(collection: T[], iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<T>;
static findLimit<T>(
collection: T[],
limit: number,
iterator: Aigle.ArrayIterator<T, boolean>
): Aigle<T>;
static findLimit<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<T>;
static findLimit<T>(
collection: Aigle.List<T>,
limit: number,
iterator: Aigle.ListIterator<T, boolean>
): Aigle<T>;
static findLimit<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<T[keyof T]>;
static findLimit<T extends object>(
collection: T,
limit: number,
iterator: Aigle.ObjectIterator<T, boolean>
): Aigle<T[keyof T]>;
static detectLimit<T>(collection: T[], iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<T>;
static detectLimit<T>(
collection: T[],
limit: number,
iterator: Aigle.ArrayIterator<T, boolean>
): Aigle<T>;
static detectLimit<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<T>;
static detectLimit<T>(
collection: Aigle.List<T>,
limit: number,
iterator: Aigle.ListIterator<T, boolean>
): Aigle<T>;
static detectLimit<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<T[keyof T]>;
static detectLimit<T extends object>(
collection: T,
limit: number,
iterator: Aigle.ObjectIterator<T, boolean>
): Aigle<T[keyof T]>;
/* findIndex */
static findIndex<T>(collection: T[], iterator?: Aigle.ArrayIterator<T, boolean>): Aigle<number>;
static findIndex<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<number>;
static findIndex<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<number>;
/* findIndexSeries */
static findIndexSeries<T>(
collection: T[],
iterator?: Aigle.ArrayIterator<T, boolean>
): Aigle<number>;
static findIndexSeries<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<number>;
static findIndexSeries<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<number>;
/* findIndexLimit */
static findIndexLimit<T>(
collection: T[],
iterator?: Aigle.ArrayIterator<T, boolean>
): Aigle<number>;
static findIndexLimit<T>(
collection: T[],
limit: number,
iterator: Aigle.ArrayIterator<T, boolean>
): Aigle<number>;
static findIndexLimit<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<number>;
static findIndexLimit<T>(
collection: Aigle.List<T>,
limit: number,
iterator: Aigle.ListIterator<T, boolean>
): Aigle<number>;
static findIndexLimit<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<number>;
static findIndexLimit<T extends object>(
collection: T,
limit: number,
iterator: Aigle.ObjectIterator<T, boolean>
): Aigle<number>;
/* findKey */
static findKey<T>(
collection: T[],
iterator?: Aigle.ArrayIterator<T, boolean>
): Aigle<string | undefined>;
static findKey<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<string | undefined>;
static findKey<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<string | undefined>;
/* findKeySeries */
static findKeySeries<T>(
collection: T[],
iterator?: Aigle.ArrayIterator<T, boolean>
): Aigle<string | undefined>;
static findKeySeries<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<string | undefined>;
static findKeySeries<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<string | undefined>;
/* findKeyLimit */
static findKeyLimit<T>(
collection: T[],
iterator?: Aigle.ArrayIterator<T, boolean>
): Aigle<string | undefined>;
static findKeyLimit<T>(
collection: T[],
limit: number,
iterator: Aigle.ArrayIterator<T, boolean>
): Aigle<string | undefined>;
static findKeyLimit<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<string | undefined>;
static findKeyLimit<T>(
collection: Aigle.List<T>,
limit: number,
iterator: Aigle.ListIterator<T, boolean>
): Aigle<string | undefined>;
static findKeyLimit<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<string | undefined>;
static findKeyLimit<T extends object>(
collection: T,
limit: number,
iterator: Aigle.ObjectIterator<T, boolean>
): Aigle<string | undefined>;
/* groupBy */
static groupBy<T>(
collection: T[],
iterator?: Aigle.ArrayIterator<T>
): Aigle<Aigle.Dictionary<T[]>>;
static groupBy<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T>
): Aigle<Aigle.Dictionary<T[]>>;
static groupBy<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T>
): Aigle<Aigle.Dictionary<T[]>>;
/* groupBySeries */
static groupBySeries<T>(
collection: T[],
iterator?: Aigle.ArrayIterator<T>
): Aigle<Aigle.Dictionary<T[]>>;
static groupBySeries<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T>
): Aigle<Aigle.Dictionary<T[]>>;
static groupBySeries<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T>
): Aigle<Aigle.Dictionary<T[]>>;
/* groupByLimit */
static groupByLimit<T>(
collection: T[],
iterator?: Aigle.ArrayIterator<T>
): Aigle<Aigle.Dictionary<T[]>>;
static groupByLimit<T>(
collection: T[],
limit: number,
iterator: Aigle.ArrayIterator<T>
): Aigle<Aigle.Dictionary<T[]>>;
static groupByLimit<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T>
): Aigle<Aigle.Dictionary<T[]>>;
static groupByLimit<T>(
collection: Aigle.List<T>,
limit: number,
iterator: Aigle.ListIterator<T>
): Aigle<Aigle.Dictionary<T[]>>;
static groupByLimit<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T>
): Aigle<Aigle.Dictionary<T[]>>;
static groupByLimit<T extends object>(
collection: T,
limit: number,
iterator: Aigle.ObjectIterator<T>
): Aigle<Aigle.Dictionary<T[]>>;
/* omit */
static omit<T>(
collection: T[],
iterator?: Aigle.ArrayIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static omit<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static omit<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<Partial<T>>;
/* omitBy */
static omitBy<T>(
collection: T[],
iterator?: Aigle.ArrayIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static omitBy<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static omitBy<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<Partial<T>>;
/* omitSeries / omitBySeries */
static omitSeries<T>(
collection: T[],
iterator?: Aigle.ArrayIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static omitSeries<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static omitSeries<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<Partial<T>>;
static omitBySeries<T>(
collection: T[],
iterator?: Aigle.ArrayIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static omitBySeries<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static omitBySeries<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<Partial<T>>;
/* omitLimit / omitByLimit */
static omitLimit<T>(
collection: T[],
iterator?: Aigle.ArrayIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static omitLimit<T>(
collection: T[],
limit: number,
iterator: Aigle.ArrayIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static omitLimit<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static omitLimit<T>(
collection: Aigle.List<T>,
limit: number,
iterator: Aigle.ListIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static omitLimit<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<Partial<T>>;
static omitLimit<T extends object>(
collection: T,
limit: number,
iterator: Aigle.ObjectIterator<T, boolean>
): Aigle<Partial<T>>;
static omitByLimit<T>(
collection: T[],
iterator?: Aigle.ArrayIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static omitByLimit<T>(
collection: T[],
limit: number,
iterator: Aigle.ArrayIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static omitByLimit<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static omitByLimit<T>(
collection: Aigle.List<T>,
limit: number,
iterator: Aigle.ListIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static omitByLimit<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<Partial<T>>;
static omitByLimit<T extends object>(
collection: T,
limit: number,
iterator: Aigle.ObjectIterator<T, boolean>
): Aigle<Partial<T>>;
/* pick */
static pick<T>(
collection: T[],
iterator?: Aigle.ArrayIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static pick<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static pick<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
/* pickBy */
static pickBy<T>(
collection: T[],
iterator?: Aigle.ArrayIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static pickBy<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static pickBy<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
/* pickSeries / pickBySeries */
static pickSeries<T>(
collection: T[],
iterator?: Aigle.ArrayIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static pickSeries<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static pickSeries<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static pickBySeries<T>(
collection: T[],
iterator?: Aigle.ArrayIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static pickBySeries<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static pickBySeries<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
/* pickLimit / pickByLimit */
static pickLimit<T>(
collection: T[],
iterator?: Aigle.ArrayIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static pickLimit<T>(
collection: T[],
limit: number,
iterator: Aigle.ArrayIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static pickLimit<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static pickLimit<T>(
collection: Aigle.List<T>,
limit: number,
iterator: Aigle.ListIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static pickLimit<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static pickLimit<T extends object>(
collection: T,
limit: number,
iterator: Aigle.ObjectIterator<T, boolean>
): Aigle<Aigle.Dictionary<T[]>>;
static pickByLimit<T>(
collection: T[],
iterator?: Aigle.ArrayIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static pickByLimit<T>(
collection: T[],
limit: number,
iterator: Aigle.ArrayIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static pickByLimit<T>(
collection: Aigle.List<T>,
iterator?: Aigle.ListIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static pickByLimit<T>(
collection: Aigle.List<T>,
limit: number,
iterator: Aigle.ListIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static pickByLimit<T extends object>(
collection: T,
iterator?: Aigle.ObjectIterator<T, boolean>
): Aigle<Aigle.Dictionary<T>>;
static pickByLimit<T extends object>(
collection: T,
limit: number,
iterator: Aigle.ObjectIterator<T, boolean>
): Aigle<Aigle.Dictionary<T[]>>;
/* transform */
static transform<T, R>(
collection: T[],
iterator: Aigle.MemoArrayIterator<T, R[]>,
accumulator?: R[]
): Aigle<R[]>;
static transform<T, R>(
collection: T[],
iterator: Aigle.MemoArrayIterator<T, Aigle.Dictionary<R>>,
accumulator: Aigle.Dictionary<R>
): Aigle<Aigle.Dictionary<R>>;
static transform<T, R>(
collection: Aigle.List<T>,
iterator: Aigle.MemoListIterator<T, R[]>,
accumulator?: R[]
): Aigle<R[]>;
static transform<T, R>(
collection: Aigle.List<T>,
iterator: Aigle.MemoListIterator<T, Aigle.Dictionary<R>>,
accumulator?: Aigle.Dictionary<R>
): Aigle<Aigle.Dictionary<R>>;
static transform<T extends object, R>(
collection: T,
iterator: Aigle.MemoObjectIterator<T, Aigle.Dictionary<R>>,
accumulator?: Aigle.Dictionary<R>
): Aigle<Aigle.Dictionary<R>>;
static transform<T extends object, R>(
collection: T,
iterator: Aigle.MemoObjectIterator<T, R[]>,
accumulator: R[]
): Aigle<R[]>;
/* transformSeries */
static transformSeries<T, R>(
collection: T[],
iterator: Aigle.MemoArrayIterator<T, R[]>,
accumulator?: R[]
): Aigle<R[]>;
static transformSeries<T, R>(
collection: T[],
iterator: Aigle.MemoArrayIterator<T, Aigle.Dictionary<R>>,
accumulator: Aigle.Dictionary<R>
): Aigle<Aigle.Dictionary<R>>;
static transformSeries<T, R>(
collection: Aigle.List<T>,
iterator: Aigle.MemoListIterator<T, R[]>,
accumulator?: R[]
): Aigle<R[]>;
static transformSeries<T, R>(
collection: Aigle.List<T>,
iterator: Aigle.MemoListIterator<T, Aigle.Dictionary<R>>,
accumulator?: Aigle.Dictionary<R>
): Aigle<Aigle.Dictionary<R>>;
static transformSeries<T extends object, R>(
collection: T,
iterator: Aigle.MemoObjectIterator<T, Aigle.Dictionary<R>>,
accumulator?: Aigle.Dictionary<R>
): Aigle<Aigle.Dictionary<R>>;
static transformSeries<T extends object, R>(
collection: T,
iterator: Aigle.MemoObjectIterator<T, R[]>,
accumulator: R[]
): Aigle<R[]>;
/* transformLimit */
static transformLimit<T, R>(
collection: T[],
iterator: Aigle.MemoArrayIterator<T, R[]>,
accumulator?: R[]
): Aigle<R[]>;
static transformLimit<T, R>(
collection: T[],
limit: number,
iterator: Aigle.MemoArrayIterator<T, R[]>,
accumulator?: R[]
): Aigle<R[]>;
static transformLimit<T, R>(
collection: T[],
iterator: Aigle.MemoArrayIterator<T, Aigle.Dictionary<R>>,
accumulator: Aigle.Dictionary<R>
): Aigle<Aigle.Dictionary<R>>;
static transformLimit<T, R>(
collection: T[],
limit: number,
iterator: Aigle.MemoArrayIterator<T, Aigle.Dictionary<R>>,
accumulator: Aigle.Dictionary<R>
): Aigle<Aigle.Dictionary<R>>;
static transformLimit<T, R>(
collection: Aigle.List<T>,
iterator: Aigle.MemoListIterator<T, R[]>,
accumulator?: R[]
): Aigle<R[]>;
static transformLimit<T, R>(
collection: Aigle.List<T>,
limit: number,
iterator: Aigle.MemoListIterator<T, R[]>,
accumulator?: R[]
): Aigle<R[]>;
static transformLimit<T, R>(
collection: Aigle.List<T>,
iterator: Aigle.MemoListIterator<T, Aigle.Dictionary<R>>,
accumulator?: Aigle.Dictionary<R>
): Aigle<Aigle.Dictionary<R>>;
static transformLimit<T, R>(
collection: Aigle.List<T>,
limit: number,
iterator: Aigle.MemoListIterator<T, Aigle.Dictionary<R>>,
accumulator?: Aigle.Dictionary<R>
): Aigle<Aigle.Dictionary<R>>;
static transformLimit<T extends object, R>(
collection: T,
iterator: Aigle.MemoObjectIterator<T, Aigle.Dictionary<R>>,
accumulator?: Aigle.Dictionary<R>
): Aigle<Aigle.Dictionary<R>>;
static transformLimit<T extends object, R>(
collection: T,
limit: number,
iterator: Aigle.MemoObjectIterator<T, Aigle.Dictionary<R>>,
accumulator?: Aigle.Dictionary<R>
): Aigle<Aigle.Dictionary<R>>;
static transformLimit<T extends object, R>(
collection: T,
iterator: Aigle.MemoObjectIterator<T, R[]>,
accumulator: R[]
): Aigle<R[]>;
static transformLimit<T extends object, R>(
collection: T,
limit: number,
iterator: Aigle.MemoObjectIterator<T, R[]>,
accumulator: R[]
): Aigle<R[]>;
/* reduce */
static reduce<T, R>(
collection: T[],
iterator: Aigle.MemoArrayIterator<T, R, R>,
accumulator?: R
): Aigle<R>;
static reduce<T, R>(
collection: Aigle.List<T>,
iterator: Aigle.MemoListIterator<T, R, R>,
accumulator?: R
): Aigle<R>;
static reduce<T extends object, R>(
collection: T,
iterator: Aigle.MemoObjectIterator<T, R, R>,
accumulator?: R
): Aigle<R>;
/* delay */
static delay<T>(ms: number, value?: T): Aigle<T>;
/* tap */
static tap<T>(value: T, intercepter: (value: T) => Aigle.ReturnType<any>): Aigle<T>;
/* thru */
static thru<T, R>(value: T, intercepter: (value: T) => Aigle.ReturnType<R>): Aigle<R>;
/**
* flow
* @see https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/lodash/common/util.d.ts#L198
*/
static flow<R1, R2>(
f1: () => Aigle.ReturnType<R1>,
f2: (a: R1) => Aigle.ReturnType<R2>
): () => Aigle<R2>;
static flow<R1, R2, R3>(
f1: () => Aigle.ReturnType<R1>,
f2: (a: R1) => Aigle.ReturnType<R2>,
f3: (a: R2) => Aigle.ReturnType<R3>
): () => Aigle<R3>;
static flow<R1, R2, R3, R4>(
f1: () => Aigle.ReturnType<R1>,
f2: (a: R1) => Aigle.ReturnType<R2>,
f3: (a: R2) => Aigle.ReturnType<R3>,
f4: (a: R3) => Aigle.ReturnType<R4>
): () => Aigle<R4>;
static flow<R1, R2, R3, R4, R5>(
f1: () => Aigle.ReturnType<R1>,
f2: (a: R1) => Aigle.ReturnType<R2>,
f3: (a: R2) => Aigle.ReturnType<R3>,
f4: (a: R3) => Aigle.ReturnType<R4>,
f5: (a: R4) => Aigle.ReturnType<R5>
): () => Aigle<R5>;
static flow<R1, R2, R3, R4, R5, R6>(
f1: () => Aigle.ReturnType<R1>,
f2: (a: R1) => Aigle.ReturnType<R2>,
f3: (a: R2) => Aigle.ReturnType<R3>,
f4: (a: R3) => Aigle.ReturnType<R4>,
f5: (a: R4) => Aigle.ReturnType<R5>,
f6: (a: R5) => Aigle.ReturnType<R6>
): () => Aigle<R6>;
static flow<R1, R2, R3, R4, R5, R6, R7>(
f1: () => Aigle.ReturnType<R1>,
f2: (a: R1) => Aigle.ReturnType<R2>,
f3: (a: R2) => Aigle.ReturnType<R3>,
f4: (a: R3) => Aigle.ReturnType<R4>,
f5: (a: R4) => Aigle.ReturnType<R5>,
f6: (a: R5) => Aigle.ReturnType<R6>,
f7: (a: R6) => Aigle.ReturnType<R7>,
...funcs: Array<Aigle.Many<(a: any) => any>>
): () => Aigle<any>;
// 1-argument first function
static flow<A1, R1, R2>(
f1: (a1: A1) => Aigle.ReturnType<R1>,
f2: (a: R1) => Aigle.ReturnType<R2>
): (a1: A1) => Aigle<R2>;
static flow<A1, R1, R2, R3>(
f1: (a1: A1) => Aigle.ReturnType<R1>,
f2: (a: R1) => Aigle.ReturnType<R2>,
f3: (a: R2) => Aigle.ReturnType<R3>
): (a1: A1) => Aigle<R3>;
static flow<A1, R1, R2, R3, R4>(
f1: (a1: A1) => Aigle.ReturnType<R1>,
f2: (a: R1) => Aigle.ReturnType<R2>,
f3: (a: R2) => Aigle.ReturnType<R3>,
f4: (a: R3) => Aigle.ReturnType<R4>
): (a1: A1) => Aigle<R4>;
static flow<A1, R1, R2, R3, R4, R5>(
f1: (a1: A1) => Aigle.ReturnType<R1>,
f2: (a: R1) => Aigle.ReturnType<R2>,
f3: (a: R2) => Aigle.ReturnType<R3>,
f4: (a: R3) => Aigle.ReturnType<R4>,
f5: (a: R4) => Aigle.ReturnType<R5>
): (a1: A1) => Aigle<R5>;
static flow<A1, R1, R2, R3, R4, R5, R6>(
f1: (a1: A1) => Aigle.ReturnType<R1>,
f2: (a: R1) => Aigle.ReturnType<R2>,
f3: (a: R2) => Aigle.ReturnType<R3>,
f4: (a: R3) => Aigle.ReturnType<R4>,
f5: (a: R4) => Aigle.ReturnType<R5>,
f6: (a: R5) => Aigle.ReturnType<R6>
): (a1: A1) => Aigle<R6>;
static flow<A1, R1, R2, R3, R4, R5, R6, R7>(
f1: (a1: A1) => Aigle.ReturnType<R1>,
f2: (a: R1) => Aigle.ReturnType<R2>,
f3: (a: R2) => Aigle.ReturnType<R3>,
f4: (a: R3) => Aigle.ReturnType<R4>,
f5: (a: R4) => Aigle.ReturnType<R5>,
f6: (a: R5) => Aigle.ReturnType<R6>,
f7: (a: R6) => Aigle.ReturnType<R7>,
...funcs: Array<Aigle.Many<(a: any) => any>>
): (a1: A1) => Aigle<any>;
// 2-argument first function
static flow<A1, A2, R1, R2>(
f1: (a1: A1, a2: A2) => Aigle.ReturnType<R1>,
f2: (a: R1) => Aigle.ReturnType<R2>
): (a1: A1, a2: A2) => Aigle<R2>;
static flow<A1, A2, R1, R2, R3>(
f1: (a1: A1, a2: A2) => Aigle.ReturnType<R1>,
f2: (a: R1) => Aigle.ReturnType<R2>,
f3: (a: R2) => Aigle.ReturnType<R3>
): (a1: A1, a2: A2) => Aigle<R3>;
static flow<A1, A2, R1, R2, R3, R4>(
f1: (a1: A1, a2: A2) => Aigle.ReturnType<R1>,
f2: (a: R1) => Aigle.ReturnType<R2>,
f3: (a: R2) => Aigle.ReturnType<R3>,
f4: (a: R3) => Aigle.ReturnType<R4>
): (a1: A1, a2: A2) => Aigle<R4>;
static flow<A1, A2, R1, R2, R3, R4, R5>(
f1: (a1: A1, a2: A2) => Aigle.ReturnType<R1>,
f2: (a: R1) => Aigle.ReturnType<R2>,
f3: (a: R2) => Aigle.ReturnType<R3>,
f4: (a: R3) => Aigle.ReturnType<R4>,
f5: (a: R4) => Aigle.ReturnType<R5>
): (a1: A1, a2: A2) => Aigle<R5>;
static flow<A1, A2, R1, R2, R3, R4, R5, R6>(
f1: (a1: A1, a2: A2) => Aigle.ReturnType<R1>,
f2: (a: R1) => Aigle.ReturnType<R2>,
f3: (a: R2) => Aigle.ReturnType<R3>,
f4: (a: R3) => Aigle.ReturnType<R4>,
f5: (a: R4) => Aigle.ReturnType<R5>,
f6: (a: R5) => Aigle.ReturnType<R6>
): (a1: A1, a2: A2) => Aigle<R6>;
static flow<A1, A2, R1, R2, R3, R4, R5, R6, R7>(
f1: (a1: A1, a2: A2) => Aigle.ReturnType<R1>,
f2: (a: R1) => Aigle.ReturnType<R2>,
f3: (a: R2) => Aigle.ReturnType<R3>,
f4: (a: R3) => Aigle.ReturnType<R4>,
f5: (a: R4) => Aigle.ReturnType<R5>,
f6: (a: R5) => Aigle.ReturnType<R6>,
f7: (a: R6) => Aigle.ReturnType<R7>,
...funcs: Array<Aigle.Many<(a: any) => any>>
): (a1: A1, a2: A2) => Aigle<any>;
// any-argument first function
static flow<A1, A2, A3, R1, R2>(
f1: (a1: A1, a2: A2, a3: A3, ...args: any[]) => Aigle.ReturnType<R1>,
f2: (a: R1) => Aigle.ReturnType<R2>
): (a1: A1, a2: A2, a3: A3, ...args: any[]) => Aigle<R2>;
static flow<A1, A2, A3, R1, R2, R3>(
f1: (a1: A1, a2: A2, a3: A3, ...args: any[]) => Aigle.ReturnType<R1>,
f2: (a: R1) => Aigle.ReturnType<R2>,
f3: (a: R2) => Aigle.ReturnType<R3>
): (a1: A1, a2: A2, a3: A3, ...args: any[]) => Aigle<R3>;
static flow<A1, A2, A3, R1, R2, R3, R4>(
f1: (a1: A1, a2: A2, a3: A3, ...args: any[]) => Aigle.ReturnType<R1>,
f2: (a: R1) => Aigle.ReturnType<R2>,
f3: (a: R2) => Aigle.ReturnType<R3>,
f4: (a: R3) => Aigle.ReturnType<R4>
): (a1: A1, a2: A2, a3: A3, ...args: any[]) => Aigle<R4>;
static flow<A1, A2, A3, R1, R2, R3, R4, R5>(
f1: (a1: A1, a2: A2, a3: A3, ...args: any[]) => Aigle.ReturnType<R1>,
f2: (a: R1) => Aigle.ReturnType<R2>,
f3: (a: R2) => Aigle.ReturnType<R3>,
f4: (a: R3) => Aigle.ReturnType<R4>,
f5: (a: R4) => Aigle.ReturnType<R5>
): (a1: A1, a2: A2, a3: A3, ...args: any[]) => Aigle<R5>;
static flow<A1, A2, A3, R1, R2, R3, R4, R5, R6>(
f1: (a1: A1, a2: A2, a3: A3, ...args: any[]) => Aigle.ReturnType<R1>,
f2: (a: R1) => Aigle.ReturnType<R2>,
f3: (a: R2) => Aigle.ReturnType<R3>,
f4: (a: R3) => Aigle.ReturnType<R4>,
f5: (a: R4) => Aigle.ReturnType<R5>,
f6: (a: R5) => Aigle.ReturnType<R6>
): (a1: A1, a2: A2, a3: A3, ...args: any[]) => Aigle<R6>;
static flow<A1, A2, A3, R1, R2, R3, R4, R5, R6, R7>(
f1: (a1: A1, a2: A2, a3: A3, ...args: any[]) => Aigle.ReturnType<R1>,
f2: (a: R1) => Aigle.ReturnType<R2>,
f3: (a: R2) => Aigle.ReturnType<R3>,
f4: (a: R3) => Aigle.ReturnType<R4>,
f5: (a: R4) => Aigle.ReturnType<R5>,
f6: (a: R5) => Aigle.ReturnType<R6>,
f7: (a: R6) => Aigle.ReturnType<R7>,
...funcs: Array<Aigle.Many<(a: any) => any>>
): (a1: A1, a2: A2, a3: A3, ...args: any[]) => Aigle<any>;
/* times */
static times<T>(n: number, iterator?: (num: number) => Aigle.ReturnType<T>): Aigle<T[]>;
/* timesSeries */
static timesSeries<T>(n: number, iterator?: (num: number) => Aigle.ReturnType<T>): Aigle<T[]>;
/* timesLimit */
static timesLimit<T>(n: number, iterator?: (num: number) => Aigle.ReturnType<T>): Aigle<T[]>;
static timesLimit<T>(
n: number,
limit: number,
iterator: (num: number) => Aigle.ReturnType<T>
): Aigle<T[]>;
/* doUntil */
static doUntil<T>(
iterator: (value: T) => Aigle.ReturnType<T>,
tester: (value: T) => Aigle.ReturnType<boolean>
): Aigle<T>;
static doUntil<T>(
value: T,
iterator: (value: T) => Aigle.ReturnType<T>,
tester: (value: T) => Aigle.ReturnType<boolean>
): Aigle<T>;
/* doWhilst */
static doWhilst<T>(
iterator: (value: T) => Aigle.ReturnType<T>,
tester: (value: T) => Aigle.ReturnType<boolean>
): Aigle<T>;
static doWhilst<T>(
value: T,
iterator: (value: T) => Aigle.ReturnType<T>,
tester: (value: T) => Aigle.ReturnType<boolean>
): Aigle<T>;
/* until */
static until<T>(
tester: (value: T) => Aigle.ReturnType<boolean>,
iterator: (value: T) => Aigle.ReturnType<T>
): Aigle<T>;
static until<T>(
value: T,
tester: (value: T) => Aigle.ReturnType<boolean>,
iterator: (value: T) => Aigle.ReturnType<T>
): Aigle<T>;
/* whilst */
static whilst<T>(
tester: (value: T) => Aigle.ReturnType<boolean>,
iterator: (value: T) => Aigle.ReturnType<T>
): Aigle<T>;
static whilst<T>(
value: T,
tester: (value: T) => Aigle.ReturnType<boolean>,
iterator: (value: T) => Aigle.ReturnType<T>
): Aigle<T>;
/* retry */
static retry<T>(handler: Aigle.PromiseCallback<T>): Aigle<T>;
static retry<T>(opts: number | Aigle.RetryOpts, handler: Aigle.PromiseCallback<T>): Aigle<T>;
/* attempt */
static attempt<T>(handler: Aigle.PromiseCallback<T>): Aigle<T>;
/* prommisify */
static promisify(fn: any, opts?: any): any;
/* prommisifyAll */
static promisifyAll(target: any, options?: any): any;
/* using */
static using<R1, T>(
arg1: Aigle.Disposer<R1>,
executor: (transaction1: R1) => Aigle.ReturnType<T>
): Aigle<T>;
static using<R1, R2, T>(
arg1: Aigle.Disposer<R1>,
arg2: Aigle.Disposer<R2>,
executor: (transaction1: R1, transaction2: R2) => Aigle.ReturnType<T>
): Aigle<T>;
static using<R1, R2, R3, T>(
arg1: Aigle.Disposer<R1>,
arg2: Aigle.Disposer<R2>,
arg3: Aigle.Disposer<R3>,
executor: (transaction1: R1, transaction2: R2, transaction3: R3) => Aigle.ReturnType<T>
): Aigle<T>;
/* mixin */
static mixin(sources: any, opts: any): any;
/* config */
static config(opts: Aigle.ConfigOpts): void;
static longStackTraces(): void;
}
declare namespace Aigle {
export enum State {
Pending = 'pending',
Fulfilled = 'fulfilled',
Rejected = 'rejected',
}
export class CancellationError extends Error {}
export class TimeoutError extends Error {}
export type ReturnType<T> = T | PromiseLike<T>;
export type ResolvableProps<T> = object & { [K in keyof T]: ReturnType<T[K]> };
export type CatchFilter<E> = (new (...args: any[]) => E) | ((error: E) => boolean) | (object & E);
export type Many<T> = T | T[];
export type List<T> = ArrayLike<T>;
export type Dictionary<T> = Record<string, T>;
export type NotVoid = {} | null | undefined;
export type PromiseCallback<T> = () => ReturnType<T>;
export type ArrayIterator<T, TResult = NotVoid> = (
value: T,
index: number,
collection: T[]
) => ReturnType<TResult>;
export type ListIterator<T, TResult = NotVoid> = (
value: T,
index: number,
collection: List<T>
) => ReturnType<TResult>;
export type ObjectIterator<T, TResult = NotVoid> = (
value: T[keyof T],
key: string,
collection: T
) => ReturnType<TResult>;
export type MemoArrayIterator<T, TResult, IResult = any> = (
accumulator: TResult,
value: T,
index: number,
collection: T[]
) => ReturnType<IResult>;
export type MemoListIterator<T, TResult, IResult = any> = (
accumulator: TResult,
value: T,
index: number,
collection: List<T>
) => ReturnType<IResult>;
export type MemoObjectIterator<T, TResult, IResult = any> = (
accumulator: TResult,
value: T[keyof T],
key: string,
collection: T
) => ReturnType<IResult>;
export interface AllSettledFulfilled<T> {
state: State.Fulfilled;
value: T;
}
export interface AllSettledRejected {
state: State.Rejected;
reason: any;
}
export type AllSettledResponse<T> = AllSettledFulfilled<T> | AllSettledRejected;
export interface ConfigOpts {
longStackTraces?: boolean;
cancellation?: boolean;
}
export interface RetryOpts {
times?: number;
interval?: number | ((count?: number) => number);
predicate?: (error?: any) => boolean;
}
export class Disposer<T> {}
} | the_stack |
'use babel'
/*!
* XAtom Debug
* Copyright(c) 2017 Williams Medina <williams.medinaa@gmail.com>
* MIT Licensed
*/
import {
createGroupButtons,
createButton,
createIcon,
createIconFromPath,
createText,
createTextEditor,
createElement,
insertElement,
attachEventFromObject
} from './element'
import { InspectorView } from './InspectorView'
import { EventEmitter } from 'events'
const { CompositeDisposable } = require('atom')
import { parse } from 'path'
export interface CallStackFrame {
name: string,
columnNumber: number,
lineNumber: number,
filePath: string
}
export type CallStackFrames = Array<CallStackFrame>
export interface DebugAreaOptions {
didPause?: Function,
didResume?: Function,
didStepOver?: Function,
didStepInto?: Function,
didStepOut?: Function,
didBreak?: Function,
didOpenFile?: Function,
didRequestProperties?: Function,
didEvaluateExpression?: Function,
didOpenFrame?: Function
}
export class DebugAreaView {
private element: HTMLElement
private callStackContentElement: HTMLElement
private watchExpressionContentElement: HTMLElement
private watchExpressionsContentElement: HTMLElement
private scopeContentElement: HTMLElement
private breakpointContentElement: HTMLElement
private resizeElement: HTMLElement
private pauseButton: HTMLElement
private resumeButton: HTMLElement
private events: EventEmitter
private projectPath: string
private subscriptions:any = new CompositeDisposable()
constructor (options?: DebugAreaOptions) {
this.events = new EventEmitter()
this.pauseButton = createButton({
click: () => {
this.events.emit('didPause')
}
}, [createIcon('pause'), createText('Pause')])
this.resumeButton = createButton({
click: () => {
this.events.emit('didResume')
}
}, [createIcon('resume'), createText('Resume')])
this.togglePause(false)
let watchInputElement: any = createTextEditor({
placeholder: 'Add watch expression',
keyEvents: {
'13': () => createExpression(),
'27': () => resetExpression()
}
})
var resetExpression = () => {
watchInputElement.getModel().setText('')
watchInputElement.style.display = 'none'
}
var createExpression = () => {
let watchExpressionText = watchInputElement.getModel().getText()
if (watchExpressionText.trim().length > 0) {
this.createExpressionLine(watchExpressionText)
}
resetExpression()
}
watchInputElement.addEventListener('blur', createExpression)
resetExpression()
this.watchExpressionsContentElement = createElement('div')
this.element = createElement('xatom-debug-area')
this.watchExpressionContentElement = createElement('xatom-debug-group-content', {
className: 'watch',
elements: [ watchInputElement, this.watchExpressionsContentElement ]
})
this.scopeContentElement = createElement('xatom-debug-group-content', {
className: 'scope'
})
this.callStackContentElement = createElement('xatom-debug-group-content', {
className: 'callstack'
})
this.breakpointContentElement = createElement('xatom-debug-group-content', {
className: 'breakpoint'
})
this.resizeElement = createElement('xatom-debug-resize', {
className: 'resize-left'
})
insertElement(this.element, [
this.resizeElement,
createElement('xatom-debug-controls', {
elements: [
this.pauseButton,
this.resumeButton,
createButton({
tooltip: {
subscriptions: this.subscriptions,
title: 'Step Over'
},
click: () => {
this.events.emit('didStepOver')
}
}, [createIcon('step-over')]),
createButton({
tooltip: {
subscriptions: this.subscriptions,
title: 'Step Into'
},
click: () => {
this.events.emit('didStepInto')
}
}, [createIcon('step-into')]),
createButton({
tooltip: {
subscriptions: this.subscriptions,
title: 'Step Out'
},
click: () => {
this.events.emit('didStepOut')
}
}, [createIcon('step-out')])
]
}),
createElement('xatom-debug-group', {
elements: [
createElement('xatom-debug-group-header', {
elements: [
createText('Watch Expressions'),
createButton({
click: () => {
watchInputElement.style.display = null
watchInputElement.focus()
}
}, createIcon('add')),
createButton({
click: () => {
// refresh
}
}, createIcon('refresh'))
]
}),
this.watchExpressionContentElement
]
}),
createElement('xatom-debug-group', {
elements: [
createElement('xatom-debug-group-header', {
elements: [createText('Variables')]
}),
this.scopeContentElement
]
}),
createElement('xatom-debug-group', {
elements: [
createElement('xatom-debug-group-header', {
elements: [createText('Call Stack')]
}),
this.callStackContentElement
]
}),
createElement('xatom-debug-group', {
elements: [
createElement('xatom-debug-group-header', {
elements: [createText('Breakpoints')]
}),
this.breakpointContentElement
]
})
])
attachEventFromObject(this.events, [
'didPause',
'didResume',
'didStepOver',
'didStepInto',
'didStepOut',
'didBreak',
'didOpenFile',
'didRequestProperties',
'didEvaluateExpression',
'didOpenFrame'
], options)
window.addEventListener('resize', () => this.adjustDebugArea())
setTimeout(() => this.adjustDebugArea(), 0)
this.resizeDebugArea()
}
adjustDebugArea () {
let ignoreElements = ['xatom-debug-controls', 'xatom-debug-group xatom-debug-group-header']
let reduce = ignoreElements.reduce((value, query): number => {
let el = this.element.querySelectorAll(query)
Array.from(el).forEach((child: HTMLElement) => {
value += child.clientHeight
})
return value
}, 6)
let contents = this.element.querySelectorAll('xatom-debug-group xatom-debug-group-content')
let items = Array.from(contents)
let availableHeight = (this.element.clientHeight - reduce) / items.length
items.forEach((el: HTMLElement) => {
el.style.height = `${availableHeight}px`
})
}
resizeDebugArea () {
let initialEvent
let resize = (targetEvent) => {
let offset = initialEvent.screenX - targetEvent.screenX
let width = this.element.clientWidth + offset
if (width > 240 && width < 600) {
this.element.style.width = `${width}px`
}
initialEvent = targetEvent
}
this.resizeElement.addEventListener('mousedown', (e) => {
initialEvent = e
document.addEventListener('mousemove', resize)
document.addEventListener('mouseup', () => {
document.removeEventListener('mouseup', resize)
document.removeEventListener('mousemove', resize)
})
})
}
togglePause (status: boolean) {
this.resumeButton.style.display = status ? null : 'none'
this.pauseButton.style.display = status ? 'none' : null
}
// Debug
createFrameLine (frame: CallStackFrame, indicate: boolean) {
let file = parse(frame.filePath)
let indicator = createIcon(indicate ? 'arrow-right-solid' : '')
if (indicate) {
indicator.classList.add('active')
}
return createElement('xatom-debug-group-item', {
options: {
click: () => {
this.events.emit('didOpenFrame', frame)
this.events.emit('didOpenFile',
frame.filePath,
frame.lineNumber,
frame.columnNumber)
}
},
elements: [
createElement('span', {
elements: [indicator, createText(frame.name || '(anonymous)')]
}),
createElement('span', {
className: 'file-reference',
elements: [
createText(file.base),
createElement('span', {
className: 'file-position',
elements: [ createText(`${frame.lineNumber + 1}${ frame.columnNumber > 0 ? ':' + frame.columnNumber : '' }`) ]
})
]
})
]
})
}
getBreakpointId (filePath: string, lineNumber: number) {
let token = btoa(`${filePath}${lineNumber}`)
return `breakpoint-${token}`
}
setWorkspace (projectPath) {
this.projectPath = projectPath
}
createExpressionLine (expressionText: string) {
let expressionValue = createElement('span')
let expressionResult = createElement('span')
insertElement(expressionValue, createText(expressionText))
// this.watchExpressionsContentElement
insertElement(this.watchExpressionsContentElement, createElement('xatom-debug-group-item', {
options: {
click () {}
},
elements: [
expressionValue,
expressionResult
]
}))
// if is running...
this.events.emit('didEvaluateExpression', expressionText, {
insertFromResult: (result) => {
if (result.type === 'object') {
result = [{
value: result
}]
}
let inspector = new InspectorView({
result,
didRequestProperties: (result, inspectorView) => {
this.events.emit('didRequestProperties', result, inspectorView)
}
})
insertElement(expressionResult, inspector.getElement())
}
})
}
createBreakpointLine (filePath: string, lineNumber: number) {
// let file = parse(filePath)
let shortName = filePath
if (this.projectPath) {
shortName = filePath.replace(this.projectPath, '')
}
insertElement(this.breakpointContentElement, createElement('xatom-debug-group-item', {
id: this.getBreakpointId(filePath, lineNumber),
options: {
click: () => {
this.events.emit('didOpenFile', filePath, lineNumber, 0)
}
},
elements: [
createIcon('break'),
createElement('span', {
// className: 'file-reference',
elements: [
createElement('span', {
className: 'file-position',
elements: [ createText(String(lineNumber + 1)) ]
}),
createText(shortName)
]
})
]
}))
}
removeBreakpointLine (filePath: string, lineNumber: number) {
let id = this.getBreakpointId(filePath, lineNumber)
let element = this.breakpointContentElement.querySelector(`[id='${id}']`)
if (element) {
element.remove()
}
}
clearBreakpoints () {
this.breakpointContentElement.innerHTML = ''
}
insertCallStackFromFrames (frames: CallStackFrames) {
this.clearCallStack()
frames.forEach((frame, index) => {
return insertElement(this.callStackContentElement,
this.createFrameLine(frame, index === 0))
})
}
clearCallStack () {
this.callStackContentElement.innerHTML = ''
}
insertScopeVariables (scope) {
if (scope) {
// render scope variables
this.clearScope()
let inspector = new InspectorView({
result: scope,
didRequestProperties: (result, inspectorView) => {
this.events.emit('didRequestProperties', result, inspectorView)
}
})
insertElement(this.scopeContentElement, inspector.getElement())
// update watch expressions
}
}
clearScope () {
this.scopeContentElement.innerHTML = ''
}
getElement () {
return this.element
}
// Destroy all
destroy () {
this.element.remove()
this.subscriptions.dispose()
window.removeEventListener('resize', () => this.adjustDebugArea())
}
} | the_stack |
import * as _ from 'lodash';
import {Component, ElementRef, EventEmitter, Injector, OnDestroy, OnInit, Output} from '@angular/core';
import {Alert} from '@common/util/alert.util';
import {AbstractComponent} from '@common/component/abstract.component';
import {FilteringOptions, FilteringOptionType} from '@domain/workbook/configurations/filter/filter';
import {DatasourceService} from '../../../datasource/service/datasource.service';
/**
* Edit recommend and essential filter in datasource
*/
@Component({
selector: 'edit-filter-data-source',
templateUrl: './edit-filter-data-source.component.html'
})
export class EditFilterDataSourceComponent extends AbstractComponent implements OnInit, OnDestroy {
// source id
private _sourceId: string;
// origin column list
private _columnList: any[];
// origin recommend filtered column list
private _originFilteringColumnList: any[];
// filtered column list
public filteredColumnList: any[];
// role type filter list
public roleTypeFilterList: any[] = [
{label: this.translateService.instant('msg.comm.ui.list.all'), value: 'ALL'},
{label: this.translateService.instant('msg.comm.name.dim'), value: 'DIMENSION'},
{label: this.translateService.instant('msg.comm.name.mea'), value: 'MEASURE'},
];
// selected role type filter
public selectedRoleTypeFilter: any;
// role type filter show flag
public isShowRoleTypeFilterList: boolean;
// type filter list
public typeFilterList: any[] = [
{label: this.translateService.instant('msg.comm.ui.list.all'), value: 'ALL'},
{label: this.translateService.instant('msg.storage.ui.list.string'), value: 'STRING'},
{label: this.translateService.instant('msg.storage.ui.list.boolean'), value: 'BOOLEAN'},
{label: this.translateService.instant('msg.storage.ui.list.integer'), value: 'INTEGER', measure: true},
{label: this.translateService.instant('msg.storage.ui.list.double'), value: 'DOUBLE', measure: true},
{label: this.translateService.instant('msg.storage.ui.list.date'), value: 'TIMESTAMP'},
{label: this.translateService.instant('msg.storage.ui.list.array'), value: 'ARRAY', measure: true},
{label: this.translateService.instant('msg.storage.ui.list.hashed.map'), value: 'HASHED_MAP', measure: true},
{label: this.translateService.instant('msg.storage.ui.list.lnt'), value: 'LNT'},
{label: this.translateService.instant('msg.storage.ui.list.lng'), value: 'LNG'},
{label: this.translateService.instant('msg.storage.ui.list.geo.point'), value: 'GEO_POINT', derived: true},
{label: this.translateService.instant('msg.storage.ui.list.geo.polygon'), value: 'GEO_POLYGON', derived: true},
{label: this.translateService.instant('msg.storage.ui.list.geo.line'), value: 'GEO_LINE', derived: true},
];
// selected type filter
public selectedTypeFilter: any;
// type filter show flag
public isShowTypeFilterList: boolean;
// filtered column list show flag
public isShowOnlyFilterColumnList: boolean;
// search text keyword
public searchTextKeyword: string;
// component show flag
public isShowComponent: boolean;
// LINKED datasource flag
public isLinkedType: boolean;
@Output()
public updatedSchema: EventEmitter<any> = new EventEmitter();
// constructor
constructor(private _dataSourceService: DatasourceService,
protected element: ElementRef,
protected injector: Injector) {
super(element, injector);
}
/**
* ngOnInit
*/
public ngOnInit() {
super.ngOnInit();
}
/**
* ngOnDestroy
*/
public ngOnDestroy() {
super.ngOnDestroy();
}
/**
* init
* @param {string} sourceId
* @param columnList
* @param {boolean} isLinkedType
*/
public init(sourceId: string, columnList: any, isLinkedType: boolean): void {
// ui init
this._initView();
// source id
this._sourceId = sourceId;
// Copy only a list of columns, not a MEASURE
// TODO 만약 TIMESTAMP로 지정된 컬럼도 filteringOptions 설정이 가능하도록 변경해달라고 하면 주석 해제할 것
// this._columnList = _.cloneDeep(_.filter(columnList, column => column.role !== 'MEASURE'));
this._columnList = _.cloneDeep(_.filter(columnList, column => column.role === 'DIMENSION'));
// set origin recommend filtered column list
this._originFilteringColumnList = _.cloneDeep(_.filter(this._columnList, column => column.filtering));
// is LINKED type source
this.isLinkedType = isLinkedType;
// update filtered column list
this._updateFilteredColumnList();
}
/**
* Search keyword
* @param {string} text
*/
public searchText(text: string): void {
this.searchTextKeyword = text;
// update filtered column list
this._updateFilteredColumnList();
}
/**
* Is enabled filtering in column
* @param column
* @returns {boolean}
*/
public isEnableColumnFiltering(column: any): boolean {
return column.filtering;
}
/**
* Is enabled filteringOption in column
* @param column
* @returns {boolean}
*/
public isEnableColumnFilteringOptions(column: any): boolean {
return column.filteringOptions;
}
/**
* Get column type label
* @param {string} type
* @param typeList
* @returns {string}
*/
public getColumnTypeLabel(type: string, typeList: any): string {
return typeList[_.findIndex(typeList, item => item['value'] === type)].label;
}
/**
* Update column list
*/
public updateColumnList(): void {
// loading show
this.loadingShow();
// update column list
this._dataSourceService.updateDatasourceFields(this._sourceId, this._getUpdateFieldParams())
.then(() => {
// alert
Alert.success(this.translateService.instant('msg.comm.alert.save.success'));
// loading hide
this.loadingHide();
// change emit
this.updatedSchema.emit();
// close
this.onClickCancel();
})
.catch(error => this.commonExceptionHandler(error));
}
/**
* Click cancel button
*/
public onClickCancel(): void {
this.isShowComponent = false;
}
/**
* Change role type filter
* @param type
*/
public onChangeRoleTypeFilter(type: any): void {
if (this.selectedRoleTypeFilter !== type) {
// change role type filter
this.selectedRoleTypeFilter = type;
// update filtered column list
this._updateFilteredColumnList();
}
}
/**
* Change type filter
* @param type
*/
public onChangeTypeFilter(type: any): void {
if (this.selectedTypeFilter !== type) {
// 타입 필털이 변경
this.selectedTypeFilter = type;
// update filtered column list
this._updateFilteredColumnList();
}
}
/**
* Change filtered list show flag
*/
public onChangeShowFilter(): void {
this.isShowOnlyFilterColumnList = !this.isShowOnlyFilterColumnList;
// update filtered column list
this._updateFilteredColumnList();
}
/**
* Change filtering in column
* @param column
*/
public onClickSetColumnFiltering(column: any): void {
// TODO 만약 TIMESTAMP로 지정된 컬럼도 filteringOptions 설정이 가능하도록 변경해달라고 하면 주석 해제할 것
// if (column.role !== 'TIMESTAMP') {
// if enabled filtering in column
if (this.isEnableColumnFiltering(column)) {
const seq = column.filteringSeq;
// delete filtering
delete column.filtering;
delete column.filteringSeq;
delete column.filteringOptions;
// resort filtering in filtered column list
this._resortFilteringColumnList(seq);
// if enable filtered list show flag, update filtered column list
this.isShowOnlyFilterColumnList && this._updateFilteredColumnList();
} else {
// set filtering
column.filtering = true;
// set seq
column.filteringSeq = _.filter(this._columnList, item => item.filtering).length - 1;
}
// }
}
/**
* Change filteringOption in column
* @param column
*/
public onClickSetColumnFilteringOptions(column: any): void {
// Only works if filtering is enabled on the column
if (this.isEnableColumnFiltering(column)) {
// If filteringOptions is set on a column
if (this.isEnableColumnFilteringOptions(column)) {
delete column.filteringOptions;
} else {
// If not, set new options
column.filteringOptions = new FilteringOptions();
column.filteringOptions.type = column.logicalType === 'TIMESTAMP' ? FilteringOptionType.TIME : FilteringOptionType.INCLUSION;
column.filteringOptions.defaultSelector = column.logicalType === 'TIMESTAMP' ? 'RANGE' : 'SINGLE_LIST';
column.filteringOptions.allowSelectors = column.logicalType === 'TIMESTAMP' ? ['RANGE'] : ['SINGLE_LIST']
}
}
}
/**
* ui init
* @private
*/
private _initView(): void {
// filter
this.selectedTypeFilter = this.typeFilterList[0];
this.selectedRoleTypeFilter = this.roleTypeFilterList[0];
// search
this.searchTextKeyword = '';
// only filtered list flag
this.isShowOnlyFilterColumnList = false;
// show flag
this.isShowComponent = true;
}
/**
* Update filtered column list
* @private
*/
private _updateFilteredColumnList(): void {
let resultList: any = this._columnList;
// role
if (this.selectedRoleTypeFilter.value !== 'ALL') {
resultList = _.filter(resultList, column => 'DIMENSION' === this.selectedRoleTypeFilter.value && 'TIMESTAMP' === column.role ? column : this.selectedRoleTypeFilter.value === column.role);
}
// type
if (this.selectedTypeFilter.value !== 'ALL') {
resultList = _.filter(resultList, column => this.selectedTypeFilter.value === column.logicalType);
}
// search
if (this.searchTextKeyword !== '') {
resultList = _.filter(resultList, column => column.name.toUpperCase().includes(this.searchTextKeyword.toUpperCase().trim()));
}
// only filtered list show
if (this.isShowOnlyFilterColumnList) {
resultList = _.filter(resultList, column => column.filtering);
}
this.filteredColumnList = resultList;
}
/**
* Resort filtered column list
* @param {number} seq
* @private
*/
private _resortFilteringColumnList(seq: number): void {
_.forEach(_.filter(this._columnList, column => column.filtering && column.filteringSeq > seq), (column) => {
column.filteringSeq--;
});
}
/**
* Get parameter for update column list
* @returns {any}
* @private
*/
private _getUpdateFieldParams(): any {
const result = [];
const filteringList = _.filter(this._columnList, column => column.filtering);
// add
_.forEach(filteringList, (column) => {
// get column exist in origin filtered column list
const temp = _.find(this._originFilteringColumnList, originColumn => originColumn.id === column['id']);
// If is not exist in the origin filtered list
// If different seq
// If different filteringOptions
if (!temp
|| temp.filteringSeq !== column['filteringSeq']
|| ((temp.filteringOptions && !column['filteringOptions']) || (!temp.filteringOptions && column['filteringOptions']))) {
column['op'] = 'replace';
result.push(column);
}
});
// remove
_.forEach(this._originFilteringColumnList, (originColumn) => {
// If is not exist in the filtered list, add
if (_.every(filteringList, column => column['id'] !== originColumn.id)) {
originColumn['op'] = 'replace';
originColumn['filtering'] = false;
result.push(originColumn);
}
});
return result;
}
} | the_stack |
import { parse } from 'tekko/dist/parse'
import camelcaseKeys from 'camelcase-keys'
import gt from 'lodash/gt'
import isEmpty from 'lodash/isEmpty'
import isFinite from 'lodash/isFinite'
import toLower from 'lodash/toLower'
import toNumber from 'lodash/toNumber'
import toUpper from 'lodash/toUpper'
import {
BaseMessage,
ChatEvents,
ClearChatMessages,
ClearMessageMessage,
Commands,
Events,
GiftPaidUpgradeParameters,
GlobalUserStateMessage,
HostTargetMessage,
JoinMessage,
KnownNoticeMessageIds,
KnownUserNoticeMessageIds,
ModeMessages,
NamesEndMessage,
NamesMessage,
NoticeEvents,
NoticeMessage,
NoticeMessages,
NoticeTags,
PartMessage,
PrivateMessages,
RaidParameters,
ResubscriptionParameters,
RitualParameters,
RoomStateMessage,
SubscriptionGiftCommunityParameters,
SubscriptionGiftParameters,
SubscriptionParameters,
UserNoticeMessages,
UserNoticeTags,
UserStateMessage,
} from '../../../twitch'
import * as constants from '../../constants'
import * as utils from '../'
import * as helpers from './helpers'
import * as tagParsers from './tags'
export const base = (rawMessages: string, username = ''): BaseMessage[] => {
const rawMessagesV = rawMessages.split(/\r?\n/g)
return rawMessagesV.reduce((messages, rawMessage) => {
if (!rawMessage.length) {
return messages
}
const {
command,
tags = {},
prefix: { name, user, host } = {
name: undefined,
user: undefined,
host: undefined,
},
params: [channel, message],
} = parse(rawMessage)
const timestamp = String(tags['tmi-sent-ts']) || Date.now().toString()
const messageTags = isEmpty(tags)
? {}
: (camelcaseKeys(tags) as { [key: string]: string })
const messageUsername = helpers.username(
host,
name,
user,
messageTags.login,
messageTags.username,
messageTags.displayName,
)
const baseMessage = {
_raw: rawMessage,
timestamp: helpers.generalTimestamp(timestamp),
command: command as Commands,
event: command as Events,
channel: channel !== '*' ? channel : '',
username: messageUsername,
isSelf:
typeof messageUsername === 'string' &&
toLower(username) === messageUsername,
tags: messageTags,
message,
}
return [...messages, baseMessage]
}, [] as BaseMessage[])
}
/**
* Join a channel.
* @see https://dev.twitch.tv/docs/irc/membership/#join-twitch-membership
*/
export const joinMessage = (baseMessage: BaseMessage): JoinMessage => {
const [
,
username,
,
,
channel,
] = /:(.+)!(.+)@(.+).tmi.twitch.tv JOIN (#.+)/g.exec(baseMessage._raw)
return {
...baseMessage,
channel,
command: Commands.JOIN,
event: Commands.JOIN,
username,
}
}
/**
* Join or depart from a channel.
* @see https://dev.twitch.tv/docs/irc/membership/#join-twitch-membership
* @see https://dev.twitch.tv/docs/irc/membership/#part-twitch-membership
*/
export const partMessage = (baseMessage: BaseMessage): PartMessage => {
const [
,
username,
,
,
channel,
] = /:(.+)!(.+)@(.+).tmi.twitch.tv PART (#.+)/g.exec(baseMessage._raw)
return {
...baseMessage,
channel,
command: Commands.PART,
event: Commands.PART,
username,
}
}
/**
* Gain/lose moderator (operator) status in a channel.
* @see https://dev.twitch.tv/docs/irc/membership/#mode-twitch-membership
*/
export const modeMessage = (baseMessage: BaseMessage): ModeMessages => {
const [
,
channel,
mode,
username,
] = /:[^\s]+ MODE (#[^\s]+) (-|\+)o ([^\s]+)/g.exec(baseMessage._raw)
const isModerator = mode === '+'
const baseModeMessage = {
...baseMessage,
command: Commands.MODE as Commands.MODE,
channel,
username,
}
return isModerator
? {
...baseModeMessage,
event: ChatEvents.MOD_GAINED,
message: `+o`,
isModerator: true,
}
: {
...baseModeMessage,
event: ChatEvents.MOD_LOST,
message: '-o',
isModerator: false,
}
}
/**
* List current chatters in a channel.
* @see https://dev.twitch.tv/docs/irc/membership/#names-twitch-membership
*/
export const namesMessage = (baseMessage: BaseMessage): NamesMessage => {
const [
,
,
,
channel,
names,
] = /:(.+).tmi.twitch.tv 353 (.+) = (#.+) :(.+)/g.exec(baseMessage._raw)
const namesV = names.split(' ')
return {
...baseMessage,
channel,
command: Commands.NAMES,
event: Commands.NAMES,
usernames: namesV,
}
}
/**
* End of list current chatters in a channel.
* @see https://dev.twitch.tv/docs/irc/membership/#names-twitch-membership
*/
export const namesEndMessage = (baseMessage: BaseMessage): NamesEndMessage => {
const [
,
username,
,
channel,
// message,
] = /:(.+).tmi.twitch.tv 366 (.+) (#.+) :(.+)/g.exec(baseMessage._raw)
return {
...baseMessage,
channel,
command: Commands.NAMES_END,
event: Commands.NAMES_END,
username,
}
}
/**
* GLOBALUSERSTATE message
*/
export const globalUserStateMessage = (
baseMessage: BaseMessage,
): GlobalUserStateMessage => {
const { tags, ...other } = baseMessage
return {
...other,
command: Commands.GLOBALUSERSTATE,
event: Commands.GLOBALUSERSTATE,
tags: tagParsers.globalUserState(tags),
}
}
/**
* Temporary or permanent ban on a channel.
* @see https://dev.twitch.tv/docs/irc/commands/#clearchat-twitch-commands
*
* All chat is cleared (deleted).
* @see https://dev.twitch.tv/docs/irc/tags/#clearchat-twitch-tags
*/
export const clearChatMessage = (
baseMessage: BaseMessage,
): ClearChatMessages => {
const { tags, message: username, ...other } = baseMessage
if (typeof username !== 'undefined') {
return {
...other,
tags: {
...tags,
banReason: helpers.generalString(tags.banReason),
banDuration: helpers.generalNumber(tags.banDuration),
},
command: Commands.CLEAR_CHAT,
event: ChatEvents.USER_BANNED,
username,
}
}
return {
...other,
command: Commands.CLEAR_CHAT,
event: Commands.CLEAR_CHAT,
}
}
/**
* Single message removal on a channel.
* @see https://dev.twitch.tv/docs/irc/commands#clearmsg-twitch-commands
*/
export const clearMessageMessage = (
baseMessage: BaseMessage,
): ClearMessageMessage => {
const { tags } = baseMessage
return {
...baseMessage,
tags: {
login: tags.login,
targetMsgId: tags.targetMsgId,
},
command: Commands.CLEAR_MESSAGE,
event: Commands.CLEAR_MESSAGE,
targetMessageId: tags.targetMsgId,
}
}
/**
* Host starts or stops a message.
* @see https://dev.twitch.tv/docs/irc/commands/#hosttarget-twitch-commands
*/
export const hostTargetMessage = (
baseMessage: BaseMessage,
): HostTargetMessage => {
const [
,
channel,
username,
numberOfViewers,
] = /:tmi.twitch.tv HOSTTARGET (#[^\s]+) :([^\s]+)?\s?(\d+)?/g.exec(
baseMessage._raw,
)
const isStopped = username === '-'
return {
...baseMessage,
channel,
username,
command: Commands.HOST_TARGET,
event: isStopped ? ChatEvents.HOST_OFF : ChatEvents.HOST_ON,
numberOfViewers: isFinite(toNumber(numberOfViewers))
? parseInt(numberOfViewers, 10)
: undefined,
}
}
/**
* When a user joins a channel or a room setting is changed.
*/
export const roomStateMessage = (
baseMessage: BaseMessage,
): RoomStateMessage => {
const { tags, ...other } = baseMessage
return {
...other,
command: Commands.ROOM_STATE,
event: Commands.ROOM_STATE,
tags: tagParsers.roomState(tags),
}
}
/**
* NOTICE/ROOM_MODS message
* @see https://dev.twitch.tv/docs/irc/commands/#msg-id-tags-for-the-notice-commands-capability
*/
export const noticeMessage = (baseMessage: BaseMessage): NoticeMessages => {
const { tags: baseTags, ...other } = baseMessage
const tags = (utils.isAuthenticationFailedMessage(baseMessage)
? { ...baseTags, msgId: toLower(Events.AUTHENTICATION_FAILED) }
: baseTags) as NoticeTags
const event = toUpper(tags.msgId) as NoticeEvents
switch (tags.msgId) {
case KnownNoticeMessageIds.ROOM_MODS:
return {
...other,
command: Commands.NOTICE,
event: NoticeEvents.ROOM_MODS,
tags,
mods: helpers.mods(other.message),
}
default:
return {
...other,
command: Commands.NOTICE,
event,
tags,
} as NoticeMessage
}
}
/**
* USERSTATE message
* When a user joins a channel or sends a PRIVMSG to a channel.
*/
export const userStateMessage = (
baseMessage: BaseMessage,
): UserStateMessage => {
const { tags, ...other } = baseMessage
return {
...other,
command: Commands.USER_STATE,
event: Commands.USER_STATE,
tags: tagParsers.userState(tags),
}
}
/**
* PRIVMSG message
* When a user joins a channel or sends a PRIVMSG to a channel.
* When a user cheers a channel.
* When a user hosts your channel while connected as broadcaster.
*/
export const privateMessage = (baseMessage: BaseMessage): PrivateMessages => {
const { _raw, tags } = baseMessage
if (gt(tags.bits, 0)) {
return {
...userStateMessage(baseMessage),
command: Commands.PRIVATE_MESSAGE,
event: ChatEvents.CHEER,
bits: parseInt(tags.bits, 10),
}
}
const [
isHostingPrivateMessage,
channel,
displayName,
isAuto,
numberOfViewers,
] = constants.PRIVATE_MESSAGE_HOSTED_RE.exec(_raw) || []
if (isHostingPrivateMessage) {
if (isAuto) {
return {
...baseMessage,
command: Commands.PRIVATE_MESSAGE,
event: ChatEvents.HOSTED_AUTO,
channel: `#${channel}`,
tags: { displayName },
numberOfViewers: helpers.generalNumber(numberOfViewers),
}
}
if (numberOfViewers) {
return {
...baseMessage,
command: Commands.PRIVATE_MESSAGE,
event: ChatEvents.HOSTED_WITH_VIEWERS,
channel: `#${channel}`,
tags: { displayName },
numberOfViewers: helpers.generalNumber(numberOfViewers),
}
}
return {
...baseMessage,
command: Commands.PRIVATE_MESSAGE,
event: ChatEvents.HOSTED_WITHOUT_VIEWERS,
channel: `#${channel}`,
tags: { displayName },
}
}
return {
...userStateMessage(baseMessage),
command: Commands.PRIVATE_MESSAGE,
event: Commands.PRIVATE_MESSAGE,
}
}
/**
* USERNOTICE message
*/
export const userNoticeMessage = (
baseMessage: BaseMessage,
): UserNoticeMessages => {
const command = Commands.USER_NOTICE
const tags = {
...tagParsers.userNotice(baseMessage.tags),
systemMsg: helpers.generalString(baseMessage.tags.systemMsg),
} as UserNoticeTags
const systemMessage = helpers.generalString(baseMessage.tags.systemMsg) || ''
const parameters = tagParsers.userNoticeMessageParameters(tags)
switch (tags.msgId) {
/**
* On anonymous gifted subscription paid upgrade to a channel.
*/
case KnownUserNoticeMessageIds.ANON_GIFT_PAID_UPGRADE:
return {
...baseMessage,
command,
event: ChatEvents.ANON_GIFT_PAID_UPGRADE,
parameters,
tags,
systemMessage,
}
/**
* On gifted subscription paid upgrade to a channel.
*/
case KnownUserNoticeMessageIds.GIFT_PAID_UPGRADE:
return {
...baseMessage,
command,
event: ChatEvents.GIFT_PAID_UPGRADE,
parameters: parameters as GiftPaidUpgradeParameters,
tags,
systemMessage,
}
/**
* On channel raid.
*/
case KnownUserNoticeMessageIds.RAID:
return {
...baseMessage,
command,
event: ChatEvents.RAID,
parameters: parameters as RaidParameters,
tags,
systemMessage,
}
/**
* On resubscription (subsequent months) to a channel.
*/
case KnownUserNoticeMessageIds.RESUBSCRIPTION:
return {
...baseMessage,
command,
event: ChatEvents.RESUBSCRIPTION,
parameters: parameters as ResubscriptionParameters,
tags,
systemMessage,
}
/**
* On channel ritual.
*/
case KnownUserNoticeMessageIds.RITUAL:
return {
...baseMessage,
command,
event: ChatEvents.RITUAL,
parameters: parameters as RitualParameters,
tags,
systemMessage,
}
/**
* On subscription gift to a channel community.
*/
case KnownUserNoticeMessageIds.SUBSCRIPTION_GIFT_COMMUNITY:
return {
...baseMessage,
command,
event: ChatEvents.SUBSCRIPTION_GIFT_COMMUNITY,
parameters: parameters as SubscriptionGiftCommunityParameters,
tags,
systemMessage,
}
/**
* On subscription gift to a channel.
*/
case KnownUserNoticeMessageIds.SUBSCRIPTION_GIFT:
return {
...baseMessage,
command,
event: ChatEvents.SUBSCRIPTION_GIFT,
parameters: parameters as SubscriptionGiftParameters,
tags,
systemMessage,
}
/**
* On subscription (first month) to a channel.
*/
case KnownUserNoticeMessageIds.SUBSCRIPTION:
return {
...baseMessage,
command,
event: ChatEvents.SUBSCRIPTION,
parameters: parameters as SubscriptionParameters,
tags,
systemMessage,
}
/**
* Unknown USERNOTICE event.
*/
default:
return {
...baseMessage,
command,
event: toUpper(tags.msgId),
tags,
parameters,
systemMessage,
} as UserNoticeMessages
}
}
export default base | the_stack |
import * as React from 'react';
import { IPropertyFieldGroupPickerPropsInternal } from './PropertyFieldGroupPicker';
import { IWebPartContext } from '@microsoft/sp-webpart-base';
import { SPHttpClient, ISPHttpClientOptions, SPHttpClientResponse } from "@microsoft/sp-http";
import { EnvironmentType, Environment } from '@microsoft/sp-core-library';
import { IPropertyFieldGroup, IGroupType } from './PropertyFieldGroupPicker';
import { NormalPeoplePicker, IBasePickerSuggestionsProps } from 'office-ui-fabric-react/lib/Pickers';
import { Label } from 'office-ui-fabric-react/lib/Label';
import { IPersonaProps, PersonaPresence, PersonaInitialsColor } from 'office-ui-fabric-react/lib/Persona';
import { Async } from 'office-ui-fabric-react/lib/Utilities';
import * as strings from 'sp-client-custom-fields/strings';
/**
* @interface
* PropertyFieldGroupPickerHost properties interface
*
*/
export interface IPropertyFieldGroupPickerHostProps extends IPropertyFieldGroupPickerPropsInternal {
}
/**
* @interface
* Defines the state of the component
*
*/
export interface IPeoplePickerState {
resultsPeople?: Array<IPropertyFieldGroup>;
resultsPersonas?: Array<IPersonaProps>;
errorMessage?: string;
}
/**
* @class
* Renders the controls for PropertyFieldGroupPicker component
*/
export default class PropertyFieldGroupPickerHost extends React.Component<IPropertyFieldGroupPickerHostProps, IPeoplePickerState> {
private searchService: PropertyFieldSearchService;
private intialPersonas: Array<IPersonaProps> = new Array<IPersonaProps>();
private resultsPeople: Array<IPropertyFieldGroup> = new Array<IPropertyFieldGroup>();
private resultsPersonas: Array<IPersonaProps> = new Array<IPersonaProps>();
private selectedPeople: Array<IPropertyFieldGroup> = new Array<IPropertyFieldGroup>();
private selectedPersonas: Array<IPersonaProps> = new Array<IPersonaProps>();
private async: Async;
private delayedValidate: (value: IPropertyFieldGroup[]) => void;
/**
* @function
* Constructor
*/
constructor(props: IPropertyFieldGroupPickerHostProps) {
super(props);
this.searchService = new PropertyFieldSearchService(props.context);
this.onSearchFieldChanged = this.onSearchFieldChanged.bind(this);
this.onItemChanged = this.onItemChanged.bind(this);
this.createInitialPersonas();
this.state = {
resultsPeople: this.resultsPeople,
resultsPersonas: this.resultsPersonas,
errorMessage: ''
};
this.async = new Async(this);
this.validate = this.validate.bind(this);
this.notifyAfterValidate = this.notifyAfterValidate.bind(this);
this.delayedValidate = this.async.debounce(this.validate, this.props.deferredValidationTime);
}
/**
* @function
* Renders the PeoplePicker controls with Office UI Fabric
*/
public render(): JSX.Element {
var suggestionProps: IBasePickerSuggestionsProps = {
suggestionsHeaderText: strings.PeoplePickerSuggestedContacts,
noResultsFoundText: strings.PeoplePickerNoResults,
loadingText: strings.PeoplePickerLoading,
};
//Renders content
return (
<div>
<Label>{this.props.label}</Label>
<NormalPeoplePicker
pickerSuggestionsProps={suggestionProps}
onResolveSuggestions={this.onSearchFieldChanged}
onChange={this.onItemChanged}
defaultSelectedItems={this.intialPersonas}
/>
{ this.state.errorMessage != null && this.state.errorMessage != '' && this.state.errorMessage != undefined ?
<div style={{paddingBottom: '8px'}}><div aria-live='assertive' className='ms-u-screenReaderOnly' data-automation-id='error-message'>{ this.state.errorMessage }</div>
<span>
<p className='ms-TextField-errorMessage ms-u-slideDownIn20'>{ this.state.errorMessage }</p>
</span>
</div>
: ''}
</div>
);
}
/**
* @function
* A search field change occured
*/
private onSearchFieldChanged(searchText: string, currentSelected: IPersonaProps[]): Promise<IPersonaProps> | IPersonaProps[] {
if (searchText.length > 2) {
//Clear the suggestions list
this.setState({ resultsPeople: this.resultsPeople, resultsPersonas: this.resultsPersonas });
//Request the search service
var result = this.searchService.searchGroups(searchText, this.props.groupType).then((response: IPropertyFieldGroup[]) => {
this.resultsPeople = [];
this.resultsPersonas = [];
//If allowDuplicate == false, so remove duplicates from results
if (this.props.allowDuplicate === false)
response = this.removeDuplicates(response);
response.map((element: IPropertyFieldGroup, index: number) => {
//Fill the results Array
this.resultsPeople.push(element);
//Transform the response in IPersonaProps object
this.resultsPersonas.push(this.getPersonaFromGroup(element, index));
});
//Refresh the component's state
this.setState({ resultsPeople: this.resultsPeople, resultsPersonas: this.resultsPersonas });
return this.resultsPersonas;
});
return result;
}
else {
return [];
}
}
/**
* @function
* Remove the duplicates if property allowDuplicate equals false
*/
private removeDuplicates(responsePeople: IPropertyFieldGroup[]): IPropertyFieldGroup[] {
if (this.selectedPeople == null || this.selectedPeople.length == 0)
return responsePeople;
var res: IPropertyFieldGroup[] = [];
responsePeople.map((element: IPropertyFieldGroup) => {
var found: boolean = false;
for (var i: number = 0; i < this.selectedPeople.length; i++) {
var responseItem: IPropertyFieldGroup = this.selectedPeople[i];
if (responseItem.id == element.id) {
found = true;
break;
}
}
if (found === false)
res.push(element);
});
return res;
}
/**
* @function
* Creates the collection of initial personas from initial IPropertyFieldGroup collection
*/
private createInitialPersonas(): void {
if (this.props.initialData == null || typeof (this.props.initialData) != typeof Array<IPropertyFieldGroup>())
return;
this.props.initialData.map((element: IPropertyFieldGroup, index: number) => {
var persona: IPersonaProps = this.getPersonaFromGroup(element, index);
this.intialPersonas.push(persona);
this.selectedPersonas.push(persona);
this.selectedPeople.push(element);
});
}
/**
* @function
* Generates a IPersonaProps object from a IPropertyFieldGroup object
*/
private getPersonaFromGroup(element: IPropertyFieldGroup, index: number): IPersonaProps {
return {
primaryText: element.fullName, secondaryText: element.description
};
}
/**
* @function
* Refreshes the web part properties
*/
private refreshWebPartProperties(): void {
this.delayedValidate(this.selectedPeople);
}
/**
* @function
* Validates the new custom field value
*/
private validate(value: IPropertyFieldGroup[]): void {
if (this.props.onGetErrorMessage === null || this.props.onGetErrorMessage === undefined) {
this.notifyAfterValidate(this.props.initialData, value);
return;
}
var result: string | PromiseLike<string> = this.props.onGetErrorMessage(value || []);
if (result !== undefined) {
if (typeof result === 'string') {
if (result === undefined || result === '')
this.notifyAfterValidate(this.props.initialData, value);
this.state.errorMessage = result;
this.setState(this.state);
}
else {
result.then((errorMessage: string) => {
if (errorMessage === undefined || errorMessage === '')
this.notifyAfterValidate(this.props.initialData, value);
this.state.errorMessage = errorMessage;
this.setState(this.state);
});
}
}
else {
this.notifyAfterValidate(this.props.initialData, value);
}
}
/**
* @function
* Notifies the parent Web Part of a property value change
*/
private notifyAfterValidate(oldValue: IPropertyFieldGroup[], newValue: IPropertyFieldGroup[]) {
if (this.props.onPropertyChange && newValue != null) {
this.props.properties[this.props.targetProperty] = newValue;
this.props.onPropertyChange(this.props.targetProperty, oldValue, newValue);
if (!this.props.disableReactivePropertyChanges && this.props.render != null)
this.props.render();
}
}
/**
* @function
* Called when the component will unmount
*/
public componentWillUnmount() {
this.async.dispose();
}
/**
* @function
* Event raises when the user changed people from hte PeoplePicker component
*/
private onItemChanged(selectedItems: IPersonaProps[]): void {
if (selectedItems.length > 0) {
if (selectedItems.length > this.selectedPersonas.length) {
var index: number = this.resultsPersonas.indexOf(selectedItems[selectedItems.length - 1]);
if (index > -1) {
var people: IPropertyFieldGroup = this.resultsPeople[index];
this.selectedPeople.push(people);
this.selectedPersonas.push(this.resultsPersonas[index]);
this.refreshWebPartProperties();
}
} else {
this.selectedPersonas.map((person, index2) => {
var selectedItemIndex: number = selectedItems.indexOf(person);
if (selectedItemIndex === -1) {
this.selectedPersonas.splice(index2, 1);
this.selectedPeople.splice(index2, 1);
}
});
}
} else {
this.selectedPersonas.splice(0, this.selectedPersonas.length);
this.selectedPeople.splice(0, this.selectedPeople.length);
}
this.refreshWebPartProperties();
}
}
/**
* @interface
* Service interface definition
*/
interface IPropertyFieldSearchService {
/**
* @function
* Search Groups from a query
*/
searchGroups(query: string, type: IGroupType): Promise<Array<IPropertyFieldGroup>>;
}
/**
* @class
* Service implementation to search people in SharePoint
*/
class PropertyFieldSearchService implements IPropertyFieldSearchService {
private context: IWebPartContext;
/**
* @function
* Service constructor
*/
constructor(pageContext: IWebPartContext) {
this.context = pageContext;
}
/**
* @function
* Search groups from the SharePoint database
*/
public searchGroups(query: string, type: IGroupType): Promise<Array<IPropertyFieldGroup>> {
if (Environment.type === EnvironmentType.Local) {
//If the running environment is local, load the data from the mock
return this.searchGroupsFromMock(query);
}
else {
//If the running env is SharePoint, loads from the peoplepicker web service
var contextInfoUrl: string = this.context.pageContext.web.absoluteUrl + "/_api/contextinfo";
var userRequestUrl: string = this.context.pageContext.web.absoluteUrl + "/_api/SP.UI.ApplicationPages.ClientPeoplePickerWebServiceInterface.clientPeoplePickerSearchUser";
var httpPostOptions: ISPHttpClientOptions = {
headers: {
"accept": "application/json",
"content-type": "application/json"
}
};
return this.context.spHttpClient.post(contextInfoUrl, SPHttpClient.configurations.v1, httpPostOptions).then((response: SPHttpClientResponse) => {
return response.json().then((jsonResponse: any) => {
var formDigestValue: string = jsonResponse.FormDigestValue;
var data = {
'queryParams': {
//'__metadata': {
// 'type': 'SP.UI.ApplicationPages.ClientPeoplePickerQueryParameters'
//},
'AllowEmailAddresses': true,
'AllowMultipleEntities': false,
'AllUrlZones': false,
'MaximumEntitySuggestions': 20,
'PrincipalSource': 15,
//PrincipalType controls the type of entities that are returned in the results.
//Choices are All - 15, Distribution List - 2 , Security Groups - 4,
//SharePoint Groups – 8, User – 1. These values can be combined
'PrincipalType': type === IGroupType.SharePoint ? 8 : 4,
'QueryString': query
//'Required':false,
//'SharePointGroupID':null,
//'UrlZone':null,
//'UrlZoneSpecified':false,
}
};
httpPostOptions = {
headers: {
'accept': 'application/json',
'content-type': 'application/json',
"X-RequestDigest": formDigestValue
},
body: JSON.stringify(data)
};
return this.context.spHttpClient.post(userRequestUrl, SPHttpClient.configurations.v1, httpPostOptions).then((searchResponse: SPHttpClientResponse) => {
return searchResponse.json().then((usersResponse: any) => {
var res: IPropertyFieldGroup[] = [];
var values: any = JSON.parse(usersResponse.value);
values.map(element => {
var persona: IPropertyFieldGroup = {
fullName: element.DisplayText,
login: type === IGroupType.SharePoint ? element.EntityData.AccountName : element.ProviderName,
id : type === IGroupType.SharePoint ? element.EntityData.SPGroupID : element.Key,
description: element.Description
};
res.push(persona);
});
return res;
});
});
});
});
}
}
/**
* @function
* Returns fake people results for the Mock mode
*/
private searchGroupsFromMock(query: string): Promise<Array<IPropertyFieldGroup>> {
return PeoplePickerMockHttpClient.searchGroups(this.context.pageContext.web.absoluteUrl).then(() => {
const results: IPropertyFieldGroup[] = [
{ id: '1', fullName: "Members", login: "Members", description: 'Members' },
{ id: '2', fullName: "Viewers", login: "Viewers", description: 'Viewers' },
{ id: '3', fullName: "Excel Services Viewers", login: "Excel Services Viewers", description: 'Excel Services Viewers' }
];
return results;
}) as Promise<Array<IPropertyFieldGroup>>;
}
}
/**
* @class
* Defines a http client to request mock data to use the web part with the local workbench
*/
class PeoplePickerMockHttpClient {
/**
* @var
* Mock SharePoint result sample
*/
private static _results: IPropertyFieldGroup[] = [];
/**
* @function
* Mock search People method
*/
public static searchGroups(restUrl: string, options?: any): Promise<IPropertyFieldGroup[]> {
return new Promise<IPropertyFieldGroup[]>((resolve) => {
resolve(PeoplePickerMockHttpClient._results);
});
}
} | the_stack |
import * as freedomMocker from '../freedom/mocks/mock-freedom-in-module-env';
declare var freedom: freedom.FreedomInModuleEnv;
freedom = freedomMocker.makeMockFreedomInModuleEnv();
import * as arraybuffers from '../arraybuffers/arraybuffers';
import * as peerconnection from '../webrtc/peerconnection';
import * as signals from '../webrtc/signals';
import * as handler from '../handler/queue';
import * as socks_to_rtc from './socks-to-rtc';
import * as net from '../net/net.types';
import * as tcp from '../net/tcp';
import * as socks_headers from '../socks/headers';
import * as logging from '../logging/logging';
var log: logging.Log = new logging.Log('socks-to-rtc spec');
var mockEndpoint :net.Endpoint = {
address: '127.0.0.1',
port: 1234
};
var mockRemoteEndpoint :net.Endpoint = {
// This address and port are both reserved for testing.
address: '192.0.2.111',
port: 1023
};
var mockConnectionInfo :tcp.ConnectionInfo = {
bound: mockEndpoint,
remote: mockRemoteEndpoint
};
var voidPromise = Promise.resolve();
// Neither fulfills nor rejects.
// Useful in a bunch of tests where a promise must be returned
// for chaining purposes.
var noopPromise = new Promise<void>((F, R) => {});
describe('SOCKS server', function() {
var server :socks_to_rtc.SocksToRtc;
var onceServerStopped :() => Promise<void>;
var mockTcpServer :tcp.Server;
var mockPeerConnection :peerconnection.PeerConnection<signals.Message>;
beforeEach(function() {
server = new socks_to_rtc.SocksToRtc();
onceServerStopped = () => { return server.onceStopped; };
// TODO: create named more fleshed out TcpServer and PeerConnection mock
// classes for testing. e.g. failing to listen mock, listen & gets
// connection, listen and connection drops, etc.
mockTcpServer = jasmine.createSpyObj('tcp server', [
'on',
'onceListening',
'shutdown',
'onceShutdown',
'isShutdown'
]);
// TODO: make a real mock of listen; this one is frgaile to implementation
// changes and tests that might call onceListening before listen.
mockTcpServer.listen = () => { return mockTcpServer.onceListening(); }
mockTcpServer.connectionsQueue = new handler.Queue<tcp.Connection, void>();
mockPeerConnection = <any>{
dataChannels: {},
peerOpenedChannelQueue: new handler.Queue<signals.Message, void>(),
signalForPeerQueue: new handler.Queue<signals.Message, void>(),
negotiateConnection: jasmine.createSpy('negotiateConnection'),
onceConnected: noopPromise,
onceClosed: noopPromise,
close: jasmine.createSpy('close')
};
});
it('onceReady fulfills with server endpoint on server and peerconnection success', (done) => {
(<any>mockTcpServer.onceListening).and.returnValue(Promise.resolve(mockEndpoint));
mockPeerConnection.onceConnected = voidPromise;
// We're not testing termination.
(<any>mockTcpServer.onceShutdown).and.returnValue(noopPromise);
server.start(mockTcpServer, mockPeerConnection)
.then((result:net.Endpoint) => {
expect(result.address).toEqual(mockEndpoint.address);
expect(result.port).toEqual(mockEndpoint.port);
})
.then(done);
});
it('onceReady rejects and \'stopped\' fires on socket setup failure', (done) => {
(<any>mockTcpServer.onceListening)
.and.returnValue(Promise.reject(new Error('could not allocate port')));
(<any>mockTcpServer.onceShutdown).and.returnValue(Promise.resolve());
server.start(mockTcpServer, mockPeerConnection).catch(onceServerStopped).then(done);
});
it('\'stopped\' fires, and start fails, on early peerconnection termination', (done) => {
(<any>mockTcpServer.onceListening).and.returnValue(Promise.resolve(mockEndpoint));
(<any>mockTcpServer.onceShutdown).and.returnValue(voidPromise);
mockPeerConnection.onceConnected = voidPromise;
mockPeerConnection.onceClosed = voidPromise;
server.start(mockTcpServer, mockPeerConnection).catch(onceServerStopped).then(done);
});
it('\'stopped\' fires on peerconnection termination', (done) => {
var terminate :() => void;
var terminatePromise = new Promise<void>((F, R) => {
terminate = F;
});
(<any>mockTcpServer.onceListening).and.returnValue(Promise.resolve(mockEndpoint));
(<any>mockTcpServer.onceShutdown).and.returnValue(terminatePromise);
mockPeerConnection.onceConnected = voidPromise;
mockPeerConnection.onceClosed = terminatePromise;
server.start(mockTcpServer, mockPeerConnection).then(onceServerStopped).then(done);
terminate();
});
it('\'stopped\' fires on call to stop', (done) => {
(<any>mockTcpServer.onceListening).and.returnValue(Promise.resolve(mockEndpoint));
mockPeerConnection.onceConnected = voidPromise;
// Neither TCP connection nor datachannel close "naturally".
(<any>mockTcpServer.onceShutdown).and.returnValue(noopPromise);
server.start(mockTcpServer, mockPeerConnection).then(
server.stop).then(onceServerStopped).then(done);
});
it('stop works before the PeerConnection or TcpServer connects', (done) => {
(<any>mockTcpServer.onceListening).and.returnValue(noopPromise);
// PeerConnection never connects.
mockPeerConnection.onceConnected = noopPromise;
// Neither TCP connection nor datachannel close "naturally".
(<any>mockTcpServer.onceShutdown).and.returnValue(noopPromise);
var onceStartFailed :Promise<void> = new Promise<void>((F, R) => {
server.start(mockTcpServer, mockPeerConnection).then(R, F);
});
Promise.all([onceStartFailed, server.stop()]).then(done);
});
});
describe('SOCKS session', function() {
var session :socks_to_rtc.Session;
var mockBytesReceived :handler.Queue<number,void>;
var mockBytesSent :handler.Queue<number,void>;
var mockDataChannel :peerconnection.DataChannel;
var mockDataFromPeerQueue :handler.Queue<peerconnection.Data,void>;
var mockTcpConnection :tcp.Connection;
beforeEach(function() {
session = new socks_to_rtc.Session();
mockTcpConnection = jasmine.createSpyObj('tcp connection', [
'onceClosed',
'close',
'isClosed',
'send',
'pause',
'resume'
]);
mockTcpConnection.dataFromSocketQueue = new handler.Queue<ArrayBuffer,void>();
(<any>mockTcpConnection.close).and.returnValue(Promise.resolve(-1));
mockTcpConnection.onceClosed = Promise.resolve(
tcp.SocketCloseKind.REMOTELY_CLOSED);
(<any>mockTcpConnection.send).and.returnValue(Promise.resolve({ bytesWritten: 1 }));
mockDataFromPeerQueue = new handler.Queue<peerconnection.Data,void>();
mockDataChannel = <any>{
close: jasmine.createSpy('close'),
dataFromPeerQueue: mockDataFromPeerQueue,
getLabel: jasmine.createSpy('getLabel').and.returnValue('mock label'),
onceClosed: noopPromise,
onceOpened: noopPromise,
send: jasmine.createSpy('send'),
isInOverflow: jasmine.createSpy('isInOverflow').and.returnValue(false),
setOverflowListener: jasmine.createSpy('setOverflowListener')
};
(<any>mockDataChannel.send).and.returnValue(voidPromise);
mockBytesReceived = new handler.Queue<number, void>();
mockBytesSent = new handler.Queue<number, void>()
});
it('onceReady fulfills on successful negotiation', (done) => {
spyOn(session, 'doAuthHandshake_').and.returnValue(Promise.resolve());
spyOn(session, 'doRequestHandshake_').and.returnValue(
Promise.resolve({reply: socks_headers.Reply.SUCCEEDED}));
session.start(mockTcpConnection, mockDataChannel, mockBytesSent, mockBytesReceived).then(done);
});
it('onceReady rejects and onceStopped fulfills on unsuccessful negotiation', (done) => {
spyOn(session, 'doAuthHandshake_').and.returnValue(Promise.resolve());
spyOn(session, 'doRequestHandshake_').and.returnValue(
Promise.resolve({reply: socks_headers.Reply.FAILURE}));
session.start(mockTcpConnection, mockDataChannel, mockBytesSent, mockBytesReceived)
.catch((e:Error) => { return session.onceStopped; }).then(done);
});
it('onceStopped fulfills on TCP connection termination', (done) => {
mockTcpConnection.onceClosed = Promise.resolve();
spyOn(session, 'doAuthHandshake_').and.returnValue(Promise.resolve());
spyOn(session, 'doRequestHandshake_').and.returnValue(
Promise.resolve({reply: socks_headers.Reply.SUCCEEDED}));
session.start(mockTcpConnection, mockDataChannel, mockBytesSent, mockBytesReceived)
.then(() => { return session.onceStopped; }).then(done);
});
it('onceStopped fulfills on call to stop', (done) => {
// Neither TCP connection nor datachannel close "naturally".
mockTcpConnection.onceClosed = new Promise<tcp.SocketCloseKind>((F, R) => {});
spyOn(session, 'doAuthHandshake_').and.returnValue(Promise.resolve());
spyOn(session, 'doRequestHandshake_').and.returnValue(
Promise.resolve({reply: socks_headers.Reply.SUCCEEDED}));
session.start(mockTcpConnection, mockDataChannel, mockBytesSent, mockBytesReceived)
.then(session.stop).then(() => { return session.onceStopped; }).then(done);
});
it('bytes sent counter', (done) => {
// Neither TCP connection nor datachannel close "naturally".
mockTcpConnection.onceClosed = new Promise<tcp.SocketCloseKind>((F, R) => {});
spyOn(session, 'doAuthHandshake_').and.returnValue(Promise.resolve());
spyOn(session, 'doRequestHandshake_').and.returnValue(
Promise.resolve({reply: socks_headers.Reply.SUCCEEDED}));
var buffer = new Uint8Array([1,2,3]).buffer;
session.start(
mockTcpConnection,
mockDataChannel,
mockBytesSent,
mockBytesReceived).then(() => {
mockTcpConnection.dataFromSocketQueue.handle(buffer);
});
mockBytesSent.setSyncNextHandler((numBytes:number) => {
expect(numBytes).toEqual(buffer.byteLength);
done();
});
});
it('bytes received counter', (done) => {
// Neither TCP connection nor datachannel close "naturally".
mockTcpConnection.onceClosed = new Promise<tcp.SocketCloseKind>((F, R) => {});
spyOn(session, 'doAuthHandshake_').and.returnValue(Promise.resolve());
spyOn(session, 'doRequestHandshake_').and.returnValue(
Promise.resolve({reply: socks_headers.Reply.SUCCEEDED}));
var message :peerconnection.Data = {
buffer: new Uint8Array([1,2,3]).buffer
};
session.start(
mockTcpConnection,
mockDataChannel,
mockBytesSent,
mockBytesReceived).then(() => {
mockDataFromPeerQueue.handle(message);
});
mockBytesReceived.setSyncNextHandler((numBytes:number) => {
expect(numBytes).toEqual(message.buffer.byteLength);
done();
});
});
it('channel queue drains before termination', (done) => {
// TCP connection doesn't close "naturally" but the data
// channel is already closed when the session is started.
mockTcpConnection.onceClosed = new Promise<tcp.SocketCloseKind>((F, R) => {});
mockDataChannel.onceClosed = voidPromise;
spyOn(session, 'doAuthHandshake_').and.returnValue(Promise.resolve());
spyOn(session, 'doRequestHandshake_').and.returnValue(
Promise.resolve({reply: socks_headers.Reply.SUCCEEDED}));
var message :peerconnection.Data = {
buffer: new Uint8Array([1,2,3]).buffer
};
var onceMessageHandled = mockDataFromPeerQueue.handle(message);
session.start(
mockTcpConnection,
mockDataChannel,
mockBytesSent,
mockBytesReceived);
session.onceStopped.then(() => {
return onceMessageHandled;
}).then(() => {
expect(mockDataChannel.dataFromPeerQueue.getLength()).toEqual(0);
done();
});
});
it('socket queue drains before termination', (done) => {
// The data channel doesn't close "naturally" but the
// TCP connection is already closed when the session is started.
mockTcpConnection.onceClosed = Promise.resolve(tcp.SocketCloseKind.WE_CLOSED_IT);
(<any>mockTcpConnection.isClosed).and.returnValue(true);
mockDataChannel.onceClosed = noopPromise;
spyOn(session, 'doAuthHandshake_').and.returnValue(Promise.resolve());
spyOn(session, 'doRequestHandshake_').and.returnValue(
Promise.resolve({reply: socks_headers.Reply.SUCCEEDED}));
var buffer = new Uint8Array([1,2,3]).buffer;
var onceMessageHandled = mockTcpConnection.dataFromSocketQueue.handle(buffer);
session.start(
mockTcpConnection,
mockDataChannel,
mockBytesSent,
mockBytesReceived);
session.onceStopped.then(() => {
return onceMessageHandled;
}).then(() => {
expect(mockTcpConnection.dataFromSocketQueue.getLength()).toEqual(0);
done();
});
});
it('backpressure', (done) => {
spyOn(session, 'doAuthHandshake_').and.returnValue(Promise.resolve());
spyOn(session, 'doRequestHandshake_').and.returnValue(
Promise.resolve({reply: socks_headers.Reply.SUCCEEDED}));
mockTcpConnection.onceConnected = Promise.resolve(mockConnectionInfo);
mockTcpConnection.onceClosed = new Promise<tcp.SocketCloseKind>((F, R) => {});
var overflowListener :(overflow:boolean) => void;
mockDataChannel.setOverflowListener = (listener) => { overflowListener = listener; };
var buffer = new Uint8Array([1,2,3]).buffer;
// Messages received before start sit in the TCP receive queue.
mockTcpConnection.dataFromSocketQueue.handle(buffer);
expect(mockTcpConnection.dataFromSocketQueue.getLength()).toEqual(1);
expect(mockDataChannel.send).not.toHaveBeenCalled();
session.start(mockTcpConnection, mockDataChannel, mockBytesSent, mockBytesReceived).then(() => {
// After start, the TCP queue should be drained into the datachannel.
expect(mockTcpConnection.dataFromSocketQueue.getLength()).toEqual(0);
expect(mockDataChannel.send).toHaveBeenCalled();
// After draining the queue, the TCP connection should be resumed.
expect(mockTcpConnection.pause).not.toHaveBeenCalled();
expect(mockTcpConnection.resume).toHaveBeenCalled();
// Enter overflow state. This should trigger a call to pause.
overflowListener(true);
expect(mockTcpConnection.pause).toHaveBeenCalled();
// In the paused state, messages are still forwarded
mockTcpConnection.dataFromSocketQueue.handle(buffer);
expect(mockTcpConnection.dataFromSocketQueue.getLength()).toEqual(0);
expect((<any>mockDataChannel.send).calls.count()).toEqual(2);
// Exit overflow state. This should trigger a call to resume.
overflowListener(false);
expect((<any>mockTcpConnection.resume).calls.count()).toEqual(2);
done();
});
});
it('backpressure with early flood', (done) => {
spyOn(session, 'doAuthHandshake_').and.returnValue(Promise.resolve());
spyOn(session, 'doRequestHandshake_').and.returnValue(
Promise.resolve({reply: socks_headers.Reply.SUCCEEDED}));
mockTcpConnection.onceConnected = Promise.resolve(mockConnectionInfo);
mockTcpConnection.onceClosed = new Promise<tcp.SocketCloseKind>((F, R) => {});
var overflowListener :(overflow:boolean) => void;
mockDataChannel.setOverflowListener = (listener) => { overflowListener = listener; };
mockDataChannel.isInOverflow = <any>jasmine.createSpy('isInOverflow').and.returnValue(true);
var buffer = new Uint8Array([1,2,3]).buffer;
// Messages received before start sit in the TCP receive queue.
mockTcpConnection.dataFromSocketQueue.handle(buffer);
expect(mockTcpConnection.dataFromSocketQueue.getLength()).toEqual(1);
expect(mockDataChannel.send).not.toHaveBeenCalled();
session.start(mockTcpConnection, mockDataChannel, mockBytesSent, mockBytesReceived).then(() => {
// After start, the TCP queue should be drained into the datachannel.
expect(mockTcpConnection.dataFromSocketQueue.getLength()).toEqual(0);
expect(mockDataChannel.send).toHaveBeenCalled();
// If the initial queue is enough to trigger overflow, then the
// socket should not be resumed.
expect(mockTcpConnection.pause).not.toHaveBeenCalled();
expect(mockTcpConnection.resume).not.toHaveBeenCalled();
// Exit overflow state. This should trigger a call to resume.
overflowListener(false);
expect(mockTcpConnection.resume).toHaveBeenCalled();
done();
});
});
}); | the_stack |
import { Component, ContentChild, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges, TemplateRef, ViewEncapsulation, ViewChild, ElementRef } from '@angular/core';
import { debounceTime, distinctUntilChanged, map, tap } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { ColumnMode, SortType } from '@swimlane/ngx-datatable';
import { get, isNumber, flatten } from 'lodash-es';
import { BaseEntity } from 'app/shared/model/base-entity';
import { LocalStorageService } from 'ngx-webstorage';
import { SortService } from 'app/shared/service/sort.service';
import { faSort, faSortUp, faSortDown, faCircleNotch } from '@fortawesome/free-solid-svg-icons';
/**
* Enum for ascending and descending order.
* @readonly
* @enum {string}
*/
enum SortOrder {
ASC = 'asc',
DESC = 'desc',
}
/**
* Enum for the sort icon.
* @readonly
* @enum {string}
*/
const SortIcon = {
NONE: faSort,
ASC: faSortUp,
DESC: faSortDown,
};
const SortOrderIcon = {
[SortOrder.ASC]: SortIcon.ASC,
[SortOrder.DESC]: SortIcon.DESC,
};
type SortProp = {
field: string;
order: SortOrder;
};
type PagingValue = number | 'all';
@Component({
selector: 'jhi-data-table',
templateUrl: './data-table.component.html',
styleUrls: ['data-table.component.scss'],
encapsulation: ViewEncapsulation.None,
})
export class DataTableComponent implements OnInit, OnChanges {
/**
* @property templateRef Ref to the content child of this component (which is ngx-datatable)
*/
@ContentChild(TemplateRef, { read: TemplateRef, static: false }) templateRef: TemplateRef<any>;
/**
* @property ngbTypeahead Ref to the autocomplete component from Angular
*/
@ViewChild('ngbTypeahead', { static: false }) ngbTypeahead: ElementRef;
/**
* @property isLoading Loading state of the data that is fetched by the ancestral component
* @property isSearching Whether to show a spinner inside of the input field on the right side (indicating a server search)
* @property searchFailed Whether to show a badge that indicates that the search has failed
* @property searchNoResults Whether to show a badge that indicates that the search did not return any results
* @property isTransitioning Loading overlay on top of the table indicating that the content is changing
* @property showPageSizeDropdownAndSearchField Flag whether to show the "entities per page" dropdown and search input field
* @property entityType Entity identifier (e.g. 'result' or 'participation') used as a key to differentiate from other tables
* @property allEntities List of all entities that should be displayed in the table (one entity per row)
* @property entitiesPerPageTranslation Translation string that has the variable {{ number }} in it (e.g. 'artemisApp.exercise.resultsPerPage')
* @property showAllEntitiesTranslation Translation string if all entities should be displayed (e.g. 'artemisApp.exercise.showAll')
* @property searchNoResultsTranslation Translation string that has the variable {{ length }} in it (default: 'artemisApp.dataTable.search.noResults')
* @property searchPlaceholderTranslation Translation string that is used for the placeholder in the search input field
* @property searchFields Fields of entity whose values will be compared to the user's search string (allows nested attributes, e.g. ['student.login', 'student.name'])
* @property searchEntityFilterEnabled Flag whether searching should cause a filtering of the entities (default: true)
* @function searchTextFromEntity Function that takes an entity and returns a text that is inserted into the search input field when clicking on an autocomplete suggestion
* @function searchResultFormatter Function that takes an entity and returns the text for the autocomplete suggestion result row
* @function onSearchWrapper Wrapper around the onSearch method that can be used to modify the items displayed in the autocomplete
* @function onAutocompleteSelectWrapper Wrapper that can be used to hook into the process when an entity was selected in the autocomplete
* @function customFilter Function that takes an entity and returns true or false depending on whether this entity should be shown (combine with customFilterKey)
* @property customFilterKey Filter state of an ancestral component which triggers a table re-rendering if it changes
*/
@Input() isLoading = false;
@Input() isSearching = false;
@Input() searchFailed = false;
@Input() searchNoResults = false;
@Input() isTransitioning = false;
@Input() showPageSizeDropdownAndSearchField = true;
@Input() entityType = 'entity';
@Input() allEntities: BaseEntity[] = [];
@Input() entitiesPerPageTranslation: string;
@Input() showAllEntitiesTranslation: string;
@Input() searchNoResultsTranslation = 'artemisApp.dataTable.search.noResults';
@Input() searchPlaceholderTranslation: string;
@Input() searchFields: string[] = [];
@Input() searchEntityFilterEnabled = true;
@Input() searchTextFromEntity: (entity: BaseEntity) => string = entityToString;
@Input() searchResultFormatter: (entity: BaseEntity) => string = entityToString;
@Input() onSearchWrapper: (stream: Observable<{ text: string; entities: BaseEntity[] }>) => Observable<BaseEntity[]> = onSearchDefaultWrapper;
@Input() onAutocompleteSelectWrapper: (entity: BaseEntity, callback: (entity: BaseEntity) => void) => void = onAutocompleteSelectDefaultWrapper;
@Input() customFilter: (entity: BaseEntity) => boolean = () => true;
@Input() customFilterKey: any = {};
/**
* @property entitiesSizeChange Emits an event when the number of entities displayed changes (e.g. by filtering)
*/
@Output() entitiesSizeChange = new EventEmitter<number>();
/**
* @property PAGING_VALUES Possible values for the number of entities shown per page of the table
* @property DEFAULT_PAGING_VALUE Default number of entities shown per page if the user has no value set for this yet in local storage
*/
readonly PAGING_VALUES: PagingValue[] = [10, 20, 50, 100, 200, 500, 1000, 'all'];
readonly DEFAULT_PAGING_VALUE = 50;
/**
* @property isRendering Rendering state of the table (used for conditional display of the loading indicator)
* @property entities (Sorted) List of entities that are shown in the table (is a subset of allEntities after filters were applied)
* @property pagingValue Current number (or 'all') of entities displayed per page (can be changed and saved to local storage by the user)
* @property entityCriteria Contains a list of search terms
*/
isRendering: boolean;
entities: BaseEntity[];
pagingValue: PagingValue;
entityCriteria: {
textSearch: string[];
sortProp: SortProp;
};
/**
* @property searchQueryTooShort Whether the entered search term
* @property minSearchQueryLength Minimum number of characters before a search is triggered
*/
searchQueryTooShort: boolean;
readonly minSearchQueryLength = 3;
// Icons
faCircleNotch = faCircleNotch;
constructor(private sortService: SortService, private localStorage: LocalStorageService) {
this.entities = [];
this.entityCriteria = {
textSearch: [],
sortProp: { field: 'id', order: SortOrder.ASC },
};
}
/**
* Life cycle hook called by Angular to indicate that Angular is done creating the component
*/
ngOnInit() {
this.pagingValue = this.getCachedEntitiesPerPage();
// explicitly bind these callbacks to their current context
// so that they can be used from child components
this.onSort = this.onSort.bind(this);
this.iconForSortPropField = this.iconForSortPropField.bind(this);
}
/**
* Method is called when Inputs of this component have changed.
*
* @param changes List of Inputs that were changed
*/
ngOnChanges(changes: SimpleChanges) {
if (changes.allEntities || changes.customFilterKey) {
this.updateEntities();
}
}
/**
* This context will be passed down to templateRef and will be
* available for binding by the local template let declarations
*/
get context() {
return {
settings: {
limit: this.pageLimit,
sortType: SortType.multi,
columnMode: ColumnMode.force,
headerHeight: 50,
footerHeight: 50,
rowHeight: 'auto',
rows: this.entities,
rowClass: '',
scrollbarH: true,
},
controls: {
iconForSortPropField: this.iconForSortPropField,
onSort: this.onSort,
},
};
}
/**
* The component is preparing if the data is loading (managed by the parent component)
* or rendering (managed by this component).
*/
get isPreparing() {
return this.isLoading || this.isRendering;
}
/**
* Number of entities displayed per page. Can be undefined to show all entities without pagination.
*/
get pageLimit() {
return isNumber(this.pagingValue) ? this.pagingValue : undefined;
}
/**
* Returns the translation based on whether a limited number of entities is displayed or all
*
* @param quantifier Number of entities per page or 'all'
*/
perPageTranslation(quantifier: PagingValue) {
return isNumber(quantifier) ? this.entitiesPerPageTranslation : this.showAllEntitiesTranslation;
}
/**
* Key that is used for storing this "items per page" setting in local storage
*/
private get perPageCacheKey() {
return `${this.entityType}-items-per-page`;
}
/**
* Get "items per page" setting from local storage. If it does not exist, use the default.
*/
private getCachedEntitiesPerPage = () => {
const cachedValue = this.localStorage.retrieve(this.perPageCacheKey);
if (cachedValue) {
const parsedValue = parseInt(cachedValue, 10) || cachedValue;
if (this.PAGING_VALUES.includes(parsedValue as any)) {
return parsedValue as PagingValue;
}
}
return this.DEFAULT_PAGING_VALUE;
};
/**
* Set the number of entities shown per page (and persist it in local storage).
* Since the rendering takes a bit, show the loading animation until it completes.
*
* @param paging Number of entities per page
*/
setEntitiesPerPage = (paging: PagingValue) => {
this.isRendering = true;
setTimeout(() => {
this.pagingValue = paging;
this.isRendering = false;
}, 500);
this.localStorage.store(this.perPageCacheKey, paging.toString());
};
/**
* Updates the UI with all available filter/sort settings.
* First performs the filtering, then sorts the remaining entities.
*/
private updateEntities() {
const searchPredicate = (entity: BaseEntity) => {
return !this.searchEntityFilterEnabled || this.filterEntityByTextSearch(this.entityCriteria.textSearch, entity, this.searchFields);
};
const filteredEntities = this.allEntities.filter((entity) => this.customFilter(entity) && searchPredicate(entity));
this.entities = this.sortService.sortByProperty(filteredEntities, this.entityCriteria.sortProp.field, this.entityCriteria.sortProp.order === SortOrder.ASC);
// defer execution of change emit to prevent ExpressionChangedAfterItHasBeenCheckedError, see explanation at https://blog.angular-university.io/angular-debugging/
setTimeout(() => this.entitiesSizeChange.emit(this.entities.length));
}
/**
* Filter the given entities by the provided search words.
* Returns entities that match any of the provides search words, if searchWords is empty returns all entities.
*
* @param searchWords list of student logins or names
* @param entity BaseEntity
* @param searchFields list of paths in entity to search
*/
private filterEntityByTextSearch = (searchWords: string[], entity: BaseEntity, searchFields: string[]) => {
// When no search word is inputted, we return all entities.
if (!searchWords.length) {
return true;
}
// Otherwise we do a fuzzy search on the inputted search words.
const containsSearchWord = (fieldValue: string) => searchWords.some(this.foundIn(fieldValue));
return this.entityFieldValues(entity, searchFields).some(containsSearchWord);
};
/**
* Returns the values that the given entity has in the given fields
*
* @param entity Entity whose field values are extracted
* @param fields Fields to extract from entity (can be paths such as "student.login")
*/
private entityFieldValues = (entity: BaseEntity, fields: string[]) => {
return flatten(fields.map((field) => this.collectEntityFieldValues(entity, field))).filter(Boolean) as string[];
};
/**
* Returns the values that the given entity has in the given field.
* Usually, this will be one value but if the field path contains an array, the rest of the path will be resolved for each array element.
* Values are merged recursively into a flat list.
*
* @param entity Entity whose field values are extracted
* @param field Field to extract from entity (can be paths such as "student.login" or array path such as "students.login")
*/
private collectEntityFieldValues = (entity: BaseEntity, field: string): any[] => {
const separator = '.';
const [head, ...tail] = field.split(separator);
if (tail.length > 0) {
const resolved = get(entity, head);
if (Array.isArray(resolved)) {
return flatten(resolved.map((subEntity) => this.collectEntityFieldValues(subEntity, tail.join(separator))));
}
return this.collectEntityFieldValues(resolved, tail.join(separator));
}
return [get(entity, head, false)];
};
/**
* Performs a case-insensitive search of "word" inside of "text".
* If "word" consists of multiple segments separated by a space, each one of them must appear in "text".
* This relaxation has the benefit that searching for "Max Mustermann" will still find "Max Gregor Mustermann".
* Additionally, the wildcard symbols "*" and "?" are supported.
*
* @param text string that is searched for param "word"
*/
private foundIn = (text: string) => (word: string) => {
const segments = word.toLowerCase().split(' ');
return (
text &&
word &&
segments.every((segment) => {
const regex = segment
.replace(/[.+\-^${}()|[\]\\]/g, '\\$&') // escape
.replace(/\*/g, '.*') // multiple characters
.replace(/\?/g, '.'); // single character
return new RegExp(regex).test(text.toLowerCase());
})
);
};
/**
* Splits the provides search words by comma and updates the autocompletion overlay.
* Also updates the available entities in the UI.
*
* @param text$ stream of text input.
*/
onSearch = (text$: Observable<string>): Observable<BaseEntity[]> => {
return this.onSearchWrapper(
text$.pipe(
debounceTime(200),
distinctUntilChanged(),
tap(() => {
this.searchQueryTooShort = false;
}),
map((text) => {
const searchWords = text.split(',').map((word) => word.trim());
// When the entity field is cleared, we translate the resulting empty string to an empty array (otherwise no entities would be found).
return { text, searchWords: searchWords.length === 1 && !searchWords[0] ? [] : searchWords };
}),
// For available entities in table.
tap(({ searchWords }) => {
this.entityCriteria.textSearch = searchWords;
this.updateEntities();
}),
// For autocomplete.
map(({ text, searchWords }) => {
// We only execute the autocomplete for the last keyword in the provided list.
const lastSearchWord = searchWords.last();
// Don't execute autocomplete for less than two inputted characters.
if (!lastSearchWord || lastSearchWord.length < this.minSearchQueryLength) {
this.searchQueryTooShort = true;
return { text, entities: [] };
}
return {
text,
entities: this.entities.filter((entity) => {
const fieldValues = this.entityFieldValues(entity, this.searchFields);
return fieldValues.some((fieldValue) => this.foundIn(fieldValue)(lastSearchWord));
}),
};
}),
),
);
};
/**
* Function that is called when the search input emits a blur event.
* Can be used to clear up search-related info messages.
*/
onSearchInputBlur() {
this.searchQueryTooShort = false;
}
/**
* Property that exposes the typeahead buttons (= autocomplete suggestion options) as DOM elements
*/
get typeaheadButtons() {
return get(this.ngbTypeahead, 'nativeElement.nextSibling.children', []);
}
/**
* Method is called when user clicks on an autocomplete suggestion. The input method
* searchTextFromEntity determines how the entity is converted to a searchable string.
*
* @param entity Entity that was selected via autocomplete
*/
onAutocompleteSelect = (entity: BaseEntity) => {
this.entityCriteria.textSearch[this.entityCriteria.textSearch.length - 1] = this.searchTextFromEntity(entity);
this.onAutocompleteSelectWrapper(entity, this.filterAfterAutocompleteSelect);
};
/**
* Method updates the displayed entities (will be only one entity if the search text is unique per entity).
*/
filterAfterAutocompleteSelect = () => {
this.updateEntities();
};
/**
* Formats the search input.
*/
searchInputFormatter = () => {
return this.entityCriteria.textSearch.join(', ');
};
/**
* Sets the selected sort field, then updates the available entities in the UI.
* Toggles the order direction (asc, desc) when the field has not changed.
*
* @param field Entity field
*/
onSort(field: string) {
const sameField = this.entityCriteria.sortProp && this.entityCriteria.sortProp.field === field;
const order = sameField ? this.invertSort(this.entityCriteria.sortProp.order) : SortOrder.ASC;
this.entityCriteria.sortProp = { field, order };
this.updateEntities();
}
/**
* Returns the opposite sort order of the given sort order.
*
* @param order SortOrder
*/
private invertSort = (order: SortOrder) => {
return order === SortOrder.ASC ? SortOrder.DESC : SortOrder.ASC;
};
/**
* Returns the Font Awesome icon name for a column header's sorting icon
* based on the currently active sortProp field and order.
*
* @param field Entity field
*/
iconForSortPropField(field: string) {
if (this.entityCriteria.sortProp.field !== field) {
return SortIcon.NONE;
}
return SortOrderIcon[this.entityCriteria.sortProp.order];
}
}
const entityToString = (entity: BaseEntity) => entity.id!.toString();
/**
* Default on search wrapper that simply strips the search text and passes on the results.
* This can be customized by supplying your own onSearchWrapper as an Input that e.g. modifies the results.
* Just copy the default wrapper below into your consumer component (that uses this component) as a blueprint and adapt it.
*
* @param stream$ stream of searches of the format {text, entities} where entities are the results
*/
const onSearchDefaultWrapper = (stream$: Observable<{ text: string; entities: BaseEntity[] }>): Observable<BaseEntity[]> => {
return stream$.pipe(
map(({ entities }) => {
return entities;
}),
);
};
/**
* Default on autocomplete select wrapper that simply calls the provided callback (which is this components onAutocompleteSelect).
* This can be customized by supplying your own onAutocompleteSelectWrapper as an Input that changes or adds behavior.
* Just copy the default wrapper below into your consumer component (that uses this component) as a blueprint and adapt it.
*
* @param entity The selected entity from the autocomplete suggestions
* @param callback Function that can be called with the selected entity to trigger this component's default behavior for on select
*/
const onAutocompleteSelectDefaultWrapper = (entity: BaseEntity, callback: (entity: BaseEntity) => void): void => {
callback(entity);
}; | the_stack |
import { Group } from '@antv/g-canvas';
import { range } from 'lodash';
import { DataCell } from '@/cell/data-cell';
import { FrozenGroup } from '@/common/constant';
import { RootInteraction } from '@/interaction/root';
import {
ScrollDirection,
BrushSelection,
CellTypes,
getScrollOffsetForCol,
getScrollOffsetForRow,
InteractionBrushSelectionStage,
InterceptType,
Node,
type OriginalEvent,
PivotSheet,
S2Event,
SpreadSheet,
type ViewMeta,
} from '@/index';
import type { TableFacet } from '@/facet';
jest.mock('@/interaction/event-controller');
jest.mock('@/interaction/root');
jest.mock('@/utils/tooltip');
jest.mock('@/cell/data-cell');
const MockRootInteraction =
RootInteraction as unknown as jest.Mock<RootInteraction>;
const MockDataCell = DataCell as unknown as jest.Mock<DataCell>;
describe('Interaction Brush Selection Tests', () => {
let brushSelectionInstance: BrushSelection;
let mockSpreadSheetInstance: SpreadSheet;
let mockRootInteraction: RootInteraction;
const startBrushDataCellMeta: Partial<ViewMeta> = {
colIndex: 0,
rowIndex: 1,
};
const endBrushDataCellMeta: Partial<ViewMeta> = {
colIndex: 4,
rowIndex: 3,
};
const startBrushDataCell = new MockDataCell();
startBrushDataCell.getMeta = () => startBrushDataCellMeta as ViewMeta;
const endBrushDataCell = new MockDataCell();
endBrushDataCell.getMeta = () => endBrushDataCellMeta as ViewMeta;
const panelGroupAllDataCells = Array.from<number[]>({ length: 4 })
.fill(range(10))
.reduce<DataCell[]>((arr, v, i) => {
v.forEach((_, j) => {
const cell = {
cellType: CellTypes.DATA_CELL,
getMeta() {
return {
colIndex: j,
rowIndex: i,
} as ViewMeta;
},
} as DataCell;
arr.push(cell);
});
return arr;
}, []);
const emitEvent = (type: S2Event, event: Partial<OriginalEvent>) => {
brushSelectionInstance.spreadsheet.emit(type, {
originalEvent: event,
preventDefault() {},
} as any);
};
const emitGlobalEvent = (type: S2Event, event: Partial<MouseEvent>) => {
brushSelectionInstance.spreadsheet.emit(type, {
...event,
preventDefault() {},
} as any);
};
beforeEach(() => {
MockRootInteraction.mockClear();
mockSpreadSheetInstance = new PivotSheet(
document.createElement('div'),
null,
null,
);
mockRootInteraction = new MockRootInteraction(mockSpreadSheetInstance);
mockSpreadSheetInstance.getCell = jest.fn(() => startBrushDataCell) as any;
mockSpreadSheetInstance.foregroundGroup = new Group('');
mockSpreadSheetInstance.showTooltipWithInfo = jest.fn();
mockRootInteraction.getPanelGroupAllDataCells = () =>
panelGroupAllDataCells;
mockSpreadSheetInstance.interaction = mockRootInteraction;
mockSpreadSheetInstance.render();
mockSpreadSheetInstance.facet.layoutResult.colLeafNodes = Array.from(
new Array(10),
).map((_, idx) => {
return {
colIndex: idx,
id: idx,
x: idx * 100,
width: 100,
};
}) as unknown[] as Node[];
mockSpreadSheetInstance.facet.layoutResult.rowLeafNodes = Array.from(
new Array(10),
).map((_, idx) => {
return {
rowIndex: idx,
id: idx,
y: idx * 100,
height: 100,
};
}) as unknown[] as Node[];
mockSpreadSheetInstance.facet.getCellRange = () => {
return {
start: 0,
end: 9,
};
};
brushSelectionInstance = new BrushSelection(mockSpreadSheetInstance);
brushSelectionInstance.brushSelectionStage =
InteractionBrushSelectionStage.UN_DRAGGED;
brushSelectionInstance.hidePrepareSelectMaskShape = jest.fn();
});
test('should register events', () => {
expect(brushSelectionInstance.bindEvents).toBeDefined();
});
test('should not render invisible prepare select mask shape after rendered', () => {
expect(brushSelectionInstance.prepareSelectMaskShape).not.toBeDefined();
});
test('should init brush selection stage', () => {
expect(brushSelectionInstance.brushSelectionStage).toEqual(
InteractionBrushSelectionStage.UN_DRAGGED,
);
});
test('should render invisible prepare select mask shape after mouse down on the data cell', () => {
emitEvent(S2Event.DATA_CELL_MOUSE_DOWN, {
layerX: 10,
layerY: 20,
});
expect(brushSelectionInstance.prepareSelectMaskShape).toBeDefined();
expect(
brushSelectionInstance.prepareSelectMaskShape.attr('visible'),
).toBeFalsy();
});
test('should get start brush point when mouse down', () => {
emitEvent(S2Event.DATA_CELL_MOUSE_DOWN, {
layerX: 10,
layerY: 20,
});
expect(brushSelectionInstance.spreadsheet.getCell).toHaveBeenCalled();
expect(brushSelectionInstance.startBrushPoint).toStrictEqual({
x: 10,
y: 20,
scrollX: 0,
scrollY: 0,
rowIndex: 1,
colIndex: 0,
});
expect(brushSelectionInstance.displayedDataCells).toEqual(
panelGroupAllDataCells,
);
});
test('should skip brush selection if mouse not dragged', () => {
emitEvent(S2Event.DATA_CELL_MOUSE_DOWN, {
layerX: 10,
layerY: 20,
});
emitGlobalEvent(S2Event.GLOBAL_MOUSE_MOVE, {
clientX: 12,
clientY: 22,
});
emitEvent(S2Event.GLOBAL_MOUSE_UP, {});
expect(brushSelectionInstance.brushSelectionStage).toEqual(
InteractionBrushSelectionStage.UN_DRAGGED,
);
expect(
brushSelectionInstance.spreadsheet.interaction.hasIntercepts([
InterceptType.BRUSH_SELECTION,
]),
).toBeFalsy();
// 如果刷选距离过短, 则走单选的逻辑, 需要隐藏刷选提示框
expect(
brushSelectionInstance.hidePrepareSelectMaskShape,
).toHaveBeenCalled();
});
// https://github.com/antvis/S2/issues/852
test('should clear brush selection state when mouse down and context menu clicked', () => {
const globalMouseUp = jest.fn();
mockSpreadSheetInstance.on(S2Event.GLOBAL_MOUSE_UP, globalMouseUp);
emitEvent(S2Event.DATA_CELL_MOUSE_DOWN, {
layerX: 10,
layerY: 20,
});
emitGlobalEvent(S2Event.GLOBAL_MOUSE_MOVE, {
clientX: 12,
clientY: 22,
});
expect(brushSelectionInstance.brushSelectionStage).toEqual(
InteractionBrushSelectionStage.DRAGGED,
);
emitEvent(S2Event.GLOBAL_CONTEXT_MENU, {});
expect(globalMouseUp).not.toHaveBeenCalled();
expect(brushSelectionInstance.brushSelectionStage).toEqual(
InteractionBrushSelectionStage.UN_DRAGGED,
);
expect(
brushSelectionInstance.spreadsheet.interaction.hasIntercepts([
InterceptType.HOVER,
]),
).toBeFalsy();
expect(
brushSelectionInstance.spreadsheet.interaction.hasIntercepts([
InterceptType.BRUSH_SELECTION,
]),
).toBeFalsy();
expect(
brushSelectionInstance.hidePrepareSelectMaskShape,
).toHaveReturnedTimes(1);
});
test('should skip brush selection if mouse move less than valid distance', () => {
emitEvent(S2Event.GLOBAL_MOUSE_MOVE, {});
expect(brushSelectionInstance.brushSelectionStage).toEqual(
InteractionBrushSelectionStage.UN_DRAGGED,
);
expect(brushSelectionInstance.endBrushPoint).not.toBeDefined();
expect(brushSelectionInstance.brushRangeDataCells).toHaveLength(0);
expect(
brushSelectionInstance.spreadsheet.interaction.hasIntercepts([
InterceptType.HOVER,
]),
).toBeFalsy();
});
test('should get brush selection range cells', () => {
const selectedFn = jest.fn();
const brushSelectionFn = jest.fn();
mockSpreadSheetInstance.getCell = jest.fn(() => startBrushDataCell) as any;
mockSpreadSheetInstance.on(S2Event.GLOBAL_SELECTED, selectedFn);
mockSpreadSheetInstance.on(
S2Event.DATE_CELL_BRUSH_SELECTION,
brushSelectionFn,
);
// ================== mouse down ==================
emitEvent(S2Event.DATA_CELL_MOUSE_DOWN, { layerX: 10, layerY: 20 });
mockSpreadSheetInstance.getCell = jest.fn(() => endBrushDataCell) as any;
// ================== mouse move ==================
emitGlobalEvent(S2Event.GLOBAL_MOUSE_MOVE, {
clientX: 100,
clientY: 200,
});
expect(brushSelectionInstance.brushSelectionStage).toEqual(
InteractionBrushSelectionStage.DRAGGED,
);
// get end brush point
expect(brushSelectionInstance.endBrushPoint).toEqual({
...endBrushDataCellMeta,
x: 100,
y: 200,
});
// show prepare brush selection mask
expect(brushSelectionInstance.prepareSelectMaskShape.attr()).toMatchObject({
x: 10,
y: 20,
width: 90,
height: 180,
});
// ================== mouse up ==================
emitEvent(S2Event.GLOBAL_MOUSE_UP, {});
// hide prepare mask
expect(
brushSelectionInstance.prepareSelectMaskShape.attr('visible'),
).toBeFalsy();
// show tooltip
expect(mockSpreadSheetInstance.showTooltipWithInfo).toHaveBeenCalled();
// reset brush stage
expect(brushSelectionInstance.brushSelectionStage).toEqual(
InteractionBrushSelectionStage.UN_DRAGGED,
);
// get brush range selected cells
expect(brushSelectionInstance.brushRangeDataCells).toHaveLength(15);
brushSelectionInstance.brushRangeDataCells.forEach((cell) => {
const { rowIndex, colIndex } = cell.getMeta();
expect(rowIndex).toBeLessThanOrEqual(endBrushDataCellMeta.rowIndex);
expect(rowIndex).toBeGreaterThanOrEqual(startBrushDataCellMeta.rowIndex);
expect(colIndex).toBeLessThanOrEqual(endBrushDataCellMeta.colIndex);
expect(colIndex).toBeGreaterThanOrEqual(startBrushDataCellMeta.colIndex);
});
// emit event
expect(selectedFn).toHaveBeenCalledTimes(1);
expect(brushSelectionFn).toHaveBeenCalledTimes(1);
});
test('should get correct formatted brush point', () => {
const EXTRA_PIXEL = 2;
const VSCROLLBAR_WIDTH = 5;
const { width, height } = mockSpreadSheetInstance.facet.getCanvasHW();
const minX = 10;
const minY = 10;
const maxY = height + 10;
const maxX = width + 10;
mockSpreadSheetInstance.facet.panelBBox = {
minX,
minY,
maxY,
maxX,
} as any;
brushSelectionInstance.endBrushPoint = {
x: maxX - 10,
y: maxY - 10,
scrollX: 0,
colIndex: 0,
rowIndex: 0,
};
mockSpreadSheetInstance.facet.vScrollBar = {
getBBox: () =>
({
width: VSCROLLBAR_WIDTH,
} as any),
} as any;
let result = brushSelectionInstance.formatBrushPointForScroll({
x: 20,
y: 20,
});
expect(result).toStrictEqual({
x: {
needScroll: true,
value: maxX - VSCROLLBAR_WIDTH - EXTRA_PIXEL,
},
y: {
needScroll: true,
value: maxY - EXTRA_PIXEL,
},
});
brushSelectionInstance.endBrushPoint = {
x: maxX - 10,
y: maxY - 10,
scrollX: 0,
colIndex: 0,
rowIndex: 0,
};
result = brushSelectionInstance.formatBrushPointForScroll({
x: 1,
y: 1,
});
expect(result).toStrictEqual({
x: {
needScroll: false,
value: maxX - 10 + 1,
},
y: {
needScroll: false,
value: maxY - 10 + 1,
},
});
brushSelectionInstance.endBrushPoint = {
x: minX + 10,
y: minY + 10,
scrollX: 0,
colIndex: 0,
rowIndex: 0,
};
result = brushSelectionInstance.formatBrushPointForScroll({
x: -20,
y: -20,
});
expect(result).toStrictEqual({
x: {
needScroll: true,
value: minX + EXTRA_PIXEL,
},
y: {
needScroll: true,
value: minY + EXTRA_PIXEL,
},
});
});
test('should get correct selected cell metas', () => {
expect(
brushSelectionInstance.getSelectedCellMetas({
start: {
colIndex: 0,
rowIndex: 0,
},
end: {
colIndex: 9,
rowIndex: 9,
},
} as any).length,
).toBe(100);
});
test('should get correct adjusted frozen rowIndex and colIndex', () => {
const { adjustNextColIndexWithFrozen, adjustNextRowIndexWithFrozen } =
brushSelectionInstance;
mockSpreadSheetInstance.setOptions({
frozenColCount: 1,
frozenRowCount: 1,
frozenTrailingColCount: 1,
frozenTrailingRowCount: 1,
});
mockSpreadSheetInstance.dataSet.getDisplayDataSet = () => {
return Array.from(new Array(10)).map(() => {
return {};
});
};
(mockSpreadSheetInstance.facet as TableFacet).panelScrollGroupIndexes = [
1, 8, 1, 8,
];
expect(adjustNextColIndexWithFrozen(9, ScrollDirection.TRAILING)).toBe(8);
expect(adjustNextColIndexWithFrozen(0, ScrollDirection.LEADING)).toBe(1);
expect(adjustNextColIndexWithFrozen(7, ScrollDirection.TRAILING)).toBe(7);
expect(adjustNextRowIndexWithFrozen(9, ScrollDirection.TRAILING)).toBe(8);
expect(adjustNextRowIndexWithFrozen(0, ScrollDirection.LEADING)).toBe(1);
expect(adjustNextRowIndexWithFrozen(7, ScrollDirection.TRAILING)).toBe(7);
});
test('should get correct scroll offset for row and col', () => {
const { facet } = mockSpreadSheetInstance;
expect(
getScrollOffsetForCol(
7,
ScrollDirection.LEADING,
mockSpreadSheetInstance,
),
).toBe(700);
expect(
getScrollOffsetForCol(
7,
ScrollDirection.TRAILING,
mockSpreadSheetInstance,
),
).toBe(200);
(facet as TableFacet).frozenGroupInfo = {
[FrozenGroup.FROZEN_COL]: {
width: 100,
},
[FrozenGroup.FROZEN_TRAILING_COL]: {
width: 100,
},
[FrozenGroup.FROZEN_ROW]: {
height: 0,
},
[FrozenGroup.FROZEN_TRAILING_ROW]: {
height: 0,
},
};
expect(
getScrollOffsetForCol(
7,
ScrollDirection.LEADING,
mockSpreadSheetInstance,
),
).toBe(600);
expect(
getScrollOffsetForCol(
7,
ScrollDirection.TRAILING,
mockSpreadSheetInstance,
),
).toBe(300);
facet.panelBBox = {
height: facet.getCanvasHW().height,
} as any;
facet.viewCellHeights = facet.getViewCellHeights(facet.layoutResult);
expect(
getScrollOffsetForRow(
7,
ScrollDirection.LEADING,
mockSpreadSheetInstance,
),
).toBe(700);
expect(
getScrollOffsetForRow(
7,
ScrollDirection.TRAILING,
mockSpreadSheetInstance,
),
).toBe(320);
(facet as TableFacet).frozenGroupInfo = {
[FrozenGroup.FROZEN_COL]: {
width: 0,
},
[FrozenGroup.FROZEN_TRAILING_COL]: {
width: 0,
},
[FrozenGroup.FROZEN_ROW]: {
height: 100,
},
[FrozenGroup.FROZEN_TRAILING_ROW]: {
height: 100,
},
};
expect(
getScrollOffsetForRow(
7,
ScrollDirection.LEADING,
mockSpreadSheetInstance,
),
).toBe(600);
expect(
getScrollOffsetForRow(
7,
ScrollDirection.TRAILING,
mockSpreadSheetInstance,
),
).toBe(420);
});
test('should get valid x and y index', () => {
const { validateXIndex, validateYIndex } = brushSelectionInstance;
expect(validateXIndex(-1)).toBe(null);
expect(validateXIndex(1)).toBe(1);
expect(validateXIndex(10)).toBe(null);
expect(validateXIndex(9)).toBe(9);
expect(validateYIndex(-1)).toBe(null);
expect(validateYIndex(1)).toBe(1);
expect(validateYIndex(10)).toBe(null);
expect(validateYIndex(9)).toBe(9);
(mockSpreadSheetInstance.facet as TableFacet).frozenGroupInfo = {
[FrozenGroup.FROZEN_COL]: {
range: [0, 1],
},
[FrozenGroup.FROZEN_TRAILING_COL]: {
range: [8, 9],
},
[FrozenGroup.FROZEN_ROW]: {
range: [0, 1],
},
[FrozenGroup.FROZEN_TRAILING_ROW]: {
range: [8, 9],
},
};
expect(validateXIndex(1)).toBe(null);
expect(validateXIndex(2)).toBe(2);
expect(validateXIndex(8)).toBe(null);
expect(validateXIndex(7)).toBe(7);
expect(validateXIndex(1)).toBe(null);
expect(validateXIndex(2)).toBe(2);
expect(validateXIndex(8)).toBe(null);
expect(validateXIndex(7)).toBe(7);
});
}); | the_stack |
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
/* eslint-disable max-statements, complexity */
import TransitionManager, {TransitionProps} from './transition-manager';
import LinearInterpolator from '../transitions/linear-interpolator';
import {IViewState} from './view-state';
import {ConstructorOf} from '../types/types';
import type Viewport from '../viewports/viewport';
import type {EventManager, MjolnirEvent, MjolnirGestureEvent, MjolnirWheelEvent, MjolnirKeyEvent} from 'mjolnir.js';
import type {Timeline} from '@luma.gl/core';
const NO_TRANSITION_PROPS = {
transitionDuration: 0
} as const;
const DEFAULT_INERTIA = 300;
const INERTIA_EASING = t => 1 - (1 - t) * (1 - t);
const EVENT_TYPES = {
WHEEL: ['wheel'],
PAN: ['panstart', 'panmove', 'panend'],
PINCH: ['pinchstart', 'pinchmove', 'pinchend'],
TRIPLE_PAN: ['tripanstart', 'tripanmove', 'tripanend'],
DOUBLE_TAP: ['doubletap'],
KEYBOARD: ['keydown']
} as const;
/** Configuration of how user input is handled */
export type ControllerOptions = {
/** Enable zooming with mouse wheel. Default `true`. */
scrollZoom?: boolean | {
/** Scaler that translates wheel delta to the change of viewport scale. Default `0.01`. */
speed?: number;
/** Smoothly transition to the new zoom. If enabled, will provide a slightly lagged but smoother experience. Default `false`. */
smooth?: boolean
};
/** Enable panning with pointer drag. Default `true` */
dragPan?: boolean;
/** Enable rotating with pointer drag. Default `true` */
dragRotate?: boolean;
/** Enable zooming with double click. Default `true` */
doubleClickZoom?: boolean;
/** Enable zooming with multi-touch. Default `true` */
touchZoom?: boolean;
/** Enable rotating with multi-touch. Use two-finger rotating gesture for horizontal and three-finger swiping gesture for vertical rotation. Default `false` */
touchRotate?: boolean;
/** Enable interaction with keyboard. Default `true`. */
keyboard?:
| boolean
| {
/** Speed of zoom using +/- keys. Default `2` */
zoomSpeed?: number;
/** Speed of movement using arrow keys, in pixels. */
moveSpeed?: number;
/** Speed of rotation using shift + left/right arrow keys, in degrees. Default 15. */
rotateSpeedX?: number;
/** Speed of rotation using shift + up/down arrow keys, in degrees. Default 10. */
rotateSpeedY?: number;
};
/** Drag behavior without pressing function keys, one of `pan` and `rotate`. */
dragMode?: 'pan' | 'rotate';
/** Enable inertia after panning/pinching. If a number is provided, indicates the duration of time over which the velocity reduces to zero, in milliseconds. Default `false`. */
inertia?: boolean | number;
};
export type ControllerProps = {
/** Identifier of the controller */
id: string;
/** Viewport x position */
x: number;
/** Viewport y position */
y: number;
/** Viewport width */
width: number;
/** Viewport height */
height: number;
} & ControllerOptions & TransitionProps;
/** The state of a controller */
export type InteractionState = {
/** If the view state is in transition */
inTransition?: boolean;
/** If the user is dragging */
isDragging?: boolean;
/** If the view is being panned, either from user input or transition */
isPanning?: boolean;
/** If the view is being rotated, either from user input or transition */
isRotating?: boolean;
/** If the view is being zoomed, either from user input or transition */
isZooming?: boolean;
}
/** Parameters passed to the onViewStateChange callback */
export type ViewStateChangeParameters = {
/** The next view state, either from user input or transition */
viewState: Record<string, any>;
/** Object describing the nature of the view state change */
interactionState: InteractionState;
/** The current view state */
oldViewState?: Record<string, any>;
}
const pinchEventWorkaround: any = {};
export default abstract class Controller<ControllerState extends IViewState<ControllerState>> {
abstract get ControllerState(): ConstructorOf<ControllerState>;
abstract get transition(): TransitionProps;
// @ts-expect-error (2564) - not assigned in the constructor
protected props: ControllerProps;
protected state: Record<string, any> = {};
protected transitionManager: TransitionManager<ControllerState>;
protected eventManager: EventManager;
protected onViewStateChange: (params: ViewStateChangeParameters) => void;
protected onStateChange: (state: InteractionState) => void;
protected makeViewport: (opts: Record<string, any>) => Viewport
private _controllerState?: ControllerState;
private _events: Record<string, boolean> = {};
private _interactionState: InteractionState = {
isDragging: false
};
private _customEvents: string[] = [];
private _eventStartBlocked: any = null;
private _panMove: boolean = false;
protected invertPan: boolean = false;
protected dragMode: 'pan' | 'rotate' = 'rotate';
protected inertia: number = 0;
protected scrollZoom: boolean | {speed?: number; smooth?: boolean} = true;
protected dragPan: boolean = true;
protected dragRotate: boolean = true;
protected doubleClickZoom: boolean = true;
protected touchZoom: boolean = true;
protected touchRotate: boolean = false;
protected keyboard:
| boolean
| {
zoomSpeed?: number; // speed of zoom using +/- keys. Default 2.
moveSpeed?: number; // speed of movement using arrow keys, in pixels.
rotateSpeedX?: number; // speed of rotation using shift + left/right arrow keys, in degrees. Default 15.
rotateSpeedY?: number; // speed of rotation using shift + up/down arrow keys, in degrees. Default 10.
} = true;
constructor(opts: {
timeline: Timeline,
eventManager: EventManager;
makeViewport: (opts: Record<string, any>) => Viewport;
onViewStateChange: (params: ViewStateChangeParameters) => void;
onStateChange: (state: InteractionState) => void;
}) {
this.transitionManager = new TransitionManager<ControllerState>({
...opts,
getControllerState: props => new this.ControllerState(props),
onViewStateChange: this._onTransition.bind(this),
onStateChange: this._setInteractionState.bind(this)
});
this.handleEvent = this.handleEvent.bind(this);
this.eventManager = opts.eventManager;
this.onViewStateChange = opts.onViewStateChange || (() => {});
this.onStateChange = opts.onStateChange || (() => {});
this.makeViewport = opts.makeViewport;
}
set events(customEvents) {
this.toggleEvents(this._customEvents, false);
this.toggleEvents(customEvents, true);
this._customEvents = customEvents;
// Make sure default events are not overwritten
if (this.props) {
this.setProps(this.props);
}
}
finalize() {
for (const eventName in this._events) {
if (this._events[eventName]) {
// eslint-disable-next-line @typescript-eslint/unbound-method
this.eventManager?.off(eventName, this.handleEvent);
}
}
this.transitionManager.finalize();
}
/**
* Callback for events
*/
handleEvent(event: MjolnirEvent) {
// Force recalculate controller state
this._controllerState = undefined;
const eventStartBlocked = this._eventStartBlocked;
switch (event.type) {
case 'panstart':
return eventStartBlocked ? false : this._onPanStart(event);
case 'panmove':
return this._onPan(event);
case 'panend':
return this._onPanEnd(event);
case 'pinchstart':
return eventStartBlocked ? false : this._onPinchStart(event);
case 'pinchmove':
return this._onPinch(event);
case 'pinchend':
return this._onPinchEnd(event);
case 'tripanstart':
return eventStartBlocked ? false : this._onTriplePanStart(event);
case 'tripanmove':
return this._onTriplePan(event);
case 'tripanend':
return this._onTriplePanEnd(event);
case 'doubletap':
return this._onDoubleTap(event);
case 'wheel':
return this._onWheel(event);
case 'keydown':
return this._onKeyDown(event);
default:
return false;
}
}
/* Event utils */
// Event object: http://hammerjs.github.io/api/#event-object
get controllerState(): ControllerState {
this._controllerState = this._controllerState || new this.ControllerState({
makeViewport: this.makeViewport,
...this.props,
...this.state
});
return this._controllerState ;
}
getCenter(event: MjolnirGestureEvent | MjolnirWheelEvent) : [number, number] {
const {x, y} = this.props;
const {offsetCenter} = event;
return [offsetCenter.x - x, offsetCenter.y - y];
}
isPointInBounds(pos: [number, number], event: MjolnirEvent): boolean {
const {width, height} = this.props;
if (event && event.handled) {
return false;
}
const inside = pos[0] >= 0 && pos[0] <= width && pos[1] >= 0 && pos[1] <= height;
if (inside && event) {
event.stopPropagation();
}
return inside;
}
isFunctionKeyPressed(event: MjolnirEvent): boolean {
const {srcEvent} = event;
return Boolean(srcEvent.metaKey || srcEvent.altKey || srcEvent.ctrlKey || srcEvent.shiftKey);
}
isDragging(): boolean {
return this._interactionState.isDragging || false;
}
// When a multi-touch event ends, e.g. pinch, not all pointers are lifted at the same time.
// This triggers a brief `pan` event.
// Calling this method will temporarily disable *start events to avoid conflicting transitions.
blockEvents(timeout: number): void {
/* global setTimeout */
const timer = setTimeout(() => {
if (this._eventStartBlocked === timer) {
this._eventStartBlocked = null;
}
}, timeout);
this._eventStartBlocked = timer;
}
/**
* Extract interactivity options
*/
setProps(props: ControllerProps) {
if (props.dragMode) {
this.dragMode = props.dragMode;
}
this.props = props;
if (!('transitionInterpolator' in props)) {
// Add default transition interpolator
props.transitionInterpolator = this._getTransitionProps().transitionInterpolator;
}
this.transitionManager.processViewStateChange(props);
const {inertia} = props;
this.inertia = Number.isFinite(inertia) ? (inertia as number) : (inertia === true ? DEFAULT_INERTIA : 0);
// TODO - make sure these are not reset on every setProps
const {
scrollZoom = true,
dragPan = true,
dragRotate = true,
doubleClickZoom = true,
touchZoom = true,
touchRotate = false,
keyboard = true
} = props;
// Register/unregister events
const isInteractive = Boolean(this.onViewStateChange);
this.toggleEvents(EVENT_TYPES.WHEEL, isInteractive && scrollZoom);
this.toggleEvents(EVENT_TYPES.PAN, isInteractive && (dragPan || dragRotate));
this.toggleEvents(EVENT_TYPES.PINCH, isInteractive && (touchZoom || touchRotate));
this.toggleEvents(EVENT_TYPES.TRIPLE_PAN, isInteractive && touchRotate);
this.toggleEvents(EVENT_TYPES.DOUBLE_TAP, isInteractive && doubleClickZoom);
this.toggleEvents(EVENT_TYPES.KEYBOARD, isInteractive && keyboard);
// Interaction toggles
this.scrollZoom = scrollZoom;
this.dragPan = dragPan;
this.dragRotate = dragRotate;
this.doubleClickZoom = doubleClickZoom;
this.touchZoom = touchZoom;
this.touchRotate = touchRotate;
this.keyboard = keyboard;
}
updateTransition() {
this.transitionManager.updateTransition();
}
toggleEvents(eventNames, enabled) {
if (this.eventManager) {
eventNames.forEach(eventName => {
if (this._events[eventName] !== enabled) {
this._events[eventName] = enabled;
if (enabled) {
// eslint-disable-next-line @typescript-eslint/unbound-method
this.eventManager.on(eventName, this.handleEvent);
} else {
// eslint-disable-next-line @typescript-eslint/unbound-method
this.eventManager.off(eventName, this.handleEvent);
}
}
});
}
}
// Private Methods
/* Callback util */
// formats map state and invokes callback function
protected updateViewport(newControllerState: ControllerState, extraProps: Record<string, any> | null = null, interactionState: InteractionState = {}) {
const viewState = {...newControllerState.getViewportProps(), ...extraProps};
// TODO - to restore diffing, we need to include interactionState
const changed = this.controllerState !== newControllerState;
// const oldViewState = this.controllerState.getViewportProps();
// const changed = Object.keys(viewState).some(key => oldViewState[key] !== viewState[key]);
this.state = newControllerState.getState();
this._setInteractionState(interactionState);
if (changed) {
const oldViewState = this.controllerState && this.controllerState.getViewportProps();
if (this.onViewStateChange) {
this.onViewStateChange({viewState, interactionState: this._interactionState, oldViewState});
}
}
}
private _onTransition(params: {viewState: Record<string, any>, oldViewState: Record<string, any>}) {
this.onViewStateChange({...params, interactionState: this._interactionState});
}
private _setInteractionState(newStates: InteractionState) {
Object.assign(this._interactionState, newStates);
this.onStateChange(this._interactionState);
}
/* Event handlers */
// Default handler for the `panstart` event.
protected _onPanStart(event: MjolnirGestureEvent): boolean {
const pos = this.getCenter(event);
if (!this.isPointInBounds(pos, event)) {
return false;
}
let alternateMode = this.isFunctionKeyPressed(event) || event.rightButton || false;
if (this.invertPan || this.dragMode === 'pan') {
// invertPan is replaced by props.dragMode, keeping for backward compatibility
alternateMode = !alternateMode;
}
const newControllerState = this.controllerState[alternateMode ? 'panStart' : 'rotateStart']({
pos
});
this._panMove = alternateMode;
this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {isDragging: true});
return true;
}
// Default handler for the `panmove` and `panend` event.
protected _onPan(event: MjolnirGestureEvent): boolean {
if (!this.isDragging()) {
return false;
}
return this._panMove ? this._onPanMove(event) : this._onPanRotate(event);
}
protected _onPanEnd(event: MjolnirGestureEvent): boolean {
if (!this.isDragging()) {
return false;
}
return this._panMove ? this._onPanMoveEnd(event) : this._onPanRotateEnd(event);
}
// Default handler for panning to move.
// Called by `_onPan` when panning without function key pressed.
protected _onPanMove(event: MjolnirGestureEvent): boolean {
if (!this.dragPan) {
return false;
}
const pos = this.getCenter(event);
const newControllerState = this.controllerState.pan({pos});
this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {
isDragging: true,
isPanning: true
});
return true;
}
protected _onPanMoveEnd(event: MjolnirGestureEvent): boolean {
const {inertia} = this;
if (this.dragPan && inertia && event.velocity) {
const pos = this.getCenter(event);
const endPos: [number, number] = [
pos[0] + (event.velocityX * inertia) / 2,
pos[1] + (event.velocityY * inertia) / 2
];
const newControllerState = this.controllerState.pan({pos: endPos}).panEnd();
this.updateViewport(
newControllerState,
{
...this._getTransitionProps(),
transitionDuration: inertia,
transitionEasing: INERTIA_EASING
},
{
isDragging: false,
isPanning: true
}
);
} else {
const newControllerState = this.controllerState.panEnd();
this.updateViewport(newControllerState, null, {
isDragging: false,
isPanning: false
});
}
return true;
}
// Default handler for panning to rotate.
// Called by `_onPan` when panning with function key pressed.
protected _onPanRotate(event: MjolnirGestureEvent): boolean {
if (!this.dragRotate) {
return false;
}
const pos = this.getCenter(event);
const newControllerState = this.controllerState.rotate({pos});
this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {
isDragging: true,
isRotating: true
});
return true;
}
protected _onPanRotateEnd(event): boolean {
const {inertia} = this;
if (this.dragRotate && inertia && event.velocity) {
const pos = this.getCenter(event);
const endPos: [number, number] = [
pos[0] + (event.velocityX * inertia) / 2,
pos[1] + (event.velocityY * inertia) / 2
];
const newControllerState = this.controllerState.rotate({pos: endPos}).rotateEnd();
this.updateViewport(
newControllerState,
{
...this._getTransitionProps(),
transitionDuration: inertia,
transitionEasing: INERTIA_EASING
},
{
isDragging: false,
isRotating: true
}
);
} else {
const newControllerState = this.controllerState.rotateEnd();
this.updateViewport(newControllerState, null, {
isDragging: false,
isRotating: false
});
}
return true;
}
// Default handler for the `wheel` event.
protected _onWheel(event: MjolnirWheelEvent): boolean {
if (!this.scrollZoom) {
return false;
}
event.srcEvent.preventDefault();
const pos = this.getCenter(event);
if (!this.isPointInBounds(pos, event)) {
return false;
}
const {speed = 0.01, smooth = false} = this.scrollZoom === true ? {} : this.scrollZoom;
const {delta} = event;
// Map wheel delta to relative scale
let scale = 2 / (1 + Math.exp(-Math.abs(delta * speed)));
if (delta < 0 && scale !== 0) {
scale = 1 / scale;
}
const newControllerState = this.controllerState.zoom({pos, scale});
this.updateViewport(
newControllerState,
{...this._getTransitionProps({around: pos}), transitionDuration: smooth ? 250 : 1},
{
isZooming: true,
isPanning: true
}
);
return true;
}
protected _onTriplePanStart(event: MjolnirGestureEvent): boolean {
const pos = this.getCenter(event);
if (!this.isPointInBounds(pos, event)) {
return false;
}
const newControllerState = this.controllerState.rotateStart({pos});
this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {isDragging: true});
return true;
}
protected _onTriplePan(event: MjolnirGestureEvent): boolean {
if (!this.touchRotate) {
return false;
}
if (!this.isDragging()) {
return false;
}
const pos = this.getCenter(event);
pos[0] -= event.deltaX;
const newControllerState = this.controllerState.rotate({pos});
this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {
isDragging: true,
isRotating: true
});
return true;
}
protected _onTriplePanEnd(event: MjolnirGestureEvent): boolean {
if (!this.isDragging()) {
return false;
}
const {inertia} = this;
if (this.touchRotate && inertia && event.velocityY) {
const pos = this.getCenter(event);
const endPos: [number, number] = [pos[0], (pos[1] += (event.velocityY * inertia) / 2)];
const newControllerState = this.controllerState.rotate({pos: endPos});
this.updateViewport(
newControllerState,
{
...this._getTransitionProps(),
transitionDuration: inertia,
transitionEasing: INERTIA_EASING
},
{
isDragging: false,
isRotating: true
}
);
this.blockEvents(inertia);
} else {
const newControllerState = this.controllerState.rotateEnd();
this.updateViewport(newControllerState, null, {
isDragging: false,
isRotating: false
});
}
return true;
}
// Default handler for the `pinchstart` event.
protected _onPinchStart(event: MjolnirGestureEvent): boolean {
const pos = this.getCenter(event);
if (!this.isPointInBounds(pos, event)) {
return false;
}
const newControllerState = this.controllerState.zoomStart({pos}).rotateStart({pos});
// hack - hammer's `rotation` field doesn't seem to produce the correct angle
pinchEventWorkaround._startPinchRotation = event.rotation;
pinchEventWorkaround._lastPinchEvent = event;
this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {isDragging: true});
return true;
}
// Default handler for the `pinchmove` and `pinchend` events.
protected _onPinch(event: MjolnirGestureEvent): boolean {
if (!this.touchZoom && !this.touchRotate) {
return false;
}
if (!this.isDragging()) {
return false;
}
let newControllerState = this.controllerState;
if (this.touchZoom) {
const {scale} = event;
const pos = this.getCenter(event);
newControllerState = newControllerState.zoom({pos, scale});
}
if (this.touchRotate) {
const {rotation} = event;
newControllerState = newControllerState.rotate({
deltaAngleX: pinchEventWorkaround._startPinchRotation - rotation
});
}
this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {
isDragging: true,
isPanning: this.touchZoom,
isZooming: this.touchZoom,
isRotating: this.touchRotate
});
pinchEventWorkaround._lastPinchEvent = event;
return true;
}
protected _onPinchEnd(event: MjolnirGestureEvent): boolean {
if (!this.isDragging()) {
return false;
}
const {inertia} = this;
const {_lastPinchEvent} = pinchEventWorkaround;
if (this.touchZoom && inertia && _lastPinchEvent && event.scale !== _lastPinchEvent.scale) {
const pos = this.getCenter(event);
let newControllerState = this.controllerState.rotateEnd();
const z = Math.log2(event.scale);
const velocityZ =
(z - Math.log2(_lastPinchEvent.scale)) / (event.deltaTime - _lastPinchEvent.deltaTime);
const endScale = Math.pow(2, z + (velocityZ * inertia) / 2);
newControllerState = newControllerState.zoom({pos, scale: endScale}).zoomEnd();
this.updateViewport(
newControllerState,
{
...this._getTransitionProps({around: pos}),
transitionDuration: inertia,
transitionEasing: INERTIA_EASING
},
{
isDragging: false,
isPanning: this.touchZoom,
isZooming: this.touchZoom,
isRotating: false
}
);
this.blockEvents(inertia);
} else {
const newControllerState = this.controllerState.zoomEnd().rotateEnd();
this.updateViewport(newControllerState, null, {
isDragging: false,
isPanning: false,
isZooming: false,
isRotating: false
});
}
pinchEventWorkaround._startPinchRotation = null;
pinchEventWorkaround._lastPinchEvent = null;
return true;
}
// Default handler for the `doubletap` event.
protected _onDoubleTap(event: MjolnirGestureEvent): boolean {
if (!this.doubleClickZoom) {
return false;
}
const pos = this.getCenter(event);
if (!this.isPointInBounds(pos, event)) {
return false;
}
const isZoomOut = this.isFunctionKeyPressed(event);
const newControllerState = this.controllerState.zoom({pos, scale: isZoomOut ? 0.5 : 2});
this.updateViewport(newControllerState, this._getTransitionProps({around: pos}), {
isZooming: true,
isPanning: true
});
this.blockEvents(100);
return true;
}
// Default handler for the `keydown` event
protected _onKeyDown(event: MjolnirKeyEvent): boolean {
if (!this.keyboard) {
return false;
}
const funcKey = this.isFunctionKeyPressed(event);
// @ts-ignore
const {zoomSpeed, moveSpeed, rotateSpeedX, rotateSpeedY} = this.keyboard === true ? {} : this.keyboard;
const {controllerState} = this;
let newControllerState;
const interactionState: InteractionState = {};
switch (event.srcEvent.code) {
case 'Minus':
newControllerState = funcKey
? controllerState.zoomOut(zoomSpeed).zoomOut(zoomSpeed)
: controllerState.zoomOut(zoomSpeed);
interactionState.isZooming = true;
break;
case 'Equal':
newControllerState = funcKey
? controllerState.zoomIn(zoomSpeed).zoomIn(zoomSpeed)
: controllerState.zoomIn(zoomSpeed);
interactionState.isZooming = true;
break;
case 'ArrowLeft':
if (funcKey) {
newControllerState = controllerState.rotateLeft(rotateSpeedX);
interactionState.isRotating = true;
} else {
newControllerState = controllerState.moveLeft(moveSpeed);
interactionState.isPanning = true;
}
break;
case 'ArrowRight':
if (funcKey) {
newControllerState = controllerState.rotateRight(rotateSpeedX);
interactionState.isRotating = true;
} else {
newControllerState = controllerState.moveRight(moveSpeed);
interactionState.isPanning = true;
}
break;
case 'ArrowUp':
if (funcKey) {
newControllerState = controllerState.rotateUp(rotateSpeedY);
interactionState.isRotating = true;
} else {
newControllerState = controllerState.moveUp(moveSpeed);
interactionState.isPanning = true;
}
break;
case 'ArrowDown':
if (funcKey) {
newControllerState = controllerState.rotateDown(rotateSpeedY);
interactionState.isRotating = true;
} else {
newControllerState = controllerState.moveDown(moveSpeed);
interactionState.isPanning = true;
}
break;
default:
return false;
}
this.updateViewport(newControllerState, this._getTransitionProps(), interactionState);
return true;
}
protected _getTransitionProps(opts?: any): TransitionProps {
const {transition} = this;
if (!transition || !transition.transitionInterpolator) {
return NO_TRANSITION_PROPS;
}
// Enables Transitions on double-tap and key-down events.
return opts
? {
...transition,
transitionInterpolator: new LinearInterpolator({
...opts,
...(transition.transitionInterpolator as LinearInterpolator).opts,
makeViewport: this.controllerState.makeViewport
})
}
: transition;
}
} | the_stack |
import fs from "fs/promises";
import http from "http";
import path from "path";
import { promisify } from "util";
import { IncomingRequestCfProperties } from "@miniflare/core";
import {
Awaitable,
Clock,
Option,
OptionType,
Plugin,
PluginContext,
SetupResult,
defaultClock,
} from "@miniflare/shared";
import type { Attributes, Options } from "selfsigned";
import { RequestInfo, fetch } from "undici";
import { getAccessibleHosts } from "./helpers";
// Milliseconds in 1 day
const DAY = 86400000;
// Max age in days of self-signed certificate
const CERT_DAYS = 30;
// Max age in days of cf.json
const CF_DAYS = 30;
export interface HTTPPluginDefaults {
certRoot?: string;
cfPath?: string;
cfFetch?: boolean;
cfFetchEndpoint?: RequestInfo;
clock?: Clock;
}
const defaultCertRoot = path.resolve(".mf", "cert");
const defaultCfPath = path.resolve("node_modules", ".mf", "cf.json");
const defaultCfFetch = process.env.NODE_ENV !== "test";
const defaultCfFetchEndpoint = "https://workers.cloudflare.com/cf.json";
const defaultCf: IncomingRequestCfProperties = {
asn: 395747,
colo: "DFW",
city: "Austin",
region: "Texas",
regionCode: "TX",
metroCode: "635",
postalCode: "78701",
country: "US",
continent: "NA",
timezone: "America/Chicago",
latitude: "30.27130",
longitude: "-97.74260",
clientTcpRtt: 0,
httpProtocol: "HTTP/1.1",
requestPriority: "weight=192;exclusive=0",
tlsCipher: "AEAD-AES128-GCM-SHA256",
tlsVersion: "TLSv1.3",
tlsClientAuth: {
certIssuerDNLegacy: "",
certIssuerDN: "",
certPresented: "0",
certSubjectDNLegacy: "",
certSubjectDN: "",
certNotBefore: "",
certNotAfter: "",
certSerial: "",
certFingerprintSHA1: "",
certVerified: "NONE",
},
};
export interface ProcessedHTTPSOptions {
key?: string;
cert?: string;
ca?: string;
pfx?: string;
passphrase?: string;
}
export interface RequestMeta {
forwardedProto?: string;
realIp?: string;
cf?: IncomingRequestCfProperties;
}
export interface HTTPOptions {
host?: string;
port?: number;
open?: boolean | string;
https?: boolean | string;
httpsKey?: string;
httpsKeyPath?: string;
httpsCert?: string;
httpsCertPath?: string;
httpsCa?: string;
httpsCaPath?: string;
httpsPfx?: string;
httpsPfxPath?: string;
httpsPassphrase?: string;
cfFetch?: boolean | string;
metaProvider?: (req: http.IncomingMessage) => Awaitable<RequestMeta>;
liveReload?: boolean;
}
function valueOrFile(
value?: string,
filePath?: string
): Awaitable<string | undefined> {
return value ?? (filePath && fs.readFile(filePath, "utf8"));
}
export class HTTPPlugin extends Plugin<HTTPOptions> implements HTTPOptions {
@Option({
type: OptionType.STRING,
alias: "H",
description: "Host for HTTP(S) server to listen on",
fromWrangler: ({ miniflare }) => miniflare?.host,
})
host?: string;
@Option({
type: OptionType.NUMBER,
alias: "p",
description: "Port for HTTP(S) server to listen on",
fromWrangler: ({ miniflare }) => miniflare?.port,
})
port?: number;
@Option({
type: OptionType.BOOLEAN_STRING,
alias: "O",
description: "Automatically open browser to URL",
fromWrangler: ({ miniflare }) => miniflare?.open,
})
open?: boolean | string;
@Option({
type: OptionType.BOOLEAN_STRING,
description: "Enable self-signed HTTPS (with optional cert path)",
logName: "HTTPS",
fromWrangler: ({ miniflare }) =>
typeof miniflare?.https === "object" ? undefined : miniflare?.https,
})
https?: boolean | string;
@Option({ type: OptionType.NONE })
httpsKey?: string;
@Option({
type: OptionType.STRING,
name: "https-key",
description: "Path to PEM SSL key",
logName: "HTTPS Key",
fromWrangler: ({ miniflare }) =>
typeof miniflare?.https === "object" ? miniflare.https?.key : undefined,
})
httpsKeyPath?: string;
@Option({ type: OptionType.NONE })
httpsCert?: string;
@Option({
type: OptionType.STRING,
name: "https-cert",
description: "Path to PEM SSL cert chain",
logName: "HTTPS Cert",
fromWrangler: ({ miniflare }) =>
typeof miniflare?.https === "object" ? miniflare.https?.cert : undefined,
})
httpsCertPath?: string;
@Option({ type: OptionType.NONE })
httpsCa?: string;
@Option({
type: OptionType.STRING,
name: "https-ca",
description: "Path to SSL trusted CA certs",
logName: "HTTPS CA",
fromWrangler: ({ miniflare }) =>
typeof miniflare?.https === "object" ? miniflare.https?.ca : undefined,
})
httpsCaPath?: string;
@Option({ type: OptionType.NONE })
httpsPfx?: string;
@Option({
type: OptionType.STRING,
name: "https-pfx",
description: "Path to PFX/PKCS12 SSL key/cert chain",
logName: "HTTPS PFX",
fromWrangler: ({ miniflare }) =>
typeof miniflare?.https === "object" ? miniflare.https?.pfx : undefined,
})
httpsPfxPath?: string;
@Option({
type: OptionType.STRING,
description: "Passphrase to decrypt SSL files",
logName: "HTTPS Passphrase",
logValue: () => "**********",
fromWrangler: ({ miniflare }) =>
typeof miniflare?.https === "object"
? miniflare.https?.passphrase
: undefined,
})
httpsPassphrase?: string;
@Option({
type: OptionType.BOOLEAN_STRING,
description: "Path for cached Request cf object from Cloudflare",
negatable: true,
logName: "Request cf Object Fetch",
logValue(value: boolean | string) {
if (value === true) return path.relative("", defaultCfPath);
if (value === false) return undefined;
return path.relative("", value);
},
fromWrangler: ({ miniflare }) => miniflare?.cf_fetch,
})
cfFetch?: boolean | string;
@Option({ type: OptionType.NONE })
metaProvider?: (req: http.IncomingMessage) => Awaitable<RequestMeta>;
@Option({
type: OptionType.BOOLEAN,
description: "Reload HTML pages whenever worker is reloaded",
fromWrangler: ({ miniflare }) => miniflare?.live_reload,
})
liveReload?: boolean;
private readonly defaultCertRoot: string;
private readonly defaultCfPath: string;
private readonly defaultCfFetch: boolean;
private readonly cfFetchEndpoint: RequestInfo;
private readonly clock: Clock;
#cf = defaultCf;
readonly httpsEnabled: boolean;
#httpsOptions?: ProcessedHTTPSOptions;
constructor(
ctx: PluginContext,
options?: HTTPOptions,
private readonly defaults: HTTPPluginDefaults = {}
) {
super(ctx);
this.assignOptions(options);
this.defaultCertRoot = defaults.certRoot ?? defaultCertRoot;
this.defaultCfPath = defaults.cfPath ?? defaultCfPath;
this.defaultCfFetch = defaults.cfFetch ?? defaultCfFetch;
this.cfFetchEndpoint = defaults.cfFetchEndpoint ?? defaultCfFetchEndpoint;
this.clock = defaults.clock ?? defaultClock;
this.httpsEnabled = !!(
this.https ||
this.httpsKey ||
this.httpsKeyPath ||
this.httpsCert ||
this.httpsCertPath ||
this.httpsCa ||
this.httpsCaPath ||
this.httpsPfx ||
this.httpsPfxPath
);
}
getRequestMeta(req: http.IncomingMessage): Awaitable<RequestMeta> {
if (this.metaProvider) return this.metaProvider(req);
return { cf: this.#cf };
}
get httpsOptions(): ProcessedHTTPSOptions | undefined {
return this.#httpsOptions;
}
async setupCf(): Promise<void> {
// Default to enabling cfFetch if we're not testing
let cfPath = this.cfFetch ?? this.defaultCfFetch;
// If cfFetch is disabled or we're using a custom provider, don't fetch the
// cf object
if (!cfPath || this.metaProvider) return;
if (cfPath === true) cfPath = this.defaultCfPath;
// Determine whether to refetch cf.json, should do this if doesn't exist
// or expired
let refetch = true;
try {
// Try load cfPath, if this fails, we'll catch the error and refetch.
// If this succeeds, and the file is stale, that's fine: it's very likely
// we'll be fetching the same data anyways.
this.#cf = JSON.parse(await fs.readFile(cfPath, "utf8"));
const cfStat = await fs.stat(cfPath);
refetch = this.clock() - cfStat.mtimeMs > CF_DAYS * DAY;
} catch {}
// If no need to refetch, stop here, otherwise fetch
if (!refetch) return;
try {
const res = await fetch(this.cfFetchEndpoint);
const cfText = await res.text();
this.#cf = JSON.parse(cfText);
// Write cf so we can reuse it later
await fs.mkdir(path.dirname(cfPath), { recursive: true });
await fs.writeFile(cfPath, cfText, "utf8");
this.ctx.log.info("Updated Request cf object cache!");
} catch (e: any) {
this.ctx.log.error(e);
}
}
async setupHttps(): Promise<void> {
// If options are falsy, don't use HTTPS, no other HTTP setup required
if (!this.httpsEnabled) return;
// If https is true, use a self-signed certificate at default location
let https = this.https;
if (https === true) https = this.defaultCertRoot;
// If https is now a string, use a self-signed certificate
if (typeof https === "string") {
const keyPath = path.join(https, "key.pem");
const certPath = path.join(https, "cert.pem");
// Determine whether to regenerate self-signed certificate, should do this
// if doesn't exist or about to expire
let regenerate = true;
try {
const keyStat = await fs.stat(keyPath);
const certStat = await fs.stat(certPath);
const created = Math.max(keyStat.mtimeMs, certStat.mtimeMs);
regenerate = this.clock() - created > (CERT_DAYS - 2) * DAY;
} catch {}
// Generate self signed certificate if needed
if (regenerate) {
this.ctx.log.info("Generating new self-signed certificate...");
// selfsigned imports node-forge, which is a pretty big library.
// To reduce startup time, only load this dynamically when needed.
const selfSigned: typeof import("selfsigned") = require("selfsigned");
const certAttrs: Attributes = [
{ name: "commonName", value: "localhost" },
];
const certOptions: Options = {
algorithm: "sha256",
days: CERT_DAYS,
keySize: 2048,
extensions: [
{ name: "basicConstraints", cA: true },
{
name: "keyUsage",
keyCertSign: true,
digitalSignature: true,
nonRepudiation: true,
keyEncipherment: true,
dataEncipherment: true,
},
{
name: "extKeyUsage",
serverAuth: true,
clientAuth: true,
codeSigning: true,
timeStamping: true,
},
{
name: "subjectAltName",
altNames: [
{ type: 2, value: "localhost" },
...getAccessibleHosts().map((ip) => ({ type: 7, ip })),
],
},
],
};
const cert = await promisify(selfSigned.generate)(
certAttrs,
certOptions
);
// Write cert so we can reuse it later
await fs.mkdir(https, { recursive: true });
await fs.writeFile(keyPath, cert.private, "utf8");
await fs.writeFile(certPath, cert.cert, "utf8");
}
this.httpsKeyPath = keyPath;
this.httpsCertPath = certPath;
}
// Load custom HTTPS options
this.#httpsOptions = {
key: await valueOrFile(this.httpsKey, this.httpsKeyPath),
cert: await valueOrFile(this.httpsCert, this.httpsCertPath),
ca: await valueOrFile(this.httpsCa, this.httpsCaPath),
pfx: await valueOrFile(this.httpsPfx, this.httpsPfxPath),
passphrase: this.httpsPassphrase,
};
}
async setup(): Promise<SetupResult> {
// noinspection ES6MissingAwait
void this.setupCf();
await this.setupHttps();
return {};
}
} | the_stack |
import { blue, cyan, magenta } from '../../utils/colors';
import { QueryResultValidator } from '../../query-tree';
import { arrayToObject, flatMap } from '../../utils/utils';
function stringify(val: any) {
if (val === undefined) {
return 'undefined';
}
return JSON.stringify(val);
}
export namespace aqlConfig {
export let enableIndentationForCode = false;
}
const INDENTATION = ' ';
/**
* Like indent(), but does not indent the first line
*/
function indentLineBreaks(val: string, level: number) {
if (level == 0) {
return val;
}
const indent = INDENTATION.repeat(level);
return val.replace(/\n/g, '\n' + indent);
}
export class AQLCodeBuildingContext {
private readonly boundValues: any[] = [];
private readonly boundCollectionNames = new Set<string>();
private variableBindings = new Map<AQLVariable, string>();
private preExecInjectedVariablesMap = new Map<AQLQueryResultVariable, string>();
private nextIndexPerLabel = new Map<string, number>();
public indentationLevel = 0;
private static getBoundValueName(index: number) {
return 'var' + (index + 1);
}
private static DEFAULT_LABEL = 'tmp';
private static getSafeLabel(label: string | undefined): string {
if (label) {
// avoid collisions with collection names, functions and keywords
// (v_ will never collide with a collection name because collection names are pluralized and v is not a plural)
label = 'v_' + label;
}
if (!label || !aql.isSafeIdentifier(label)) {
// bail out
label = AQLCodeBuildingContext.DEFAULT_LABEL;
}
// we prefixed with v_, so we can't collide with a keyword -> no need for ``
return label;
}
private static getVarName(label: string, index: number) {
return label + (index + 1);
}
bindValue(value: any): string {
const index = this.boundValues.length;
if (value === undefined) {
// AQL does not know about "undefined" and would complain about a missing value for bind parameter.
value = null;
}
this.boundValues.push(value);
return AQLCodeBuildingContext.getBoundValueName(index);
}
bindCollectionName(collectionName: string): string {
this.boundCollectionNames.add(collectionName);
return '@@' + collectionName;
}
getOrAddVariable(token: AQLVariable): string {
const existingBinding = this.variableBindings.get(token);
if (existingBinding != undefined) {
return existingBinding;
}
const safeLabel = AQLCodeBuildingContext.getSafeLabel(token.label);
const newIndex = this.nextIndexPerLabel.get(safeLabel) || 0;
this.nextIndexPerLabel.set(safeLabel, newIndex + 1);
const newBinding = AQLCodeBuildingContext.getVarName(safeLabel, newIndex);
this.variableBindings.set(token, newBinding);
if (token instanceof AQLQueryResultVariable) {
this.preExecInjectedVariablesMap.set(token, newBinding);
}
return newBinding;
}
getBoundValueMap() {
let result: { [key: string]: unknown } = {};
for (let i = 0; i < this.boundValues.length; i++) {
const name = AQLCodeBuildingContext.getBoundValueName(i);
result[name] = this.boundValues[i];
}
for (const collectionName of this.boundCollectionNames) {
result['@' + collectionName] = collectionName;
}
return result;
}
getPreExecInjectedVariablesMap(): Map<AQLQueryResultVariable, string> {
return this.preExecInjectedVariablesMap;
}
}
export abstract class AQLFragment {
toString(): string {
return this.toStringWithContext(new AQLCodeBuildingContext());
}
toColoredString(): string {
return this.toColoredStringWithContext(new AQLCodeBuildingContext());
}
getCode() {
const context = new AQLCodeBuildingContext();
const code = this.getCodeWithContext(context);
return {
code,
boundValues: context.getBoundValueMap(),
usedResultVariables: context.getPreExecInjectedVariablesMap()
};
}
isEmpty() {
return false;
}
abstract toStringWithContext(context: AQLCodeBuildingContext): string;
abstract toColoredStringWithContext(context: AQLCodeBuildingContext): string;
abstract getCodeWithContext(context: AQLCodeBuildingContext): string;
}
export class AQLCodeFragment extends AQLFragment {
constructor(public readonly aql: string) {
super();
}
isEmpty() {
return !this.aql.length;
}
toStringWithContext(context: AQLCodeBuildingContext): string {
return indentLineBreaks(this.aql, context.indentationLevel);
}
toColoredStringWithContext(context: AQLCodeBuildingContext): string {
return indentLineBreaks(this.aql, context.indentationLevel);
}
getCodeWithContext(context: AQLCodeBuildingContext): string {
if (aqlConfig.enableIndentationForCode) {
return indentLineBreaks(this.aql, context.indentationLevel);
} else {
return this.aql;
}
}
}
export class AQLVariable extends AQLFragment {
constructor(public readonly label?: string) {
super();
}
getCodeWithContext(context: AQLCodeBuildingContext): string {
return context.getOrAddVariable(this);
}
toStringWithContext(context: AQLCodeBuildingContext): string {
return this.getCodeWithContext(context);
}
toColoredStringWithContext(context: AQLCodeBuildingContext): string {
return magenta(this.toStringWithContext(context));
}
}
export class AQLQueryResultVariable extends AQLVariable {
getCodeWithContext(context: AQLCodeBuildingContext): string {
return '@' + super.getCodeWithContext(context);
}
}
export class AQLBoundValue extends AQLFragment {
constructor(public readonly value: any) {
super();
}
toStringWithContext(context: AQLCodeBuildingContext): string {
return indentLineBreaks(stringify(this.value), context.indentationLevel);
}
toColoredStringWithContext(): string {
return cyan(this.toString());
}
getCodeWithContext(context: AQLCodeBuildingContext): string {
return '@' + context.bindValue(this.value);
}
}
export class AQLCollection extends AQLFragment {
constructor(public readonly collectionName: string) {
super();
if (typeof collectionName !== 'string') {
throw new Error(
`Tried to create AQLCollection with a parameter that is not a string but ${typeof collectionName}`
);
}
// test this here so we are sure we can use it safely as bind parameter name
if (!collectionName.match(/^[a-zA-Z0-9_]+$/)) {
throw new Error(`Collection name does not follow conventions: ${JSON.stringify(collectionName)}`);
}
// no need for these, so be safe
if (collectionName.startsWith('_')) {
throw new Error(`Tried to create AQLCollection with system collection (starts with _): ${collectionName}`);
}
if (collectionName.startsWith('v_')) {
// catch this early - shouldn't happen (v is not a plural), and could cause collisions with variables
throw new Error(`Collections can't start with v_`);
}
}
toStringWithContext(context: AQLCodeBuildingContext): string {
return this.collectionName;
}
toColoredStringWithContext(): string {
return blue(this.collectionName);
}
getCodeWithContext(context: AQLCodeBuildingContext): string {
return context.bindCollectionName(this.collectionName);
}
}
export class AQLCompoundFragment extends AQLFragment {
constructor(public readonly fragments: ReadonlyArray<AQLFragment>) {
super();
}
isEmpty() {
return this.fragments.length == 0 || this.fragments.every(fr => fr.isEmpty());
}
toStringWithContext(context: AQLCodeBuildingContext): string {
return this.fragments.map(fr => fr.toStringWithContext(context)).join('');
}
toColoredStringWithContext(context: AQLCodeBuildingContext): string {
return this.fragments.map(fr => fr.toColoredStringWithContext(context)).join('');
}
getCodeWithContext(context: AQLCodeBuildingContext): string {
// loop and += seems to be faster than join()
let code = '';
for (const fragment of this.fragments) {
code += fragment.getCodeWithContext(context);
}
return code;
}
}
export class AQLIndentationFragment extends AQLFragment {
constructor(public readonly fragment: AQLFragment) {
super();
}
isEmpty() {
return this.fragment.isEmpty();
}
toStringWithContext(context: AQLCodeBuildingContext): string {
context.indentationLevel++;
const result = INDENTATION + this.fragment.toStringWithContext(context);
context.indentationLevel--;
return result;
}
toColoredStringWithContext(context: AQLCodeBuildingContext): string {
context.indentationLevel++;
const result = INDENTATION + this.fragment.toColoredStringWithContext(context);
context.indentationLevel--;
return result;
}
getCodeWithContext(context: AQLCodeBuildingContext): string {
if (!aqlConfig.enableIndentationForCode) {
return this.fragment.getCodeWithContext(context);
}
context.indentationLevel++;
const code = INDENTATION + this.fragment.getCodeWithContext(context);
context.indentationLevel--;
return code;
}
}
export function aql(
strings: ReadonlyArray<string>,
...values: (AQLFragment | string | number | boolean)[]
): AQLFragment {
let snippets = [...strings];
let fragments: AQLFragment[] = [];
while (snippets.length || values.length) {
if (snippets.length) {
fragments.push(new AQLCodeFragment(snippets.shift()!));
}
if (values.length) {
const value = values.shift();
if (value instanceof AQLCompoundFragment) {
fragments.push(...value.fragments);
} else if (value instanceof AQLFragment) {
fragments.push(value);
} else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
fragments.push(new AQLBoundValue(value));
} else {
throw new Error(`aql: Received a value that is neither an AQLFragment, nor a primitive`);
}
}
}
return new AQLCompoundFragment(fragments);
}
export namespace aql {
export function concat(fragments: ReadonlyArray<AQLFragment>) {
return new AQLCompoundFragment(fragments);
}
export function join(fragments: AQLFragment[], separator: AQLFragment): AQLFragment {
const newFragments: AQLFragment[] = [];
let isFirst = true;
for (const fragment of fragments) {
if (fragment.isEmpty()) {
continue;
}
if (!isFirst) {
newFragments.push(separator);
}
isFirst = false;
newFragments.push(fragment);
}
return new AQLCompoundFragment(newFragments);
}
export function code(code: string): AQLFragment {
return new AQLCodeFragment(code);
}
export function lines(...fragments: AQLFragment[]) {
return join(fragments, aql`\n`);
}
export function indent(fragment: AQLFragment) {
return new AQLIndentationFragment(fragment);
}
export function variable(label?: string): AQLFragment {
return new AQLVariable(label);
}
export function value(value: any): AQLFragment {
return new AQLBoundValue(value);
}
export function queryResultVariable(label?: string): AQLQueryResultVariable {
return new AQLQueryResultVariable(label);
}
export function collection(name: string): AQLFragment {
return new AQLCollection(name);
}
export function identifier(name: string): AQLFragment {
if (!isSafeIdentifier(name)) {
throw new Error(`Possibly invalid/unsafe identifier in AQL: ${name}`);
}
// could always collide with a (future) keyword, so wrap in ``
return code('`' + name + '`');
}
/**
* Should be used when fairly certain that string can't be malicious
*
* As the string is json-encoded, it *should* be fine in any case, but still, user-supplied strings in queries is scary
*/
export function string(str: string): AQLFragment {
return code(JSON.stringify(str));
}
export function integer(number: number): AQLFragment {
return code(JSON.stringify(Number(number)));
}
/**
* Caution: should only use in .identifier() and NOT .code() because it does not account for keywords
*/
export function isSafeIdentifier(str: string) {
return typeof str == 'string' && str.match(/^[a-zA-Z0-9_]+$/);
}
}
//TODO Refactor. AQLCompoundQuery isn't a real AQLFragment.
/**
* A node in an AQL transaction tree
*
* This is an intermediate representation in the process of converting a query tree to an AQL transaction. The
* transaction tree's root is the root query. Children of a transaction node are the direct preExec queries of a query.
* Thus, the query tree is reduced to WithPreExecQueryNodes as nodes, all other kinds of nodes are already processed
* into AQLFragments.
*/
export class AQLCompoundQuery extends AQLFragment {
constructor(
public readonly preExecQueries: AQLCompoundQuery[],
public readonly aqlQuery: AQLFragment,
public readonly resultVar: AQLQueryResultVariable | undefined,
public readonly resultValidator: QueryResultValidator | undefined,
public readonly readAccessedCollections: string[],
public readonly writeAccessedCollections: string[]
) {
super();
}
/**
* Gets the linear AQL transaction for this transaction tree
*
* The returned transaction steps are to be executed sequentially.
*/
getExecutableQueries(): AQLExecutableQuery[] {
const resultVarToNameMap = new Map<AQLQueryResultVariable, string>();
return this.getExecutableQueriesRecursive(resultVarToNameMap);
}
private getExecutableQueriesRecursive(
resultVarToNameMap: Map<AQLQueryResultVariable, string>
): AQLExecutableQuery[] {
const executableQueries = flatMap(this.preExecQueries, aqlQuery =>
aqlQuery.getExecutableQueriesRecursive(resultVarToNameMap)
);
const { code, boundValues, usedResultVariables } = this.aqlQuery.getCode();
const usedResultNames: { [p: string]: string } = {};
usedResultVariables.forEach((bindParamName, aqlVariable) => {
const usedResultName = resultVarToNameMap.get(aqlVariable);
if (!usedResultName) {
throw new Error(`Name for query result variable ${aqlVariable} not found.`);
}
usedResultNames[usedResultName] = bindParamName;
});
let queryResultName = undefined;
if (this.resultVar) {
queryResultName = 'query_result_' + resultVarToNameMap.size;
resultVarToNameMap.set(this.resultVar, queryResultName);
}
let queryResultValidator = undefined;
if (this.resultValidator) {
queryResultValidator = {
[this.resultValidator.getValidatorName()]: this.resultValidator.getValidatorData()
};
}
const executableQuery = new AQLExecutableQuery(
code,
boundValues,
usedResultNames,
queryResultName,
queryResultValidator
);
return [...executableQueries, executableQuery];
}
//TODO Refactor the following three methods. AQLCompoundQuery isn't a real AQLFragment.
//TODO Include read/write accessed collections in output
toStringWithContext(context: AQLCodeBuildingContext): string {
let descriptions = this.preExecQueries.map(aqlQuery => aqlQuery.toStringWithContext(context));
const varDescription = this.resultVar ? this.resultVar.toStringWithContext(context) + ' = ' : '';
const validatorDescription = this.resultValidator ? ' validate result ' + this.resultValidator.describe() : '';
const execDescription =
varDescription +
'execute(\n' +
aql.indent(this.aqlQuery).toStringWithContext(context) +
'\n)' +
validatorDescription +
';';
descriptions.push(execDescription);
return descriptions.join('\n');
}
toColoredStringWithContext(context: AQLCodeBuildingContext): string {
let descriptions = this.preExecQueries.map(aqlQuery => aqlQuery.toColoredStringWithContext(context));
const varDescription = this.resultVar ? this.resultVar.toColoredStringWithContext(context) + ' = ' : '';
const validatorDescription = this.resultValidator ? ' validate result ' + this.resultValidator.describe() : '';
const execDescription =
varDescription +
'execute(\n' +
aql.indent(this.aqlQuery).toColoredStringWithContext(context) +
'\n)' +
validatorDescription +
';';
descriptions.push(execDescription);
return descriptions.join('\n');
}
getCodeWithContext(context: AQLCodeBuildingContext): string {
throw new Error('Unsupported Operation. AQLCompoundQuery can not provide a single AQL statement.');
}
}
/**
* A step in an AQL transaction
*/
export class AQLExecutableQuery {
constructor(
public readonly code: string,
public readonly boundValues: { [p: string]: any },
public readonly usedPreExecResultNames: { [p: string]: string },
public readonly resultName?: string,
public readonly resultValidator?: { [name: string]: any }
) {}
} | the_stack |
/// <reference types="node" />
declare class AdmZip {
/**
* @param fileNameOrRawData If provided, reads an existing archive. Otherwise creates a new, empty archive.
*/
constructor(fileNameOrRawData?: string | Buffer);
/**
* Extracts the given entry from the archive and returns the content.
* @param entry The full path of the entry or a `IZipEntry` object.
* @return `Buffer` or `null` in case of error.
*/
readFile(entry: string | AdmZip.IZipEntry): Buffer | null;
/**
* Asynchronous `readFile`.
* @param entry The full path of the entry or a `IZipEntry` object.
* @param callback Called with a `Buffer` or `null` in case of error.
*/
readFileAsync(entry: string | AdmZip.IZipEntry, callback: (data: Buffer | null, err: string) => any): void;
/**
* Extracts the given entry from the archive and returns the content as
* plain text in the given encoding.
* @param entry The full path of the entry or a `IZipEntry` object.
* @param encoding If no encoding is specified `"utf8"` is used.
*/
readAsText(fileName: string | AdmZip.IZipEntry, encoding?: string): string;
/**
* Asynchronous `readAsText`.
* @param entry The full path of the entry or a `IZipEntry` object.
* @param callback Called with the resulting string.
* @param encoding If no encoding is specified `"utf8"` is used.
*/
readAsTextAsync(fileName: string | AdmZip.IZipEntry, callback: (data: string, err: string) => any, encoding?: string): void;
/**
* Remove the entry from the file or the entry and all its nested directories
* and files if the given entry is a directory.
* @param entry The full path of the entry or a `IZipEntry` object.
*/
deleteFile(entry: string | AdmZip.IZipEntry): void;
/**
* Adds a comment to the zip. The zip must be rewritten after
* adding the comment.
* @param comment Content of the comment.
*/
addZipComment(comment: string): void;
/**
* @return The zip comment.
*/
getZipComment(): string;
/**
* Adds a comment to a specified file or `IZipEntry`. The zip must be rewritten after
* adding the comment.
* The comment cannot exceed 65535 characters in length.
* @param entry The full path of the entry or a `IZipEntry` object.
* @param comment The comment to add to the entry.
*/
addZipEntryComment(entry: string | AdmZip.IZipEntry, comment: string): void;
/**
* Returns the comment of the specified entry.
* @param entry The full path of the entry or a `IZipEntry` object.
* @return The comment of the specified entry.
*/
getZipEntryComment(entry: string | AdmZip.IZipEntry): string;
/**
* Updates the content of an existing entry inside the archive. The zip
* must be rewritten after updating the content.
* @param entry The full path of the entry or a `IZipEntry` object.
* @param content The entry's new contents.
*/
updateFile(entry: string | AdmZip.IZipEntry, content: Buffer): void;
/**
* Adds a file from the disk to the archive.
* @param localPath Path to a file on disk.
* @param zipPath Path to a directory in the archive. Defaults to the empty
* string.
* @param zipName Name for the file.
*/
addLocalFile(localPath: string, zipPath?: string, zipName?: string): void;
/**
* Adds a local directory and all its nested files and directories to the
* archive.
* @param localPath Path to a folder on disk.
* @param zipPath Path to a folder in the archive. Default: `""`.
* @param filter RegExp or Function if files match will be included.
*/
addLocalFolder(localPath: string, zipPath?: string, filter?: RegExp | ((filename: string) => boolean)): void;
/**
* Allows you to create a entry (file or directory) in the zip file.
* If you want to create a directory the `entryName` must end in `"/"` and a `null`
* buffer should be provided.
* @param entryName Entry path.
* @param content Content to add to the entry; must be a 0-length buffer
* for a directory.
* @param comment Comment to add to the entry.
* @param attr Attribute to add to the entry.
*/
addFile(entryName: string, data: Buffer, comment?: string, attr?: number): void;
/**
* Returns an array of `IZipEntry` objects representing the files and folders
* inside the archive.
*/
getEntries(): AdmZip.IZipEntry[];
/**
* Returns a `IZipEntry` object representing the file or folder specified by `name`.
* @param name Name of the file or folder to retrieve.
* @return The entry corresponding to the `name`.
*/
getEntry(name: string): AdmZip.IZipEntry | null;
/**
* Extracts the given entry to the given `targetPath`.
* If the entry is a directory inside the archive, the entire directory and
* its subdirectories will be extracted.
* @param entry The full path of the entry or a `IZipEntry` object.
* @param targetPath Target folder where to write the file.
* @param maintainEntryPath If maintainEntryPath is `true` and the entry is
* inside a folder, the entry folder will be created in `targetPath` as
* well. Default: `true`.
* @param overwrite If the file already exists at the target path, the file
* will be overwriten if this is `true`. Default: `false`.
*/
extractEntryTo(
entryPath: string | AdmZip.IZipEntry,
targetPath: string,
maintainEntryPath?: boolean,
overwrite?: boolean,
): boolean;
/**
* Extracts the entire archive to the given location.
* @param targetPath Target location.
* @param overwrite If the file already exists at the target path, the file
* will be overwriten if this is `true`. Default: `false`.
*/
extractAllTo(targetPath: string, overwrite?: boolean): void;
/**
* Extracts the entire archive to the given location.
* @param targetPath Target location.
* @param overwrite If the file already exists at the target path, the file
* will be overwriten if this is `true`. Default: `false`.
* @param callback The callback function will be called after extraction.
*/
extractAllToAsync(targetPath: string, overwrite?: boolean, callback?: (error: Error) => void): void;
/**
* Writes the newly created zip file to disk at the specified location or
* if a zip was opened and no `targetFileName` is provided, it will
* overwrite the opened zip.
*/
writeZip(targetFileName?: string, callback?: (error: Error | null) => void): void;
/**
* Returns the content of the entire zip file.
*/
toBuffer(): Buffer;
/**
* Asynchronously returns the content of the entire zip file.
* @param onSuccess called with the content of the zip file, once it has been generated.
* @param onFail unused.
* @param onItemStart called before an entry is compressed.
* @param onItemEnd called after an entry is compressed.
*/
toBuffer(
onSuccess: (buffer: Buffer) => void,
onFail?: (...args: any[]) => void,
onItemStart?: (name: string) => void,
onItemEnd?: (name: string) => void,
): void;
/**
* Test the archive.
*/
test(): boolean;
}
declare namespace AdmZip {
/**
* The `IZipEntry` is more than a structure representing the entry inside the
* zip file. Beside the normal attributes and headers a entry can have, the
* class contains a reference to the part of the file where the compressed
* data resides and decompresses it when requested. It also compresses the
* data and creates the headers required to write in the zip file.
*/
// disable warning about the I-prefix in interface name to prevent breaking stuff for users without a major bump
// tslint:disable-next-line:interface-name
interface IZipEntry {
/**
* Represents the full name and path of the file
*/
entryName: string;
readonly rawEntryName: Buffer;
/**
* Extra data associated with this entry.
*/
extra: Buffer;
/**
* Entry comment.
*/
comment: string;
readonly name: string;
/**
* Read-Only property that indicates the type of the entry.
*/
readonly isDirectory: boolean;
/**
* Get the header associated with this ZipEntry.
*/
readonly header: EntryHeader;
attr: number;
/**
* Retrieve the compressed data for this entry. Note that this may trigger
* compression if any properties were modified.
*/
getCompressedData(): Buffer;
/**
* Asynchronously retrieve the compressed data for this entry. Note that
* this may trigger compression if any properties were modified.
*/
getCompressedDataAsync(callback: (data: Buffer) => void): void;
/**
* Set the (uncompressed) data to be associated with this entry.
*/
setData(value: string | Buffer): void;
/**
* Get the decompressed data associated with this entry.
*/
getData(): Buffer;
/**
* Asynchronously get the decompressed data associated with this entry.
*/
getDataAsync(callback: (data: Buffer, err: string) => any): void;
/**
* Returns the CEN Entry Header to be written to the output zip file, plus
* the extra data and the entry comment.
*/
packHeader(): Buffer;
/**
* Returns a nicely formatted string with the most important properties of
* the ZipEntry.
*/
toString(): string;
}
interface EntryHeader {
made: number;
version: number;
flags: number;
method: number;
time: Date;
crc: number;
compressedSize: number;
size: number;
fileNameLength: number;
extraLength: number;
commentLength: number;
diskNumStart: number;
inAttr: number;
attr: number;
offset: number;
readonly encripted: boolean;
readonly entryHeaderSize: number;
readonly realDataOffset: number;
readonly dataHeader: DataHeader;
loadDataHeaderFromBinary(data: Buffer): void;
loadFromBinary(data: Buffer): void;
dataHeaderToBinary(): Buffer;
entryHeaderToBinary(): Buffer;
toString(): string;
}
interface DataHeader {
version: number;
flags: number;
method: number;
time: number;
crc: number;
compressedSize: number;
size: number;
fnameLen: number;
extraLen: number;
}
}
export = AdmZip; | the_stack |
import {
AttributeContextParameters,
CdmAttributeContext,
CdmCollection,
CdmConstantEntityDefinition,
CdmCorpusContext,
CdmCorpusDefinition,
CdmDocumentDefinition,
CdmEntityReference,
CdmObject,
CdmObjectDefinition,
CdmObjectReference,
cdmObjectType,
CdmParameterDefinition,
CdmTraitDefinition,
CdmTraitReference,
copyOptions,
isEntityAttributeDefinition,
isEntityDefinition,
resolveContext,
ResolvedAttributeSet,
ResolvedAttributeSetBuilder,
ResolvedTrait,
ResolvedTraitSet,
ResolvedTraitSetBuilder,
resolveOptions,
SymbolSet,
VisitCallback
} from '../internal';
import { PersistenceLayer } from '../Persistence';
import { CdmJsonType } from '../Persistence/CdmFolder/types';
export abstract class CdmObjectBase implements CdmObject {
public inDocument: CdmDocumentDefinition;
public ID: number;
public objectType: cdmObjectType;
public ctx: CdmCorpusContext;
public get atCorpusPath(): string {
if (!this.inDocument) {
return `NULL:/NULL/${this.declaredPath ? this.declaredPath : ''}`;
} else {
return `${this.inDocument.atCorpusPath}/${this.declaredPath ? this.declaredPath : ''}`;
}
}
/**
* @internal
*/
public traitCache: Map<string, ResolvedTraitSetBuilder>;
/**
* @internal
*/
public declaredPath: string;
public owner: CdmObject;
private resolvingTraits: boolean = false;
constructor(ctx: CdmCorpusContext) {
this.ID = CdmCorpusDefinition.nextID();
this.ctx = ctx;
}
public static get objectType(): cdmObjectType {
return;
}
/**
* @deprecated
*/
public static instanceFromData<T extends CdmObject>(...args: any[]): T {
const objectType: cdmObjectType = this.objectType;
const persistenceType: string = 'CdmFolder';
return PersistenceLayer.fromData(...args, objectType, persistenceType);
}
/**
* @internal
*/
public static visitArray(items: CdmCollection<CdmObject>, path: string, preChildren: VisitCallback, postChildren: VisitCallback): boolean {
// let bodyCode = () =>
{
let result: boolean = false;
if (items) {
const lItem: number = items.length;
for (let iItem: number = 0; iItem < lItem; iItem++) {
const element: CdmObject = items.allItems[iItem];
if (element) {
if (element.visit(path, preChildren, postChildren)) {
result = true;
break;
}
}
}
}
return result;
}
// return p.measure(bodyCode);
}
/**
* @internal
*/
public static resolvedTraitToTraitRef(resOpt: resolveOptions, rt: ResolvedTrait): CdmTraitReference {
let traitRef: CdmTraitReference;
if (rt.parameterValues && rt.parameterValues.length) {
traitRef = rt.trait.ctx.corpus.MakeObject(cdmObjectType.traitRef, rt.traitName, false);
const l: number = rt.parameterValues.length;
if (l === 1) {
// just one argument, use the shortcut syntax
let val: string | object | CdmObject = CdmObjectBase.protectParameterValues(resOpt, rt.parameterValues.values[0]);
if (val !== undefined) {
traitRef.arguments.push(undefined, val);
}
} else {
for (let i: number = 0; i < l; i++) {
const param: CdmParameterDefinition = rt.parameterValues.fetchParameterAtIndex(i);
let val: string | object | CdmObject = CdmObjectBase.protectParameterValues(resOpt, rt.parameterValues.values[i]);
if (val !== undefined) {
traitRef.arguments.push(param.name, val);
}
}
}
} else {
traitRef = rt.trait.ctx.corpus.MakeObject(cdmObjectType.traitRef, rt.traitName, true);
}
if (resOpt.saveResolutionsOnCopy) {
// used to localize references between documents
traitRef.explicitReference = rt.trait;
traitRef.inDocument = (rt.trait as CdmTraitDefinition).inDocument;
}
// always make it a property when you can, however the dataFormat traits should be left alone
// also the wellKnown is the first constrained list that uses the datatype to hold the table instead of the default value property.
// so until we figure out how to move the enums away from default value, show that trait too
if (rt.trait.associatedProperties && !rt.trait.isDerivedFrom('is.dataFormat', resOpt) && rt.trait.traitName !== 'is.constrainedList.wellKnown') {
traitRef.isFromProperty = true;
}
return traitRef;
}
public abstract isDerivedFrom(baseDef: string, resOpt?: resolveOptions): boolean;
public abstract copy(resOpt?: resolveOptions, host?: CdmObject): CdmObject;
public abstract validate(): boolean;
public abstract getObjectType(): cdmObjectType;
public abstract fetchObjectDefinitionName(): string;
public abstract fetchObjectDefinition<T extends CdmObjectDefinition>(resOpt: resolveOptions): T;
public abstract createSimpleReference(resOpt: resolveOptions): CdmObjectReference;
/**
* @internal
*/
public abstract createPortableReference(resOpt: resolveOptions): CdmObjectReference;
/**
* @deprecated
*/
public copyData(resOpt: resolveOptions, options?: copyOptions): CdmJsonType {
const persistenceType: string = 'CdmFolder';
if (resOpt == null) {
resOpt = new resolveOptions(this, this.ctx.corpus.defaultResolutionDirectives);
}
if (options == null) {
options = new copyOptions();
}
return PersistenceLayer.toData(this, resOpt, options, persistenceType);
}
/**
* @internal
*/
public constructResolvedTraits(rtsb: ResolvedTraitSetBuilder, resOpt: resolveOptions): void {
// let bodyCode = () =>
// return p.measure(bodyCode);
}
/**
* @internal
*/
public constructResolvedAttributes(resOpt: resolveOptions, under?: CdmAttributeContext): ResolvedAttributeSetBuilder {
// let bodyCode = () =>
{
return undefined;
}
// return p.measure(bodyCode);
}
/**
* @internal
*/
public fetchResolvedTraits(resOpt: resolveOptions): ResolvedTraitSet {
// let bodyCode = () =>
{
const wasPreviouslyResolving: boolean = this.ctx.corpus.isCurrentlyResolving;
this.ctx.corpus.isCurrentlyResolving = true;
if (!resOpt) {
resOpt = new resolveOptions(this, this.ctx.corpus.defaultResolutionDirectives);
}
const kind: string = 'rtsb';
const ctx: resolveContext = this.ctx as resolveContext;
let cacheTagA: string = ctx.corpus.createDefinitionCacheTag(resOpt, this, kind);
let rtsbAll: ResolvedTraitSetBuilder;
if (!this.traitCache) {
this.traitCache = new Map<string, ResolvedTraitSetBuilder>();
} else {
rtsbAll = cacheTagA ? this.traitCache.get(cacheTagA) : undefined;
}
// store the previous symbol set, we will need to add it with
// children found from the constructResolvedTraits call
const currSymbolRefSet: SymbolSet = resOpt.symbolRefSet || new SymbolSet();
resOpt.symbolRefSet = new SymbolSet();
if (!rtsbAll) {
rtsbAll = new ResolvedTraitSetBuilder();
if (!this.resolvingTraits) {
this.resolvingTraits = true;
this.constructResolvedTraits(rtsbAll, resOpt);
this.resolvingTraits = false;
}
const objDef: CdmObjectDefinition = this.fetchObjectDefinition(resOpt);
if (objDef !== undefined) {
// register set of possible docs
ctx.corpus.registerDefinitionReferenceSymbols(objDef, kind, resOpt.symbolRefSet);
if (rtsbAll.rts === undefined) {
// nothing came back, but others will assume there is a set in this builder
rtsbAll.rts = new ResolvedTraitSet(resOpt);
}
// get the new cache tag now that we have the list of docs
cacheTagA = ctx.corpus.createDefinitionCacheTag(resOpt, this, kind);
if (cacheTagA) {
this.traitCache.set(cacheTagA, rtsbAll);
}
}
} else {
// cache was found
// get the SymbolSet of refereces for this cached object
const key: string = CdmCorpusDefinition.createCacheKeyFromObject(this, kind);
resOpt.symbolRefSet = ctx.corpus.definitionReferenceSymbols.get(key);
}
// merge child symbols set with current
currSymbolRefSet.merge(resOpt.symbolRefSet);
resOpt.symbolRefSet = currSymbolRefSet;
this.ctx.corpus.isCurrentlyResolving = wasPreviouslyResolving;
return rtsbAll.rts;
}
// return p.measure(bodyCode);
}
/**
* @internal
*/
public fetchObjectFromCache(resOpt: resolveOptions, acpInContext?: AttributeContextParameters): ResolvedAttributeSetBuilder {
const kind: string = 'rasb';
const ctx: resolveContext = this.ctx as resolveContext; // what it actually is
const cacheTag: string = ctx.corpus.createDefinitionCacheTag(resOpt, this, kind, acpInContext ? 'ctx' : '');
return cacheTag ? ctx.attributeCache.get(cacheTag) : undefined;
}
/**
* @internal
*/
public fetchResolvedAttributes(resOpt?: resolveOptions, acpInContext?: AttributeContextParameters): ResolvedAttributeSet {
// let bodyCode = () =>
{
const wasPreviouslyResolving: boolean = this.ctx.corpus.isCurrentlyResolving;
this.ctx.corpus.isCurrentlyResolving = true;
if (!resOpt) {
resOpt = new resolveOptions(this, this.ctx.corpus.defaultResolutionDirectives);
}
let inCircularReference: boolean = false;
const wasInCircularReference: boolean = resOpt.inCircularReference;
if (isEntityDefinition(this)) {
inCircularReference = resOpt.currentlyResolvingEntities.has(this);
resOpt.currentlyResolvingEntities.add(this);
resOpt.inCircularReference = inCircularReference;
// uncomment this line as a test to turn off allowing cycles
//if (inCircularReference) {
// return new ResolvedAttributeSet();
//}
}
const currentDepth: number = resOpt.depthInfo.currentDepth;
const kind: string = 'rasb';
const ctx: resolveContext = this.ctx as resolveContext; // what it actually is
let rasbResult: ResolvedAttributeSetBuilder;
let rasbCache: ResolvedAttributeSetBuilder = this.fetchObjectFromCache(resOpt, acpInContext);
let underCtx: CdmAttributeContext;
// store the previous symbol set, we will need to add it with
// children found from the constructResolvedTraits call
const currSymRefSet: SymbolSet = resOpt.symbolRefSet || new SymbolSet();
resOpt.symbolRefSet = new SymbolSet();
// if using the cache passes the maxDepth, we cannot use it
if (rasbCache && resOpt.depthInfo.currentDepth + rasbCache.ras.depthTraveled > resOpt.depthInfo.maxDepth) {
rasbCache = undefined;
}
if (!rasbCache) {
// a new context node is needed for these attributes,
// this tree will go into the cache, so we hang it off a placeholder parent
// when it is used from the cache (or now), then this placeholder parent is ignored and the things under it are
// put into the 'receiving' tree
underCtx = CdmAttributeContext.getUnderContextForCacheContext(resOpt, this.ctx, acpInContext);
rasbCache = this.constructResolvedAttributes(resOpt, underCtx);
if (rasbCache !== undefined) {
// register set of possible docs
const odef: CdmObject = this.fetchObjectDefinition(resOpt);
if (odef !== undefined) {
ctx.corpus.registerDefinitionReferenceSymbols(odef, kind, resOpt.symbolRefSet);
if (this.objectType === cdmObjectType.entityDef) {
// if we just got attributes for an entity, take the time now to clean up this cached tree and prune out
// things that don't help explain where the final set of attributes came from
if (underCtx) {
const scopesForAttributes = new Set<CdmAttributeContext>();
underCtx.collectContextFromAtts(rasbCache.ras, scopesForAttributes); // the context node for every final attribute
if (!underCtx.pruneToScope(scopesForAttributes)) {
return undefined;
}
}
}
// get the new cache tag now that we have the list of docs
const cacheTag: string = ctx.corpus.createDefinitionCacheTag(resOpt, this, kind, acpInContext ? 'ctx' : undefined);
// save this as the cached version
if (cacheTag) {
ctx.attributeCache.set(cacheTag, rasbCache);
}
}
// get the 'underCtx' of the attribute set from the acp that is wired into
// the target tree
underCtx = rasbCache.ras.attributeContext ?
rasbCache.ras.attributeContext.getUnderContextFromCacheContext(resOpt, acpInContext) : undefined;
}
} else {
// get the 'underCtx' of the attribute set from the cache. The one stored there was build with a different
// acp and is wired into the fake placeholder. so now build a new underCtx wired into the output tree but with
// copies of all cached children
underCtx = rasbCache.ras.attributeContext ?
rasbCache.ras.attributeContext.getUnderContextFromCacheContext(resOpt, acpInContext) : undefined;
//underCtx.validateLineage(resOpt); // debugging
}
if (rasbCache) {
// either just built something or got from cache
// either way, same deal: copy resolved attributes and copy the context tree associated with it
// 1. deep copy the resolved att set (may have groups) and leave the attCtx pointers set to the old tree
// 2. deep copy the tree.
// 1. deep copy the resolved att set (may have groups) and leave the attCtx pointers set to the old tree
rasbResult = new ResolvedAttributeSetBuilder();
rasbResult.ras = rasbCache.ras.copy();
// 2. deep copy the tree and map the context references.
if (underCtx) // null context? means there is no tree, probably 0 attributes came out
{
if (!underCtx.associateTreeCopyWithAttributes(resOpt, rasbResult.ras)) {
return undefined;
}
}
}
if (isEntityAttributeDefinition(this)) {
// if we hit the maxDepth, we are now going back up
resOpt.depthInfo.currentDepth = currentDepth;
// now at the top of the chain where max depth does not influence the cache
if (resOpt.depthInfo.currentDepth === 0) {
resOpt.depthInfo.maxDepthExceeded = false;
}
}
if (!inCircularReference && isEntityDefinition(this)) {
// should be removed from the root level only
// if it is in a circular reference keep it there
resOpt.currentlyResolvingEntities.delete(this);
}
resOpt.inCircularReference = wasInCircularReference;
// merge child reference symbols set with current
currSymRefSet.merge(resOpt.symbolRefSet);
resOpt.symbolRefSet = currSymRefSet;
this.ctx.corpus.isCurrentlyResolving = wasPreviouslyResolving;
return rasbResult ? rasbResult.ras : undefined;
}
// return p.measure(bodyCode);
}
/**
* @internal
*/
public clearTraitCache(): void {
// let bodyCode = () =>
{
this.traitCache = undefined;
}
// return p.measure(bodyCode);
}
public abstract visit(path: string, preChildren: VisitCallback, postChildren: VisitCallback): boolean;
private static protectParameterValues(resOpt: resolveOptions, val: any) {
if (val) {
// the value might be a contant entity object, need to protect the original
let cEnt: any = (val as CdmEntityReference) ? (val as CdmEntityReference).explicitReference as CdmConstantEntityDefinition : undefined;
if (cEnt) {
// copy the constant entity AND the reference that holds it
cEnt = cEnt.copy(resOpt) as CdmConstantEntityDefinition;
val = (val as CdmEntityReference).copy(resOpt);
(val as CdmEntityReference).explicitReference = cEnt;
}
}
return val;
}
} | the_stack |
import Aigle from './aigle';
type AllSettledResponse<T> = Aigle.AllSettledResponse<T>;
/* interface */
interface Hawk {
hawk(): string;
}
interface Swan {
swan(): string;
}
interface Duck {
duck(): string;
}
class Crow extends Error {
crow(): string {
return 'crow';
}
}
type Hawks = Hawk[];
type Swans = Swan[];
type Ducks = Duck[];
type Crows = Crow[];
type HawkMap<T extends string = string> = Record<T, Hawk>;
type SwanMap<T extends string = string> = Record<T, Swan>;
type DuckMap<T extends string = string> = Record<T, Duck>;
type CrowMap<T extends string = string> = Record<T, Crow>;
type List<T> = ArrayLike<T>;
type PromiseCallback<T> = () => Aigle<T>;
/* variables */
let obj: object;
let bool: boolean;
let num: number;
let str: string;
let err: Error;
let hawk: Hawk;
let swan: Swan;
let duck: Duck;
let hawkArr: Hawks;
let swanArr: Swans;
let duckArr: Ducks;
let hawkList: List<Hawk>;
let swanList: List<Swan>;
let duckList: List<Duck>;
let hawkProm: Aigle<Hawk>;
let swanProm: Aigle<Swan>;
let duckProm: Aigle<Duck>;
let hawkThen: PromiseLike<Hawk>;
let swanThen: PromiseLike<Swan>;
let duckThen: PromiseLike<Duck>;
let hawkArrProm: Aigle<Hawks>;
let swanArrProm: Aigle<Swans>;
let duckArrProm: Aigle<Ducks>;
let hawkListProm: Aigle<List<Hawk>>;
let swanListProm: Aigle<List<Swan>>;
let duckListProm: Aigle<List<Duck>>;
let hawkCallback: PromiseCallback<Hawk>;
let swanCallback: PromiseCallback<Swan>;
let duckCallback: PromiseCallback<Duck>;
/* core functions */
//-- instances --//
hawkProm = new Aigle((resolve: (value: Hawk) => void, reject: (reason: any) => void) =>
bool ? resolve(hawk) : reject(err)
);
hawkProm = new Aigle((resolve: (value: Hawk) => void) => resolve(hawk));
hawkProm = new Aigle<Hawk>((resolve, reject) => (bool ? resolve(hawkThen) : reject(err)));
hawkProm = new Aigle<Hawk>((resolve) => resolve(hawkThen));
//-- then --//
hawkProm.then(
(value: Hawk) => swan,
(reason: any) => err
);
hawkProm.then(
(value: Hawk) => swanProm,
(reason: any) => duckProm
);
hawkProm.then((value: Hawk) => swan).then((value: Swan) => duck);
hawkProm.then((value: Hawk) => swanProm).then((value: Swan) => duck);
hawkProm
.then((value: Hawk) => swanProm)
.then((value: Swan) => duckProm)
.then((value: Duck) => null);
//-- catch --//
hawkProm.catch((reason: any) => {});
hawkProm.catch(
(error: any) => true,
(reason: any) => {}
);
hawkProm.catch(Crow, (reason: any) => {});
hawkProm.catch(Crow, Crow, Crow, (reason: any) => {});
//-- finally --//
hawkProm.finally(() => {});
hawkProm.finally(() => str);
hawkProm.finally(() => swanProm);
/* all */
hawkArrProm.all().then((values: Hawks) => {});
/* allSettled */
hawkArrProm.allSettled().then((values: AllSettledResponse<Hawk>[]) => {});
/* race */
hawkArrProm.race().then((value: Hawk) => {});
/* series */
hawkArrProm.series().then((values: Hawks) => {});
/* parallel */
hawkArrProm.parallel().then((values: Hawks) => {});
/* parallelLimit */
hawkArrProm.parallelLimit().then((values: Hawks) => {});
hawkArrProm.parallelLimit(2).then((values: Hawks) => {});
/* each/forEach */
//-- each:array --//
hawkArrProm.each((hawk: Hawk, index: number, arr: Hawks) => hawk).then((arr: Hawks) => {});
hawkArrProm.each((hawk: Hawk, index: number) => swan).then((arr: Hawks) => {});
hawkArrProm.each((hawk: Hawk) => duck).then((arr: Hawks) => {});
//-- each:list --//
hawkListProm
.each((hawk: Hawk, index: number, list: List<Hawk>) => hawk)
.then((list: List<Hawk>) => {});
hawkListProm.each((hawk: Hawk, index: number) => swan).then((list: List<Hawk>) => {});
hawkListProm.each((hawk: Hawk) => duck).then((list: List<Hawk>) => {});
//-- each:object --//
hawkProm.each((val: Hawk[keyof Hawk], key: string, hawk: Hawk) => hawk).then((hawk: Hawk) => {});
hawkProm.each((val: Hawk[keyof Hawk], key: string) => swan).then((hawk: Hawk) => {});
hawkProm.each((val: Hawk[keyof Hawk]) => duck).then((hawk: Hawk) => {});
//-- forEach:array --//
hawkArrProm.forEach((hawk: Hawk, index: number, arr: Hawks) => hawk).then((arr: Hawks) => {});
hawkArrProm.forEach((hawk: Hawk, index: number) => swan).then((arr: Hawks) => {});
hawkArrProm.forEach((hawk: Hawk) => duck).then((arr: Hawks) => {});
//-- forEach:list --//
hawkListProm
.forEach((hawk: Hawk, index: number, list: List<Hawk>) => hawk)
.then((list: List<Hawk>) => {});
hawkListProm.forEach((hawk: Hawk, index: number) => swan).then((list: List<Hawk>) => {});
hawkListProm.forEach((hawk: Hawk) => duck).then((list: List<Hawk>) => {});
//-- forEach:object --//
hawkProm.forEach((val: Hawk[keyof Hawk], key: string, hawk: Hawk) => hawk).then((hawk: Hawk) => {});
hawkProm.forEach((val: Hawk[keyof Hawk], key: string) => swan).then((hawk: Hawk) => {});
hawkProm.forEach((val: Hawk[keyof Hawk]) => duck).then((hawk: Hawk) => {});
/* eachSeries/forEachSeries */
//-- eachSeries:array --//
hawkArrProm.eachSeries((hawk: Hawk, index: number, arr: Hawks) => hawk).then((arr: Hawks) => {});
hawkArrProm.eachSeries((hawk: Hawk, index: number) => swan).then((arr: Hawks) => {});
hawkArrProm.eachSeries((hawk: Hawk) => duck).then((arr: Hawks) => {});
//-- eachSeries:list --//
hawkListProm
.eachSeries((hawk: Hawk, index: number, list: List<Hawk>) => hawk)
.then((list: List<Hawk>) => {});
hawkListProm.eachSeries((hawk: Hawk, index: number) => swan).then((list: List<Hawk>) => {});
hawkListProm.eachSeries((hawk: Hawk) => duck).then((list: List<Hawk>) => {});
//-- eachSeries:object --//
hawkProm
.eachSeries((val: Hawk[keyof Hawk], key: string, hawk: Hawk) => hawk)
.then((hawk: Hawk) => {});
hawkProm.eachSeries((val: Hawk[keyof Hawk], key: string) => swan).then((hawk: Hawk) => {});
hawkProm.eachSeries((val: Hawk[keyof Hawk]) => duck).then((hawk: Hawk) => {});
//-- forEachSeries:array --//
hawkArrProm.forEachSeries((hawk: Hawk, index: number, arr: Hawks) => hawk).then((arr: Hawks) => {});
hawkArrProm.forEachSeries((hawk: Hawk, index: number) => swan).then((arr: Hawks) => {});
hawkArrProm.forEachSeries((hawk: Hawk) => duck).then((arr: Hawks) => {});
//-- forEachSeries:list --//
hawkListProm
.forEachSeries((hawk: Hawk, index: number, list: List<Hawk>) => hawk)
.then((list: List<Hawk>) => {});
hawkListProm.forEachSeries((hawk: Hawk, index: number) => swan).then((list: List<Hawk>) => {});
hawkListProm.forEachSeries((hawk: Hawk) => duck).then((list: List<Hawk>) => {});
//-- forEachSeries:object --//
hawkProm
.forEachSeries((val: Hawk[keyof Hawk], key: string, hawk: Hawk) => hawk)
.then((hawk: Hawk) => {});
hawkProm.forEachSeries((val: Hawk[keyof Hawk], key: string) => swan).then((hawk: Hawk) => {});
hawkProm.forEachSeries((val: Hawk[keyof Hawk]) => duck).then((hawk: Hawk) => {});
/* eachLimit/forEachLimit */
//-- eachLimit:array --//
hawkArrProm.eachLimit((hawk: Hawk, index: number, arr: Hawks) => hawk).then((arr: Hawks) => {});
hawkArrProm.eachLimit(2, (hawk: Hawk, index: number, arr: Hawks) => hawk).then((arr: Hawks) => {});
hawkArrProm.eachLimit((hawk: Hawk, index: number) => swan).then((arr: Hawks) => {});
hawkArrProm.eachLimit(2, (hawk: Hawk, index: number) => swan).then((arr: Hawks) => {});
hawkArrProm.eachLimit((hawk: Hawk) => duck).then((arr: Hawks) => {});
hawkArrProm.eachLimit(2, (hawk: Hawk) => duck).then((arr: Hawks) => {});
//-- eachLimit:list --//
hawkListProm
.eachLimit((hawk: Hawk, index: number, list: List<Hawk>) => hawk)
.then((list: List<Hawk>) => {});
hawkListProm
.eachLimit(2, (hawk: Hawk, index: number, list: List<Hawk>) => hawk)
.then((list: List<Hawk>) => {});
hawkListProm.eachLimit((hawk: Hawk, index: number) => swan).then((list: List<Hawk>) => {});
hawkListProm.eachLimit(2, (hawk: Hawk, index: number) => swan).then((list: List<Hawk>) => {});
hawkListProm.eachLimit((hawk: Hawk) => duck).then((list: List<Hawk>) => {});
hawkListProm.eachLimit(2, (hawk: Hawk) => duck).then((list: List<Hawk>) => {});
//-- eachLimit:object --//
hawkProm
.eachLimit((val: Hawk[keyof Hawk], key: string, hawk: Hawk) => hawk)
.then((hawk: Hawk) => {});
hawkProm
.eachLimit(2, (val: Hawk[keyof Hawk], key: string, hawk: Hawk) => hawk)
.then((hawk: Hawk) => {});
hawkProm.eachLimit((val: Hawk[keyof Hawk], key: string) => swan).then((hawk: Hawk) => {});
hawkProm.eachLimit(2, (val: Hawk[keyof Hawk], key: string) => swan).then((hawk: Hawk) => {});
hawkProm.eachLimit((val: Hawk[keyof Hawk]) => duck).then((hawk: Hawk) => {});
hawkProm.eachLimit(2, (val: Hawk[keyof Hawk]) => duck).then((hawk: Hawk) => {});
//-- forEachLimit:array --//
hawkArrProm.forEachLimit((hawk: Hawk, index: number, arr: Hawks) => hawk).then((arr: Hawks) => {});
hawkArrProm
.forEachLimit(2, (hawk: Hawk, index: number, arr: Hawks) => hawk)
.then((arr: Hawks) => {});
hawkArrProm.forEachLimit((hawk: Hawk, index: number) => swan).then((arr: Hawks) => {});
hawkArrProm.forEachLimit(2, (hawk: Hawk, index: number) => swan).then((arr: Hawks) => {});
hawkArrProm.forEachLimit((hawk: Hawk) => duck).then((arr: Hawks) => {});
hawkArrProm.forEachLimit(2, (hawk: Hawk) => duck).then((arr: Hawks) => {});
//-- foreachLimit:list --//
hawkListProm
.forEachLimit((hawk: Hawk, index: number, list: List<Hawk>) => hawk)
.then((list: List<Hawk>) => {});
hawkListProm
.forEachLimit(2, (hawk: Hawk, index: number, list: List<Hawk>) => hawk)
.then((list: List<Hawk>) => {});
hawkListProm.forEachLimit((hawk: Hawk, index: number) => swan).then((list: List<Hawk>) => {});
hawkListProm.forEachLimit(2, (hawk: Hawk, index: number) => swan).then((list: List<Hawk>) => {});
hawkListProm.forEachLimit((hawk: Hawk) => duck).then((list: List<Hawk>) => {});
hawkListProm.forEachLimit(2, (hawk: Hawk) => duck).then((list: List<Hawk>) => {});
//-- foreachLimit:object --//
hawkProm
.forEachLimit((val: Hawk[keyof Hawk], key: string, hawk: Hawk) => hawk)
.then((hawk: Hawk) => {});
hawkProm
.forEachLimit(2, (val: Hawk[keyof Hawk], key: string, hawk: Hawk) => hawk)
.then((hawk: Hawk) => {});
hawkProm.forEachLimit((val: Hawk[keyof Hawk], key: string) => swan).then((hawk: Hawk) => {});
hawkProm.forEachLimit(2, (val: Hawk[keyof Hawk], key: string) => swan).then((hawk: Hawk) => {});
hawkProm.forEachLimit((val: Hawk[keyof Hawk]) => duck).then((hawk: Hawk) => {});
hawkProm.forEachLimit(2, (val: Hawk[keyof Hawk]) => duck).then((hawk: Hawk) => {});
/* concat */
//-- concat:array --//
hawkArrProm.concat((hawk: Hawk, index: number, arr: Hawks) => [hawk]).then((arr: Hawks) => {});
hawkArrProm.concat((hawk: Hawk, index: number) => [swan]).then((arr: Swans) => {});
hawkArrProm.concat((hawk: Hawk) => duck).then((arr: Ducks) => {});
//-- concat:list --//
hawkListProm
.concat((hawk: Hawk, index: number, list: List<Hawk>) => [hawk])
.then((arr: Hawks) => {});
hawkListProm.concat((hawk: Hawk, index: number) => [swan]).then((arr: Swans) => {});
hawkListProm.concat((hawk: Hawk) => duck).then((arr: Ducks) => {});
//-- concat:object --//
hawkProm
.concat((val: Hawk[keyof Hawk], key: string, hawk: Hawk) => [hawk])
.then((arr: Hawks) => {});
hawkProm.concat((val: Hawk[keyof Hawk], key: string) => [swan]).then((arr: Swans) => {});
hawkProm.concat((val: Hawk[keyof Hawk]) => duck).then((arr: Ducks) => {});
/* every */
//-- every:array --//
hawkArrProm.every((hawk: Hawk, index: number, arr: Hawks) => bool).then((bool: boolean) => {});
hawkArrProm.every((hawk: Hawk, index: number) => bool).then((bool: boolean) => {});
hawkArrProm.every((hawk: Hawk) => bool).then((bool: boolean) => {});
//-- every:list --//
hawkListProm
.every((hawk: Hawk, index: number, list: List<Hawk>) => bool)
.then((bool: boolean) => {});
hawkListProm.every((hawk: Hawk, index: number) => bool).then((bool: boolean) => {});
hawkListProm.every((hawk: Hawk) => bool).then((bool: boolean) => {});
//-- every:object --//
hawkProm
.every((val: Hawk[keyof Hawk], key: string, hawk: Hawk) => bool)
.then((bool: boolean) => {});
hawkProm.every((val: Hawk[keyof Hawk], key: string) => bool).then((bool: boolean) => {});
hawkProm.every((val: Hawk[keyof Hawk]) => bool).then((bool: boolean) => {});
/* transform */
//-- transform:array --//
hawkArrProm
.transform((acc: Swans, hawk: Hawk, index: number, arr: Hawks) => acc.push(swan))
.then((arr: Swans) => {});
hawkArrProm
.transform((acc: Swans, hawk: Hawk, index: number) => acc.push(swan))
.then((arr: Swans) => {});
hawkArrProm.transform((acc: SwanMap, hawk: Hawk) => (acc.a = swan), {}).then((swan: SwanMap) => {});
//-- transform:list --//
hawkListProm
.transform((acc: Swans, hawk: Hawk, index: number, list: List<Hawk>) => acc.push(swan))
.then((arr: Swans) => {});
hawkListProm
.transform((acc: Swans, hawk: Hawk, index: number) => acc.push(swan))
.then((arr: Swans) => {});
hawkListProm.transform((acc: SwanMap, hawk: Hawk) => (acc.a = swan), {}).then((map: SwanMap) => {});
//-- transform:object --//
hawkProm
.transform((acc: SwanMap, val: Hawk[keyof Hawk], key: string, hawk: Hawk) => {})
.then((map: SwanMap) => {});
hawkProm
.transform((acc: Swans, hawk: Hawk[keyof Hawk], key: string) => acc.push(swan), [])
.then((arr: Swans) => {});
hawkProm
.transform((acc: SwanMap, hawk: Hawk[keyof Hawk]) => (acc.a = swan), {})
.then((swan: SwanMap) => {});
/* times */
Aigle.resolve(10)
.times((num: number) => hawkProm)
.then((hawks: Hawks) => {});
/* tap */
hawkProm.tap((hawk: Hawk) => swanProm).then((hawk: Hawk) => {});
/* thru */
hawkProm.thru((hawk: Hawk) => swanProm).then((swan: Swan) => {});
/* timeout */
hawkProm.timeout(num).then((hawk: Hawk) => {});
hawkProm.timeout(num, str).then((hawk: Hawk) => {});
hawkProm.timeout(num, err).then((hawk: Hawk) => {});
/** static **/
/* core functions */
//-- resolve --//
Aigle.resolve(hawk).then((value: Hawk) => swan);
Aigle.resolve(hawkProm).then((value: Hawk) => swan);
//-- reject --//
Aigle.reject(err).catch((error: any) => {});
Aigle.resolve(hawkProm)
.catch((error: any) => Aigle.reject(error))
.then((value: Hawk) => swan);
/* all */
Aigle.all([hawkProm, swanProm, duckProm]).then((values: [Hawk, Swan, Duck]) => {});
/* allSettled */
Aigle.allSettled([
hawkProm,
swanProm,
duckProm,
]).then(
(values: [AllSettledResponse<Hawk>, AllSettledResponse<Swan>, AllSettledResponse<Duck>]) => {}
);
/* race */
Aigle.race([hawkProm, swanProm, duckProm]).then((value: Hawk | Swan | Duck) => {});
/* series */
Aigle.series([hawkProm, swanProm, duckProm]).then((values: [Hawk, Swan, Duck]) => {});
Aigle.series([hawkCallback, swanCallback, duckCallback]).then((values: [Hawk, Swan, Duck]) => {});
/* parallel */
Aigle.parallel([hawkProm, swanProm, duckProm]).then((values: [Hawk, Swan, Duck]) => {});
Aigle.parallel([hawkCallback, swanCallback, duckCallback]).then((values: [Hawk, Swan, Duck]) => {});
/* parallelLimit */
Aigle.parallelLimit([hawkProm, swanProm, duckProm]).then((values: [Hawk, Swan, Duck]) => {});
Aigle.parallelLimit(
[hawkCallback, swanCallback, duckCallback],
2
).then((values: [Hawk, Swan, Duck]) => {});
/* each/forEach */
//-- each:array --//
Aigle.each(hawkArr, (hawk: Hawk, index: number, arr: Hawks) => hawk).then((arr: Hawks) => {});
Aigle.each(hawkArr, (hawk: Hawk, index: number) => swan).then((arr: Hawks) => {});
Aigle.each(hawkArr, (hawk: Hawk) => duck).then((arr: Hawks) => {});
//-- each:list --//
Aigle.each(
hawkList,
(hawk: Hawk, index: number, arr: List<Hawk>) => hawk
).then((list: List<Hawk>) => {});
Aigle.each(hawkList, (hawk: Hawk, index: number) => swan).then((list: List<Hawk>) => {});
Aigle.each(hawkList, (hawk: Hawk) => duck).then((list: List<Hawk>) => {});
//-- each:object --//
Aigle.each(hawk, (val: Hawk[keyof Hawk], key: string, hawk: Hawk) => hawk).then((hawk: Hawk) => {});
Aigle.each(hawk, (val: Hawk[keyof Hawk], key: string) => swan).then((hawk: Hawk) => {});
Aigle.each(hawk, (val: Hawk[keyof Hawk]) => duck).then((hawk: Hawk) => {});
//-- forEach:array --//
Aigle.forEach(hawkArr, (hawk: Hawk, index: number, arr: Hawks) => hawk).then((arr: Hawks) => {});
Aigle.forEach(hawkArr, (hawk: Hawk, index: number) => swan).then((arr: Hawks) => {});
Aigle.forEach(hawkArr, (hawk: Hawk) => duck).then((arr: Hawks) => {});
//-- forEach:list --//
Aigle.forEach(
hawkList,
(hawk: Hawk, index: number, arr: List<Hawk>) => hawk
).then((list: List<Hawk>) => {});
Aigle.forEach(hawkList, (hawk: Hawk, index: number) => swan).then((list: List<Hawk>) => {});
Aigle.forEach(hawkList, (hawk: Hawk) => duck).then((list: List<Hawk>) => {});
//-- forEach:object --//
Aigle.forEach(
hawk,
(val: Hawk[keyof Hawk], key: string, hawk: Hawk) => hawk
).then((hawk: Hawk) => {});
Aigle.forEach(hawk, (val: Hawk[keyof Hawk], key: string) => swan).then((hawk: Hawk) => {});
Aigle.forEach(hawk, (val: Hawk[keyof Hawk]) => duck).then((hawk: Hawk) => {});
/* mapValues */
//-- mapValues:array --//
Aigle.mapValues(
hawkArr,
(hawk: Hawk, index: number, arr: Hawks) => hawk
).then((map: HawkMap) => {});
Aigle.mapValues(hawkArr, (hawk: Hawk, index: number) => swan).then((map: SwanMap) => {});
Aigle.mapValues(hawkArr, (hawk: Hawk) => duck).then((map: DuckMap) => {});
//-- mapValues:list --//
Aigle.mapValues(
hawkList,
(hawk: Hawk, index: number, arr: List<Hawk>) => hawk
).then((map: HawkMap) => {});
Aigle.mapValues(hawkList, (hawk: Hawk, index: number) => swan).then((map: SwanMap) => {});
Aigle.mapValues(hawkList, (hawk: Hawk) => duck).then((map: DuckMap) => {});
//-- mapValues:object --//
Aigle.mapValues(
hawk,
(val: Hawk[keyof Hawk], key: string, hawk: Hawk) => hawk
).then((map: HawkMap<keyof Hawk>) => {});
Aigle.mapValues(
hawk,
(val: Hawk[keyof Hawk], key: string) => swan
).then((map: SwanMap<keyof Hawk>) => {});
Aigle.mapValues(hawk, (val: Hawk[keyof Hawk]) => duck).then((map: DuckMap<keyof Hawk>) => {});
/* concat */
//-- concat:array --//
Aigle.concat(hawkArr, (hawk: Hawk, index: number, arr: Hawks) => [hawk]).then((arr: Hawks) => {});
Aigle.concat(hawkArr, (hawk: Hawk, index: number) => [swan]).then((arr: Swans) => {});
Aigle.concat(hawkArr, (hawk: Hawk) => duck).then((arr: Ducks) => {});
//-- concat:list --//
Aigle.concat(hawkList, (hawk: Hawk, index: number, arr: List<Hawk>) => [
hawk,
]).then((arr: Hawks) => {});
Aigle.concat(hawkList, (hawk: Hawk, index: number) => [swan]).then((arr: Swans) => {});
Aigle.concat(hawkList, (hawk: Hawk) => duck).then((arr: Ducks) => {});
//-- concat:object --//
Aigle.concat(hawk, (val: Hawk[keyof Hawk], key: string, hawk: Hawk) => [
hawk,
]).then((arr: Hawks) => {});
Aigle.concat(hawk, (val: Hawk[keyof Hawk], key: string) => [swan]).then((arr: Swans) => {});
Aigle.concat(hawk, (val: Hawk[keyof Hawk]) => duck).then((arr: Ducks) => {});
/* every */
//-- every:array --//
Aigle.every(hawkArr, (hawk: Hawk, index: number, arr: Hawks) => bool).then((bool: boolean) => {});
Aigle.every(hawkArr, (hawk: Hawk, index: number) => bool).then((bool: boolean) => {});
Aigle.every(hawkArr, (hawk: Hawk) => bool).then((bool: boolean) => {});
//-- every:list --//
Aigle.every(
hawkList,
(hawk: Hawk, index: number, arr: List<Hawk>) => bool
).then((bool: boolean) => {});
Aigle.every(hawkList, (hawk: Hawk, index: number) => bool).then((bool: boolean) => {});
Aigle.every(hawkList, (hawk: Hawk) => bool).then((bool: boolean) => {});
//-- every:object --//
Aigle.every(
hawk,
(val: Hawk[keyof Hawk], key: string, hawk: Hawk) => bool
).then((bool: boolean) => {});
Aigle.every(hawk, (val: Hawk[keyof Hawk], key: string) => bool).then((bool: boolean) => {});
Aigle.every(hawk, (val: Hawk[keyof Hawk]) => bool).then((bool: boolean) => {});
/* tap */
Aigle.tap(hawk, (hawk: Hawk) => swanProm).then((hawk: Hawk) => {});
/* thru */
Aigle.thru(hawk, (hawk: Hawk) => swanProm).then((swan: Swan) => {});
/* flow */
Aigle.flow(
(a: number, b: number) => Aigle.delay(10, a + b),
(c: number) => Aigle.delay(10, c * c)
)(1, 2).then((value: number) => {});
/* attempt */
Aigle.attempt(() => hawkProm).then((val: Hawk) => {});
/* using */
Aigle.using(
hawkProm.disposer(() => {}),
(hawk: Hawk) => hawk
).then((hawk: Hawk) => {}); | the_stack |
import React, { useMemo, useEffect } from 'react';
import { FormikProps } from 'formik';
import { defineMessages, FormattedMessage } from 'react-intl';
import { bigNumberify } from 'ethers/utils';
import moveDecimal from 'move-decimal-point';
import { ColonyRole, ROOT_DOMAIN_ID } from '@colony/colony-js';
import { AddressZero } from 'ethers/constants';
import { useTransformer } from '~utils/hooks';
import Button from '~core/Button';
import DialogSection from '~core/Dialog/DialogSection';
import {
Select,
Input,
Annotations,
TokenSymbolSelector,
SelectOption,
} from '~core/Fields';
import Heading from '~core/Heading';
import PermissionRequiredInfo from '~core/PermissionRequiredInfo';
import PermissionsLabel from '~core/PermissionsLabel';
import {
useLoggedInUser,
useTokenBalancesForDomainsLazyQuery,
} from '~data/index';
import { ActionDialogProps } from '~core/Dialog';
import EthUsd from '~core/EthUsd';
import Numeral from '~core/Numeral';
import Toggle from '~core/Fields/Toggle';
import NotEnoughReputation from '~dashboard/NotEnoughReputation';
import {
getBalanceFromToken,
getTokenDecimalsWithFallback,
} from '~utils/tokens';
import { useDialogActionPermissions } from '~utils/hooks/useDialogActionPermissions';
import { getUserRolesForDomain } from '../../../transformers';
import { userHasRole } from '../../../users/checks';
import styles from './TransferFundsDialogForm.css';
import { FormValues } from './TransferFundsDialog';
import Icon from '~core/Icon';
import MotionDomainSelect from '~dashboard/MotionDomainSelect';
const MSG = defineMessages({
title: {
id: 'dashboard.TransferFundsDialog.TransferFundsDialogForm.title',
defaultMessage: 'Transfer Funds',
},
from: {
id: 'dashboard.TransferFundsDialog.TransferFundsDialogForm.from',
defaultMessage: 'From',
},
to: {
id: 'dashboard.TransferFundsDialog.TransferFundsDialogForm.to',
defaultMessage: 'To',
},
amount: {
id: 'dashboard.TransferFundsDialog.TransferFundsDialogForm.amount',
defaultMessage: 'Amount',
},
token: {
id: 'dashboard.TransferFundsDialog.TransferFundsDialogForm.address',
defaultMessage: 'Token',
},
annotation: {
id: 'dashboard.TransferFundsDialog.TransferFundsDialogForm.annotation',
defaultMessage: 'Explain why you’re transferring these funds (optional)',
},
domainTokenAmount: {
id:
'dashboard.TransferFundsDialog.TransferFundsDialogForm.domainTokenAmount',
defaultMessage: 'Available: {amount} {symbol}',
},
noAmount: {
id: 'dashboard.TransferFundsDialog.TransferFundsDialogForm.noAmount',
defaultMessage: 'Amount must be greater than zero',
},
noBalance: {
id: 'dashboard.TransferFundsDialog.TransferFundsDialogForm.noBalance',
defaultMessage: 'Insufficient balance in from team pot',
},
noPermissionFrom: {
id:
'dashboard.TransferFundsDialog.TransferFundsDialogForm.noPermissionFrom',
defaultMessage: `You need the {permissionLabel} permission in {domainName}
to take this action`,
},
samePot: {
id: 'dashboard.TransferFundsDialog.TransferFundsDialogForm.samePot',
defaultMessage: 'Cannot move to same team pot',
},
transferIconTitle: {
id:
'dashboard.TransferFundsDialog.TransferFundsDialogForm.transferIconTitle',
defaultMessage: 'Transfer',
},
});
interface Props {
domainOptions: SelectOption[];
}
const TransferFundsDialogForm = ({
back,
colony,
colony: { colonyAddress, domains, tokens },
domainOptions,
handleSubmit,
isSubmitting,
isValid,
setErrors,
values,
validateForm,
errors,
isVotingExtensionEnabled,
}: ActionDialogProps & FormikProps<FormValues> & Props) => {
const { tokenAddress, amount } = values;
const fromDomainId = values.fromDomain
? parseInt(values.fromDomain, 10)
: ROOT_DOMAIN_ID;
const fromDomain = domains.find(
({ ethDomainId }) => ethDomainId === fromDomainId,
);
const toDomainId = values.toDomain
? parseInt(values.toDomain, 10)
: undefined;
const selectedToken = useMemo(
() => tokens.find((token) => token.address === values.tokenAddress),
[tokens, values.tokenAddress],
);
const { walletAddress } = useLoggedInUser();
const fromDomainRoles = useTransformer(getUserRolesForDomain, [
colony,
walletAddress,
fromDomainId,
]);
const canTransferFunds = userHasRole(fromDomainRoles, ColonyRole.Funding);
const requiredRoles: ColonyRole[] = [ColonyRole.Funding];
const [userHasPermission, onlyForceAction] = useDialogActionPermissions(
colony.colonyAddress,
canTransferFunds,
isVotingExtensionEnabled,
values.forceAction,
);
const inputDisabled = !userHasPermission || onlyForceAction;
const [
loadTokenBalances,
{ data: tokenBalancesData },
] = useTokenBalancesForDomainsLazyQuery();
useEffect(() => {
if (tokenAddress) {
loadTokenBalances({
variables: {
colonyAddress,
tokenAddresses: [tokenAddress],
domainIds: [fromDomainId, toDomainId || ROOT_DOMAIN_ID],
},
});
}
}, [
colonyAddress,
tokenAddress,
fromDomainId,
toDomainId,
loadTokenBalances,
]);
const fromDomainTokenBalance = useMemo(() => {
const token =
tokenBalancesData &&
tokenBalancesData.tokens.find(({ address }) => address === tokenAddress);
return getBalanceFromToken(token, fromDomainId);
}, [fromDomainId, tokenAddress, tokenBalancesData]);
const toDomainTokenBalance = useMemo(() => {
if (toDomainId) {
const token =
tokenBalancesData &&
tokenBalancesData.tokens.find(
({ address }) => address === tokenAddress,
);
return getBalanceFromToken(token, toDomainId);
}
return undefined;
}, [toDomainId, tokenAddress, tokenBalancesData]);
// Perform form validations
useEffect(() => {
const customValidationErrors: {
amount?: any;
toDomain?: any;
} = {
...errors,
};
if (
!selectedToken ||
!(amount && amount.length) ||
!fromDomainTokenBalance
) {
return setErrors(customValidationErrors); // silent error
}
const convertedAmount = bigNumberify(
moveDecimal(amount, getTokenDecimalsWithFallback(selectedToken.decimals)),
);
if (convertedAmount.isZero()) {
customValidationErrors.amount = MSG.noAmount;
}
if (fromDomainTokenBalance.lt(convertedAmount)) {
customValidationErrors.amount = MSG.noBalance;
}
if (toDomainId !== undefined && toDomainId === fromDomainId) {
customValidationErrors.toDomain = MSG.samePot;
}
return setErrors(customValidationErrors);
}, [
errors,
amount,
fromDomainId,
fromDomainTokenBalance,
selectedToken,
setErrors,
toDomainId,
]);
return (
<>
<DialogSection appearance={{ theme: 'sidePadding' }}>
<div className={styles.modalHeading}>
{isVotingExtensionEnabled && (
<div className={styles.motionVoteDomain}>
<MotionDomainSelect
colony={colony}
/*
* @NOTE Always disabled since you can only create this motion in root
*/
disabled
/>
</div>
)}
<div className={styles.headingContainer}>
<Heading
appearance={{ size: 'medium', margin: 'none', theme: 'dark' }}
text={MSG.title}
/>
{canTransferFunds && isVotingExtensionEnabled && (
<Toggle label={{ id: 'label.force' }} name="forceAction" />
)}
</div>
</div>
</DialogSection>
{!userHasPermission && (
<div className={styles.permissionsRequired}>
<DialogSection>
<PermissionRequiredInfo requiredRoles={requiredRoles} />
</DialogSection>
</div>
)}
<DialogSection>
<div className={styles.domainSelects}>
<div>
<Select
options={domainOptions}
label={MSG.from}
name="fromDomain"
appearance={{ theme: 'grey' }}
onChange={() => validateForm()}
disabled={inputDisabled}
/>
{!!tokenAddress && (
<div className={styles.domainPotBalance}>
<FormattedMessage
{...MSG.domainTokenAmount}
values={{
amount: (
<Numeral
appearance={{
size: 'small',
theme: 'grey',
}}
value={fromDomainTokenBalance || 0}
unit={getTokenDecimalsWithFallback(
selectedToken && selectedToken.decimals,
)}
truncate={3}
/>
),
symbol: (selectedToken && selectedToken.symbol) || '???',
}}
/>
</div>
)}
</div>
<Icon
className={styles.transferIcon}
name="circle-arrow-back"
title={MSG.transferIconTitle}
appearance={{ size: 'medium' }}
/>
<div>
<Select
options={domainOptions}
label={MSG.to}
name="toDomain"
appearance={{ theme: 'grey' }}
onChange={() => validateForm()}
disabled={inputDisabled}
/>
{!!tokenAddress && toDomainTokenBalance && !errors.toDomain && (
<div className={styles.domainPotBalance}>
<FormattedMessage
{...MSG.domainTokenAmount}
values={{
amount: (
<Numeral
appearance={{
size: 'small',
theme: 'grey',
}}
value={toDomainTokenBalance || 0}
unit={getTokenDecimalsWithFallback(
selectedToken && selectedToken.decimals,
)}
truncate={3}
/>
),
symbol: (selectedToken && selectedToken.symbol) || '???',
}}
/>
</div>
)}
</div>
</div>
</DialogSection>
<DialogSection>
<div className={styles.tokenAmount}>
<div className={styles.amountContainer}>
<Input
label={MSG.amount}
name="amount"
appearance={{
theme: 'minimal',
align: 'right',
}}
formattingOptions={{
delimiter: ',',
numeral: true,
numeralDecimalScale: getTokenDecimalsWithFallback(
selectedToken && selectedToken.decimals,
),
}}
disabled={inputDisabled}
onChange={() => validateForm()}
/>
</div>
<div className={styles.tokenAmountSelect}>
<TokenSymbolSelector
label={MSG.token}
tokens={tokens}
name="tokenAddress"
elementOnly
appearance={{ alignOptions: 'right', theme: 'grey' }}
disabled={inputDisabled}
/>
</div>
{values.tokenAddress === AddressZero && (
<div className={styles.tokenAmountUsd}>
<EthUsd
appearance={{ theme: 'grey', size: 'small' }}
value={
/*
* @NOTE Set value to 0 if amount is only the decimal point
* Just entering the decimal point will pass it through to EthUsd
* and that will try to fetch the balance for, which, obviously, will fail
*/
values.amount && values.amount !== '.' ? values.amount : '0'
}
/>
</div>
)}
</div>
</DialogSection>
<DialogSection>
<Annotations
label={MSG.annotation}
name="annotation"
disabled={inputDisabled}
/>
</DialogSection>
{!userHasPermission && (
<DialogSection>
<span className={styles.permissionsError}>
<FormattedMessage
{...MSG.noPermissionFrom}
values={{
permissionLabel: (
<PermissionsLabel
permission={ColonyRole.Funding}
name={{ id: `role.${ColonyRole.Funding}` }}
/>
),
domainName: fromDomain?.name,
}}
/>
</span>
</DialogSection>
)}
{onlyForceAction && (
<NotEnoughReputation appearance={{ marginTop: 'negative' }} />
)}
<DialogSection appearance={{ align: 'right', theme: 'footer' }}>
{back && (
<Button
appearance={{ theme: 'secondary', size: 'large' }}
onClick={back}
text={{ id: 'button.back' }}
/>
)}
<Button
appearance={{ theme: 'primary', size: 'large' }}
onClick={() => handleSubmit()}
text={{ id: 'button.confirm' }}
loading={isSubmitting}
disabled={!isValid || inputDisabled}
style={{ width: styles.wideButton }}
/>
</DialogSection>
</>
);
};
TransferFundsDialogForm.displayName =
'dashboard.TransferFundsDialog.TransferFundsDialogForm';
export default TransferFundsDialogForm; | the_stack |
import * as ts from 'typescript'
import {
FieldDefinition,
SyntaxType,
UnionDefinition,
} from '@creditkarma/thrift-parser'
import { thriftTypeForFieldType, typeNodeForFieldType } from './types'
import {
createClassConstructor,
createConstStatement,
createEqualsCheck,
createFunctionParameter,
createLetStatement,
createNotNullCheck,
propertyAccessForIdentifier,
throwProtocolException,
} from './utils'
import { createNumberType } from './types'
import {
assignmentForField,
createArgsParameterForStruct,
createFieldsForStruct,
createInputParameter,
createSkipBlock,
createWriteMethod,
readFieldBegin,
readFieldEnd,
readStructBegin,
readStructEnd,
readValueForFieldType,
throwForField,
} from './struct'
import {
COMMON_IDENTIFIERS,
THRIFT_IDENTIFIERS,
THRIFT_TYPES,
} from './identifiers'
import { IRenderState } from '../../types'
/**
* There is a lot of duplication here of code with renderStruct. Need to revisit and clean this up.
* Probably revisit how functions are defined in the struct rendering code so that it is easier
* to insert instrumentation for Unions.
*/
export function renderUnion(
node: UnionDefinition,
state: IRenderState,
): ts.ClassDeclaration {
const fields: Array<ts.PropertyDeclaration> = createFieldsForStruct(
node,
state,
)
/**
* After creating the properties on our class for the struct fields we must create
* a constructor that knows how to assign these values based on a passed args.
*
* The constructor will take one arguments 'args'. This argument will be an object
* of an interface matching the struct definition. This interface is built by another
* function in src/render/interface
*
* The interface follows the naming convention of 'I<struct name>'
*
* If a required argument is not on the passed 'args' argument we need to throw on error.
* Optional fields we must allow to be null or undefined.
*/
const fieldAssignments: Array<ts.IfStatement> = node.fields.map(
createFieldAssignment,
)
/**
* Field assignments rely on there being an args argument passed in. We need to wrap
* field assignments in a conditional to check for the existance of args
*
* if (args != null) {
* ...fieldAssignments
* }
*/
const isArgsNull: ts.BinaryExpression = createNotNullCheck('args')
const argsCheckWithAssignments: ts.IfStatement = ts.createIf(
isArgsNull, // condition
ts.createBlock(
[...fieldAssignments, createFieldValidation(node)],
true,
), // then
undefined, // else
)
const argsParameter: Array<
ts.ParameterDeclaration
> = createArgsParameterForStruct(node)
// let fieldsSet: number = 0;
const fieldsSet: ts.VariableStatement = createFieldIncrementer()
// Build the constructor body
const ctor: ts.ConstructorDeclaration = createClassConstructor(
argsParameter,
[fieldsSet, argsCheckWithAssignments],
)
const factories: Array<ts.MethodDeclaration> = createUnionFactories(
node,
state,
)
// Build the `read` method
const readMethod: ts.MethodDeclaration = createReadMethod(node, state)
// Build the `write` method
const writeMethod: ts.MethodDeclaration = createWriteMethod(node, state)
// export class <node.name> { ... }
return ts.createClassDeclaration(
undefined, // decorators
[ts.createToken(ts.SyntaxKind.ExportKeyword)], // modifiers
node.name.value, // name
[], // type parameters
[], // heritage
[...fields, ctor, ...factories, writeMethod, readMethod], // body
)
}
function capitalize(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1)
}
function createFactoryNameForField(field: FieldDefinition): string {
return `from${capitalize(field.name.value)}`
}
function createUnionFactories(
node: UnionDefinition,
state: IRenderState,
): Array<ts.MethodDeclaration> {
return node.fields.map(
(next: FieldDefinition): ts.MethodDeclaration => {
return ts.createMethod(
undefined,
[
ts.createToken(ts.SyntaxKind.PublicKeyword),
ts.createToken(ts.SyntaxKind.StaticKeyword),
],
undefined,
ts.createIdentifier(createFactoryNameForField(next)),
undefined,
undefined,
[
createFunctionParameter(
ts.createIdentifier(next.name.value),
typeNodeForFieldType(next.fieldType, state),
),
],
ts.createTypeReferenceNode(
ts.createIdentifier(node.name.value),
undefined,
),
ts.createBlock(
[
ts.createReturn(
ts.createNew(
ts.createIdentifier(node.name.value),
undefined,
[
ts.createObjectLiteral([
ts.createShorthandPropertyAssignment(
next.name.value,
),
]),
],
),
),
],
true,
),
)
},
)
}
/**
* Assign field if contained in args:
*
* if (args && args.<field.name> != null) {
* this.<field.name> = args.<field.name>
* }
*
* If field is required throw an error:
*
* else {
* throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, 'Required field {{fieldName}} is unset!')
* }
*/
function createFieldAssignment(field: FieldDefinition): ts.IfStatement {
const comparison: ts.BinaryExpression = createNotNullCheck(
`args.${field.name.value}`,
)
const thenAssign: ts.Statement = assignmentForField(field)
const incrementer: ts.ExpressionStatement = incrementFieldsSet()
const elseThrow: ts.ThrowStatement | undefined = throwForField(field)
return ts.createIf(
comparison,
ts.createBlock([incrementer, thenAssign], true),
elseThrow !== undefined ? ts.createBlock([elseThrow], true) : undefined,
)
}
function createReadMethod(
node: UnionDefinition,
state: IRenderState,
): ts.MethodDeclaration {
const inputParameter: ts.ParameterDeclaration = createInputParameter()
const returnVariable: ts.VariableStatement = createLetStatement(
COMMON_IDENTIFIERS._returnValue,
ts.createUnionTypeNode([
ts.createTypeReferenceNode(
ts.createIdentifier(node.name.value),
undefined,
),
ts.createNull(),
]),
ts.createNull(),
)
// let fieldsSet: number = 0;
const fieldsSet: ts.VariableStatement = createFieldIncrementer()
// cosnt ret: { fieldName: string; fieldType: Thrift.Type; fieldId: number; } = input.readFieldBegin()
const ret: ts.VariableStatement = createConstStatement(
'ret',
ts.createTypeReferenceNode(THRIFT_IDENTIFIERS.TField, undefined),
readFieldBegin(),
)
// const fieldType: Thrift.Type = ret.fieldType
const fieldType: ts.VariableStatement = createConstStatement(
'fieldType',
ts.createTypeReferenceNode(THRIFT_IDENTIFIERS.Thrift_Type, undefined),
propertyAccessForIdentifier('ret', 'ftype'),
)
// const fieldId: number = ret.fieldId
const fieldId: ts.VariableStatement = createConstStatement(
'fieldId',
createNumberType(),
propertyAccessForIdentifier('ret', 'fid'),
)
/**
* if (fieldType === Thrift.Type.STOP) {
* break;
* }
*/
const checkStop: ts.IfStatement = ts.createIf(
createEqualsCheck(COMMON_IDENTIFIERS.fieldType, THRIFT_TYPES.STOP),
ts.createBlock([ts.createBreak()], true),
)
const caseStatements: Array<ts.CaseClause> = node.fields.map(
(field: FieldDefinition) => {
return createCaseForField(node, field, state)
},
)
/**
* switch (fieldId) {
* ...caseStatements
* }
*/
const switchStatement: ts.SwitchStatement = ts.createSwitch(
COMMON_IDENTIFIERS.fieldId, // what to switch on
ts.createCaseBlock([
...caseStatements,
ts.createDefaultClause([createSkipBlock()]),
]),
)
const whileBlock: ts.Block = ts.createBlock(
[ret, fieldType, fieldId, checkStop, switchStatement, readFieldEnd()],
true,
)
const whileLoop: ts.WhileStatement = ts.createWhile(
ts.createLiteral(true),
whileBlock,
)
return ts.createMethod(
undefined,
[
ts.createToken(ts.SyntaxKind.PublicKeyword),
ts.createToken(ts.SyntaxKind.StaticKeyword),
],
undefined,
COMMON_IDENTIFIERS.read,
undefined,
undefined,
[inputParameter],
ts.createTypeReferenceNode(
ts.createIdentifier(node.name.value),
undefined,
), // return type
ts.createBlock(
[
fieldsSet,
returnVariable,
readStructBegin(),
whileLoop,
readStructEnd(),
createFieldValidation(node, true),
ts.createIf(
ts.createBinary(
COMMON_IDENTIFIERS._returnValue,
ts.SyntaxKind.ExclamationEqualsEqualsToken,
ts.createNull(),
),
ts.createBlock(
[ts.createReturn(COMMON_IDENTIFIERS._returnValue)],
true,
),
ts.createBlock(
[
throwProtocolException(
'UNKNOWN',
'Unable to read data for TUnion',
),
],
true,
),
),
],
true,
),
)
}
/**
* EXAMPLE
*
* case 1: {
* if (fieldType === Thrift.Type.I32) {
* this.id = input.readI32();
* }
* else {
* input.skip(fieldType);
* }
* break;
* }
*/
export function createCaseForField(
node: UnionDefinition,
field: FieldDefinition,
state: IRenderState,
): ts.CaseClause {
const fieldAlias: ts.Identifier = ts.createUniqueName('value')
const checkType: ts.IfStatement = ts.createIf(
createEqualsCheck(
COMMON_IDENTIFIERS.fieldType,
thriftTypeForFieldType(field.fieldType, state),
),
ts.createBlock(
[
incrementFieldsSet(),
...readValueForFieldType(field.fieldType, fieldAlias, state),
...endReadForField(node, fieldAlias, field),
],
true,
),
createSkipBlock(),
)
if (field.fieldID !== null) {
return ts.createCaseClause(ts.createLiteral(field.fieldID.value), [
checkType,
ts.createBreak(),
])
} else {
throw new Error(`FieldID on line ${field.loc.start.line} is null`)
}
}
function endReadForField(
node: UnionDefinition,
fieldName: ts.Identifier,
field: FieldDefinition,
): Array<ts.Statement> {
switch (field.fieldType.type) {
case SyntaxType.VoidKeyword:
return []
default:
return [
ts.createStatement(
ts.createAssignment(
COMMON_IDENTIFIERS._returnValue,
ts.createCall(
ts.createPropertyAccess(
ts.createIdentifier(node.name.value),
createFactoryNameForField(field),
),
undefined,
[fieldName],
),
),
),
]
}
}
/**
* if (fieldsSet > 1) {
* throw new Thrift.TProtocolException(TProtocolExceptionType.INVALID_DATA, "Cannot read a TUnion with more than one set value!");
* }
* else if (fieldsSet < 1) {
* throw new Thrift.TProtocolException(TProtocolExceptionType.INVALID_DATA, "Cannot read a TUnion with no set value!");
* }
*/
export function createFieldValidation(
node: UnionDefinition,
withElse: boolean = false,
): ts.IfStatement {
return ts.createIf(
ts.createBinary(
COMMON_IDENTIFIERS._fieldsSet,
ts.SyntaxKind.GreaterThanToken,
ts.createLiteral(1),
),
ts.createBlock(
[
throwProtocolException(
'INVALID_DATA',
'Cannot read a TUnion with more than one set value!',
),
],
true,
),
ts.createIf(
ts.createBinary(
COMMON_IDENTIFIERS._fieldsSet,
ts.SyntaxKind.LessThanToken,
ts.createLiteral(1),
),
ts.createBlock(
[
throwProtocolException(
'INVALID_DATA',
'Cannot read a TUnion with no set value!',
),
],
true,
),
),
)
}
// let fieldsSet: number = 0;
export function createFieldIncrementer(): ts.VariableStatement {
return createLetStatement(
COMMON_IDENTIFIERS._fieldsSet,
createNumberType(),
ts.createLiteral(0),
)
}
// fieldsSet++;
export function incrementFieldsSet(): ts.ExpressionStatement {
return ts.createStatement(
ts.createPostfixIncrement(COMMON_IDENTIFIERS._fieldsSet),
)
} | the_stack |
declare class GMSAddress extends NSObject implements NSCopying {
static alloc(): GMSAddress; // inherited from NSObject
static new(): GMSAddress; // inherited from NSObject
readonly administrativeArea: string;
readonly coordinate: CLLocationCoordinate2D;
readonly country: string;
readonly lines: NSArray<string>;
readonly locality: string;
readonly postalCode: string;
readonly subLocality: string;
readonly thoroughfare: string;
addressLine1(): string;
addressLine2(): string;
copyWithZone(zone: interop.Pointer | interop.Reference<any>): any;
}
declare class GMSCALayer extends CALayer {
static alloc(): GMSCALayer; // inherited from NSObject
static layer(): GMSCALayer; // inherited from CALayer
static new(): GMSCALayer; // inherited from NSObject
}
declare class GMSCameraPosition extends NSObject implements NSCopying, NSMutableCopying {
static alloc(): GMSCameraPosition; // inherited from NSObject
static cameraWithLatitudeLongitudeZoom(latitude: number, longitude: number, zoom: number): GMSCameraPosition;
static cameraWithLatitudeLongitudeZoomBearingViewingAngle(latitude: number, longitude: number, zoom: number, bearing: number, viewingAngle: number): GMSCameraPosition;
static cameraWithTargetZoom(target: CLLocationCoordinate2D, zoom: number): GMSCameraPosition;
static cameraWithTargetZoomBearingViewingAngle(target: CLLocationCoordinate2D, zoom: number, bearing: number, viewingAngle: number): GMSCameraPosition;
static new(): GMSCameraPosition; // inherited from NSObject
static zoomAtCoordinateForMetersPerPoints(coordinate: CLLocationCoordinate2D, meters: number, points: number): number;
readonly bearing: number;
readonly target: CLLocationCoordinate2D;
readonly viewingAngle: number;
readonly zoom: number;
constructor(o: { target: CLLocationCoordinate2D; zoom: number; bearing: number; viewingAngle: number; });
copyWithZone(zone: interop.Pointer | interop.Reference<any>): any;
initWithTargetZoomBearingViewingAngle(target: CLLocationCoordinate2D, zoom: number, bearing: number, viewingAngle: number): this;
mutableCopyWithZone(zone: interop.Pointer | interop.Reference<any>): any;
}
declare class GMSCameraUpdate extends NSObject {
static alloc(): GMSCameraUpdate; // inherited from NSObject
static fitBounds(bounds: GMSCoordinateBounds): GMSCameraUpdate;
static fitBoundsWithEdgeInsets(bounds: GMSCoordinateBounds, edgeInsets: UIEdgeInsets): GMSCameraUpdate;
static fitBoundsWithPadding(bounds: GMSCoordinateBounds, padding: number): GMSCameraUpdate;
static new(): GMSCameraUpdate; // inherited from NSObject
static scrollByXY(dX: number, dY: number): GMSCameraUpdate;
static setCamera(camera: GMSCameraPosition): GMSCameraUpdate;
static setTarget(target: CLLocationCoordinate2D): GMSCameraUpdate;
static setTargetZoom(target: CLLocationCoordinate2D, zoom: number): GMSCameraUpdate;
static zoomBy(delta: number): GMSCameraUpdate;
static zoomByAtPoint(zoom: number, point: CGPoint): GMSCameraUpdate;
static zoomIn(): GMSCameraUpdate;
static zoomOut(): GMSCameraUpdate;
static zoomTo(zoom: number): GMSCameraUpdate;
}
declare class GMSCircle extends GMSOverlay {
static alloc(): GMSCircle; // inherited from NSObject
static circleWithPositionRadius(position: CLLocationCoordinate2D, radius: number): GMSCircle;
static new(): GMSCircle; // inherited from NSObject
fillColor: UIColor;
position: CLLocationCoordinate2D;
radius: number;
strokeColor: UIColor;
strokeWidth: number;
}
declare const enum GMSFrameRate {
kGMSFrameRatePowerSave = 0,
kGMSFrameRateConservative = 1,
kGMSFrameRateMaximum = 2
}
declare class GMSGeocoder extends NSObject {
static alloc(): GMSGeocoder; // inherited from NSObject
static geocoder(): GMSGeocoder;
static new(): GMSGeocoder; // inherited from NSObject
reverseGeocodeCoordinateCompletionHandler(coordinate: CLLocationCoordinate2D, handler: (p1: GMSReverseGeocodeResponse, p2: NSError) => void): void;
}
declare const enum GMSGeocoderErrorCode {
kGMSGeocoderErrorInvalidCoordinate = 1,
kGMSGeocoderErrorInternal = 2
}
declare function GMSGeometryArea(path: GMSPath): number;
declare function GMSGeometryContainsLocation(point: CLLocationCoordinate2D, path: GMSPath, geodesic: boolean): boolean;
declare function GMSGeometryDistance(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D): number;
declare function GMSGeometryHeading(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D): number;
declare function GMSGeometryInterpolate(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D, fraction: number): CLLocationCoordinate2D;
declare function GMSGeometryIsLocationOnPath(point: CLLocationCoordinate2D, path: GMSPath, geodesic: boolean): boolean;
declare function GMSGeometryIsLocationOnPathTolerance(point: CLLocationCoordinate2D, path: GMSPath, geodesic: boolean, tolerance: number): boolean;
declare function GMSGeometryLength(path: GMSPath): number;
declare function GMSGeometryOffset(from: CLLocationCoordinate2D, distance: number, heading: number): CLLocationCoordinate2D;
declare function GMSGeometrySignedArea(path: GMSPath): number;
declare class GMSGroundOverlay extends GMSOverlay {
static alloc(): GMSGroundOverlay; // inherited from NSObject
static groundOverlayWithBoundsIcon(bounds: GMSCoordinateBounds, icon: UIImage): GMSGroundOverlay;
static groundOverlayWithPositionIconZoomLevel(position: CLLocationCoordinate2D, icon: UIImage, zoomLevel: number): GMSGroundOverlay;
static new(): GMSGroundOverlay; // inherited from NSObject
anchor: CGPoint;
bearing: number;
bounds: GMSCoordinateBounds;
icon: UIImage;
opacity: number;
position: CLLocationCoordinate2D;
}
declare class GMSIndoorBuilding extends NSObject {
static alloc(): GMSIndoorBuilding; // inherited from NSObject
static new(): GMSIndoorBuilding; // inherited from NSObject
readonly defaultLevelIndex: number;
readonly levels: NSArray<GMSIndoorLevel>;
readonly underground: boolean;
}
declare class GMSIndoorDisplay extends NSObject {
static alloc(): GMSIndoorDisplay; // inherited from NSObject
static new(): GMSIndoorDisplay; // inherited from NSObject
readonly activeBuilding: GMSIndoorBuilding;
activeLevel: GMSIndoorLevel;
delegate: GMSIndoorDisplayDelegate;
}
interface GMSIndoorDisplayDelegate extends NSObjectProtocol {
didChangeActiveBuilding?(building: GMSIndoorBuilding): void;
didChangeActiveLevel?(level: GMSIndoorLevel): void;
}
declare var GMSIndoorDisplayDelegate: {
prototype: GMSIndoorDisplayDelegate;
};
declare class GMSIndoorLevel extends NSObject {
static alloc(): GMSIndoorLevel; // inherited from NSObject
static new(): GMSIndoorLevel; // inherited from NSObject
readonly name: string;
readonly shortName: string;
}
declare const enum GMSLengthKind {
kGMSLengthGeodesic = 0,
kGMSLengthRhumb = 1,
kGMSLengthProjected = 2
}
declare class GMSMapLayer extends GMSCALayer {
static alloc(): GMSMapLayer; // inherited from NSObject
static layer(): GMSMapLayer; // inherited from CALayer
static new(): GMSMapLayer; // inherited from NSObject
cameraBearing: number;
cameraLatitude: number;
cameraLongitude: number;
cameraViewingAngle: number;
cameraZoomLevel: number;
}
interface GMSMapPoint {
x: number;
y: number;
}
declare var GMSMapPoint: interop.StructType<GMSMapPoint>;
declare function GMSMapPointDistance(a: GMSMapPoint, b: GMSMapPoint): number;
declare function GMSMapPointInterpolate(a: GMSMapPoint, b: GMSMapPoint, t: number): GMSMapPoint;
declare class GMSMapStyle extends NSObject {
static alloc(): GMSMapStyle; // inherited from NSObject
static new(): GMSMapStyle; // inherited from NSObject
static styleWithContentsOfFileURLError(fileURL: NSURL): GMSMapStyle;
static styleWithJSONStringError(style: string): GMSMapStyle;
}
declare class GMSMapView extends UIView {
static alloc(): GMSMapView; // inherited from NSObject
static appearance(): GMSMapView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): GMSMapView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): GMSMapView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): GMSMapView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): GMSMapView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): GMSMapView; // inherited from UIAppearance
static mapWithFrameCamera(frame: CGRect, camera: GMSCameraPosition): GMSMapView;
static new(): GMSMapView; // inherited from NSObject
buildingsEnabled: boolean;
camera: GMSCameraPosition;
cameraTargetBounds: GMSCoordinateBounds;
delegate: GMSMapViewDelegate;
readonly indoorDisplay: GMSIndoorDisplay;
indoorEnabled: boolean;
readonly layer: GMSMapLayer;
mapStyle: GMSMapStyle;
mapType: GMSMapViewType;
readonly maxZoom: number;
readonly minZoom: number;
readonly myLocation: CLLocation;
myLocationEnabled: boolean;
padding: UIEdgeInsets;
paddingAdjustmentBehavior: GMSMapViewPaddingAdjustmentBehavior;
preferredFrameRate: GMSFrameRate;
readonly projection: GMSProjection;
selectedMarker: GMSMarker;
readonly settings: GMSUISettings;
trafficEnabled: boolean;
animateToBearing(bearing: number): void;
animateToCameraPosition(cameraPosition: GMSCameraPosition): void;
animateToLocation(location: CLLocationCoordinate2D): void;
animateToViewingAngle(viewingAngle: number): void;
animateToZoom(zoom: number): void;
animateWithCameraUpdate(cameraUpdate: GMSCameraUpdate): void;
areEqualForRenderingPositionPosition(position: GMSCameraPosition, otherPosition: GMSCameraPosition): boolean;
cameraForBoundsInsets(bounds: GMSCoordinateBounds, insets: UIEdgeInsets): GMSCameraPosition;
clear(): void;
moveCamera(update: GMSCameraUpdate): void;
setMinZoomMaxZoom(minZoom: number, maxZoom: number): void;
startRendering(): void;
stopRendering(): void;
}
interface GMSMapViewDelegate extends NSObjectProtocol {
didTapMyLocationButtonForMapView?(mapView: GMSMapView): boolean;
mapViewDidBeginDraggingMarker?(mapView: GMSMapView, marker: GMSMarker): void;
mapViewDidChangeCameraPosition?(mapView: GMSMapView, position: GMSCameraPosition): void;
mapViewDidCloseInfoWindowOfMarker?(mapView: GMSMapView, marker: GMSMarker): void;
mapViewDidDragMarker?(mapView: GMSMapView, marker: GMSMarker): void;
mapViewDidEndDraggingMarker?(mapView: GMSMapView, marker: GMSMarker): void;
mapViewDidFinishTileRendering?(mapView: GMSMapView): void;
mapViewDidLongPressAtCoordinate?(mapView: GMSMapView, coordinate: CLLocationCoordinate2D): void;
mapViewDidLongPressInfoWindowOfMarker?(mapView: GMSMapView, marker: GMSMarker): void;
mapViewDidStartTileRendering?(mapView: GMSMapView): void;
mapViewDidTapAtCoordinate?(mapView: GMSMapView, coordinate: CLLocationCoordinate2D): void;
mapViewDidTapInfoWindowOfMarker?(mapView: GMSMapView, marker: GMSMarker): void;
mapViewDidTapMarker?(mapView: GMSMapView, marker: GMSMarker): boolean;
mapViewDidTapMyLocation?(mapView: GMSMapView, location: CLLocationCoordinate2D): void;
mapViewDidTapOverlay?(mapView: GMSMapView, overlay: GMSOverlay): void;
mapViewDidTapPOIWithPlaceIDNameLocation?(mapView: GMSMapView, placeID: string, name: string, location: CLLocationCoordinate2D): void;
mapViewIdleAtCameraPosition?(mapView: GMSMapView, position: GMSCameraPosition): void;
mapViewMarkerInfoContents?(mapView: GMSMapView, marker: GMSMarker): UIView;
mapViewMarkerInfoWindow?(mapView: GMSMapView, marker: GMSMarker): UIView;
mapViewSnapshotReady?(mapView: GMSMapView): void;
mapViewWillMove?(mapView: GMSMapView, gesture: boolean): void;
}
declare var GMSMapViewDelegate: {
prototype: GMSMapViewDelegate;
};
declare const enum GMSMapViewPaddingAdjustmentBehavior {
kGMSMapViewPaddingAdjustmentBehaviorAlways = 0,
kGMSMapViewPaddingAdjustmentBehaviorAutomatic = 1,
kGMSMapViewPaddingAdjustmentBehaviorNever = 2
}
declare const enum GMSMapViewType {
kGMSTypeNormal = 1,
kGMSTypeSatellite = 2,
kGMSTypeTerrain = 3,
kGMSTypeHybrid = 4,
kGMSTypeNone = 5
}
declare class GMSMarker extends GMSOverlay {
static alloc(): GMSMarker; // inherited from NSObject
static markerImageWithColor(color: UIColor): UIImage;
static markerWithPosition(position: CLLocationCoordinate2D): GMSMarker;
static new(): GMSMarker; // inherited from NSObject
appearAnimation: GMSMarkerAnimation;
draggable: boolean;
flat: boolean;
groundAnchor: CGPoint;
icon: UIImage;
iconView: UIView;
infoWindowAnchor: CGPoint;
readonly layer: GMSMarkerLayer;
opacity: number;
panoramaView: GMSPanoramaView;
position: CLLocationCoordinate2D;
rotation: number;
snippet: string;
tracksInfoWindowChanges: boolean;
tracksViewChanges: boolean;
}
declare const enum GMSMarkerAnimation {
kGMSMarkerAnimationNone = 0,
kGMSMarkerAnimationPop = 1
}
declare class GMSMarkerLayer extends GMSOverlayLayer {
static alloc(): GMSMarkerLayer; // inherited from NSObject
static layer(): GMSMarkerLayer; // inherited from CALayer
static new(): GMSMarkerLayer; // inherited from NSObject
latitude: number;
longitude: number;
rotation: number;
}
declare class GMSMutableCameraPosition extends GMSCameraPosition {
static alloc(): GMSMutableCameraPosition; // inherited from NSObject
static cameraWithLatitudeLongitudeZoom(latitude: number, longitude: number, zoom: number): GMSMutableCameraPosition; // inherited from GMSCameraPosition
static cameraWithLatitudeLongitudeZoomBearingViewingAngle(latitude: number, longitude: number, zoom: number, bearing: number, viewingAngle: number): GMSMutableCameraPosition; // inherited from GMSCameraPosition
static cameraWithTargetZoom(target: CLLocationCoordinate2D, zoom: number): GMSMutableCameraPosition; // inherited from GMSCameraPosition
static cameraWithTargetZoomBearingViewingAngle(target: CLLocationCoordinate2D, zoom: number, bearing: number, viewingAngle: number): GMSMutableCameraPosition; // inherited from GMSCameraPosition
static new(): GMSMutableCameraPosition; // inherited from NSObject
bearing: number;
target: CLLocationCoordinate2D;
viewingAngle: number;
zoom: number;
}
declare class GMSMutablePath extends GMSPath {
static alloc(): GMSMutablePath; // inherited from NSObject
static new(): GMSMutablePath; // inherited from NSObject
static path(): GMSMutablePath; // inherited from GMSPath
static pathFromEncodedPath(encodedPath: string): GMSMutablePath; // inherited from GMSPath
addCoordinate(coord: CLLocationCoordinate2D): void;
addLatitudeLongitude(latitude: number, longitude: number): void;
insertCoordinateAtIndex(coord: CLLocationCoordinate2D, index: number): void;
removeAllCoordinates(): void;
removeCoordinateAtIndex(index: number): void;
removeLastCoordinate(): void;
replaceCoordinateAtIndexWithCoordinate(index: number, coord: CLLocationCoordinate2D): void;
}
interface GMSOrientation {
heading: number;
pitch: number;
}
declare var GMSOrientation: interop.StructType<GMSOrientation>;
declare class GMSOverlay extends NSObject implements NSCopying {
static alloc(): GMSOverlay; // inherited from NSObject
static new(): GMSOverlay; // inherited from NSObject
map: GMSMapView;
tappable: boolean;
title: string;
userData: any;
zIndex: number;
copyWithZone(zone: interop.Pointer | interop.Reference<any>): any;
}
declare class GMSOverlayLayer extends CALayer {
static alloc(): GMSOverlayLayer; // inherited from NSObject
static layer(): GMSOverlayLayer; // inherited from CALayer
static new(): GMSOverlayLayer; // inherited from NSObject
}
declare class GMSPanorama extends NSObject {
static alloc(): GMSPanorama; // inherited from NSObject
static new(): GMSPanorama; // inherited from NSObject
readonly coordinate: CLLocationCoordinate2D;
readonly links: NSArray<GMSPanoramaLink>;
readonly panoramaID: string;
}
declare class GMSPanoramaCamera extends NSObject {
static alloc(): GMSPanoramaCamera; // inherited from NSObject
static cameraWithHeadingPitchZoom(heading: number, pitch: number, zoom: number): GMSPanoramaCamera;
static cameraWithHeadingPitchZoomFOV(heading: number, pitch: number, zoom: number, FOV: number): GMSPanoramaCamera;
static cameraWithOrientationZoom(orientation: GMSOrientation, zoom: number): GMSPanoramaCamera;
static cameraWithOrientationZoomFOV(orientation: GMSOrientation, zoom: number, FOV: number): GMSPanoramaCamera;
static new(): GMSPanoramaCamera; // inherited from NSObject
readonly FOV: number;
readonly orientation: GMSOrientation;
readonly zoom: number;
constructor(o: { orientation: GMSOrientation; zoom: number; FOV: number; });
initWithOrientationZoomFOV(orientation: GMSOrientation, zoom: number, FOV: number): this;
}
declare class GMSPanoramaCameraUpdate extends NSObject {
static alloc(): GMSPanoramaCameraUpdate; // inherited from NSObject
static new(): GMSPanoramaCameraUpdate; // inherited from NSObject
static rotateBy(deltaHeading: number): GMSPanoramaCameraUpdate;
static setHeading(heading: number): GMSPanoramaCameraUpdate;
static setPitch(pitch: number): GMSPanoramaCameraUpdate;
static setZoom(zoom: number): GMSPanoramaCameraUpdate;
}
declare class GMSPanoramaLayer extends GMSCALayer {
static alloc(): GMSPanoramaLayer; // inherited from NSObject
static layer(): GMSPanoramaLayer; // inherited from CALayer
static new(): GMSPanoramaLayer; // inherited from NSObject
cameraFOV: number;
cameraHeading: number;
cameraPitch: number;
cameraZoom: number;
}
declare class GMSPanoramaLink extends NSObject {
static alloc(): GMSPanoramaLink; // inherited from NSObject
static new(): GMSPanoramaLink; // inherited from NSObject
heading: number;
panoramaID: string;
}
declare class GMSPanoramaService extends NSObject {
static alloc(): GMSPanoramaService; // inherited from NSObject
static new(): GMSPanoramaService; // inherited from NSObject
requestPanoramaNearCoordinateCallback(coordinate: CLLocationCoordinate2D, callback: (p1: GMSPanorama, p2: NSError) => void): void;
requestPanoramaNearCoordinateRadiusCallback(coordinate: CLLocationCoordinate2D, radius: number, callback: (p1: GMSPanorama, p2: NSError) => void): void;
requestPanoramaNearCoordinateRadiusSourceCallback(coordinate: CLLocationCoordinate2D, radius: number, source: GMSPanoramaSource, callback: (p1: GMSPanorama, p2: NSError) => void): void;
requestPanoramaNearCoordinateSourceCallback(coordinate: CLLocationCoordinate2D, source: GMSPanoramaSource, callback: (p1: GMSPanorama, p2: NSError) => void): void;
requestPanoramaWithIDCallback(panoramaID: string, callback: (p1: GMSPanorama, p2: NSError) => void): void;
}
declare const enum GMSPanoramaSource {
kGMSPanoramaSourceDefault = 0,
kGMSPanoramaSourceOutside = 1
}
declare class GMSPanoramaView extends UIView {
static alloc(): GMSPanoramaView; // inherited from NSObject
static appearance(): GMSPanoramaView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): GMSPanoramaView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): GMSPanoramaView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): GMSPanoramaView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): GMSPanoramaView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): GMSPanoramaView; // inherited from UIAppearance
static new(): GMSPanoramaView; // inherited from NSObject
static panoramaWithFrameNearCoordinate(frame: CGRect, coordinate: CLLocationCoordinate2D): GMSPanoramaView;
static panoramaWithFrameNearCoordinateRadius(frame: CGRect, coordinate: CLLocationCoordinate2D, radius: number): GMSPanoramaView;
static panoramaWithFrameNearCoordinateRadiusSource(frame: CGRect, coordinate: CLLocationCoordinate2D, radius: number, source: GMSPanoramaSource): GMSPanoramaView;
static panoramaWithFrameNearCoordinateSource(frame: CGRect, coordinate: CLLocationCoordinate2D, source: GMSPanoramaSource): GMSPanoramaView;
camera: GMSPanoramaCamera;
delegate: GMSPanoramaViewDelegate;
readonly layer: GMSPanoramaLayer;
navigationGestures: boolean;
navigationLinksHidden: boolean;
orientationGestures: boolean;
panorama: GMSPanorama;
streetNamesHidden: boolean;
zoomGestures: boolean;
animateToCameraAnimationDuration(camera: GMSPanoramaCamera, duration: number): void;
moveNearCoordinate(coordinate: CLLocationCoordinate2D): void;
moveNearCoordinateRadius(coordinate: CLLocationCoordinate2D, radius: number): void;
moveNearCoordinateRadiusSource(coordinate: CLLocationCoordinate2D, radius: number, source: GMSPanoramaSource): void;
moveNearCoordinateSource(coordinate: CLLocationCoordinate2D, source: GMSPanoramaSource): void;
moveToPanoramaID(panoramaID: string): void;
orientationForPoint(point: CGPoint): GMSOrientation;
pointForOrientation(orientation: GMSOrientation): CGPoint;
setAllGesturesEnabled(enabled: boolean): void;
updateCameraAnimationDuration(cameraUpdate: GMSPanoramaCameraUpdate, duration: number): void;
}
interface GMSPanoramaViewDelegate extends NSObjectProtocol {
panoramaViewDidFinishRendering?(panoramaView: GMSPanoramaView): void;
panoramaViewDidMoveCamera?(panoramaView: GMSPanoramaView, camera: GMSPanoramaCamera): void;
panoramaViewDidMoveToPanorama?(view: GMSPanoramaView, panorama: GMSPanorama): void;
panoramaViewDidMoveToPanoramaNearCoordinate?(view: GMSPanoramaView, panorama: GMSPanorama, coordinate: CLLocationCoordinate2D): void;
panoramaViewDidStartRendering?(panoramaView: GMSPanoramaView): void;
panoramaViewDidTap?(panoramaView: GMSPanoramaView, point: CGPoint): void;
panoramaViewDidTapMarker?(panoramaView: GMSPanoramaView, marker: GMSMarker): boolean;
panoramaViewErrorOnMoveNearCoordinate?(view: GMSPanoramaView, error: NSError, coordinate: CLLocationCoordinate2D): void;
panoramaViewErrorOnMoveToPanoramaID?(view: GMSPanoramaView, error: NSError, panoramaID: string): void;
panoramaViewWillMoveToPanoramaID?(view: GMSPanoramaView, panoramaID: string): void;
}
declare var GMSPanoramaViewDelegate: {
prototype: GMSPanoramaViewDelegate;
};
declare class GMSPath extends NSObject implements NSCopying, NSMutableCopying {
static alloc(): GMSPath; // inherited from NSObject
static new(): GMSPath; // inherited from NSObject
static path(): GMSPath;
static pathFromEncodedPath(encodedPath: string): GMSPath;
constructor(o: { path: GMSPath; });
coordinateAtIndex(index: number): CLLocationCoordinate2D;
copyWithZone(zone: interop.Pointer | interop.Reference<any>): any;
count(): number;
encodedPath(): string;
initWithPath(path: GMSPath): this;
lengthOfKind(kind: GMSLengthKind): number;
mutableCopyWithZone(zone: interop.Pointer | interop.Reference<any>): any;
pathOffsetByLatitudeLongitude(deltaLatitude: number, deltaLongitude: number): this;
segmentsForLengthKind(length: number, kind: GMSLengthKind): number;
}
declare class GMSPolygon extends GMSOverlay {
static alloc(): GMSPolygon; // inherited from NSObject
static new(): GMSPolygon; // inherited from NSObject
static polygonWithPath(path: GMSPath): GMSPolygon;
fillColor: UIColor;
geodesic: boolean;
holes: NSArray<GMSPath>;
path: GMSPath;
strokeColor: UIColor;
strokeWidth: number;
}
declare class GMSPolyline extends GMSOverlay {
static alloc(): GMSPolyline; // inherited from NSObject
static new(): GMSPolyline; // inherited from NSObject
static polylineWithPath(path: GMSPath): GMSPolyline;
geodesic: boolean;
path: GMSPath;
spans: NSArray<GMSStyleSpan>;
strokeColor: UIColor;
strokeWidth: number;
}
declare function GMSProject(coordinate: CLLocationCoordinate2D): GMSMapPoint;
declare class GMSProjection extends NSObject {
static alloc(): GMSProjection; // inherited from NSObject
static new(): GMSProjection; // inherited from NSObject
containsCoordinate(coordinate: CLLocationCoordinate2D): boolean;
coordinateForPoint(point: CGPoint): CLLocationCoordinate2D;
pointForCoordinate(coordinate: CLLocationCoordinate2D): CGPoint;
pointsForMetersAtCoordinate(meters: number, coordinate: CLLocationCoordinate2D): number;
visibleRegion(): GMSVisibleRegion;
}
declare class GMSReverseGeocodeResponse extends NSObject implements NSCopying {
static alloc(): GMSReverseGeocodeResponse; // inherited from NSObject
static new(): GMSReverseGeocodeResponse; // inherited from NSObject
copyWithZone(zone: interop.Pointer | interop.Reference<any>): any;
firstResult(): GMSAddress;
results(): NSArray<GMSAddress>;
}
declare class GMSServices extends NSObject {
static SDKVersion(): string;
static alloc(): GMSServices; // inherited from NSObject
static new(): GMSServices; // inherited from NSObject
static openSourceLicenseInfo(): string;
static provideAPIKey(APIKey: string): boolean;
static provideAPIOptions(APIOptions: NSArray<string>): boolean;
static sharedServices(): NSObjectProtocol;
}
declare class GMSStrokeStyle extends NSObject {
static alloc(): GMSStrokeStyle; // inherited from NSObject
static gradientFromColorToColor(fromColor: UIColor, toColor: UIColor): GMSStrokeStyle;
static new(): GMSStrokeStyle; // inherited from NSObject
static solidColor(color: UIColor): GMSStrokeStyle;
}
declare class GMSStyleSpan extends NSObject {
static alloc(): GMSStyleSpan; // inherited from NSObject
static new(): GMSStyleSpan; // inherited from NSObject
static spanWithColor(color: UIColor): GMSStyleSpan;
static spanWithColorSegments(color: UIColor, segments: number): GMSStyleSpan;
static spanWithStyle(style: GMSStrokeStyle): GMSStyleSpan;
static spanWithStyleSegments(style: GMSStrokeStyle, segments: number): GMSStyleSpan;
readonly segments: number;
readonly style: GMSStrokeStyle;
}
declare function GMSStyleSpans(path: GMSPath, styles: NSArray<GMSStrokeStyle>, lengths: NSArray<number>, lengthKind: GMSLengthKind): NSArray<GMSStyleSpan>;
declare function GMSStyleSpansOffset(path: GMSPath, styles: NSArray<GMSStrokeStyle>, lengths: NSArray<number>, lengthKind: GMSLengthKind, lengthOffset: number): NSArray<GMSStyleSpan>;
declare class GMSSyncTileLayer extends GMSTileLayer {
static alloc(): GMSSyncTileLayer; // inherited from NSObject
static new(): GMSSyncTileLayer; // inherited from NSObject
tileForXYZoom(x: number, y: number, zoom: number): UIImage;
}
declare class GMSTileLayer extends NSObject {
static alloc(): GMSTileLayer; // inherited from NSObject
static new(): GMSTileLayer; // inherited from NSObject
fadeIn: boolean;
map: GMSMapView;
opacity: number;
tileSize: number;
zIndex: number;
clearTileCache(): void;
requestTileForXYZoomReceiver(x: number, y: number, zoom: number, receiver: GMSTileReceiver): void;
}
interface GMSTileReceiver extends NSObjectProtocol {
receiveTileWithXYZoomImage(x: number, y: number, zoom: number, image: UIImage): void;
}
declare var GMSTileReceiver: {
prototype: GMSTileReceiver;
};
declare class GMSUISettings extends NSObject {
static alloc(): GMSUISettings; // inherited from NSObject
static new(): GMSUISettings; // inherited from NSObject
allowScrollGesturesDuringRotateOrZoom: boolean;
compassButton: boolean;
consumesGesturesInView: boolean;
indoorPicker: boolean;
myLocationButton: boolean;
rotateGestures: boolean;
scrollGestures: boolean;
tiltGestures: boolean;
zoomGestures: boolean;
setAllGesturesEnabled(enabled: boolean): void;
}
declare class GMSURLTileLayer extends GMSTileLayer {
static alloc(): GMSURLTileLayer; // inherited from NSObject
static new(): GMSURLTileLayer; // inherited from NSObject
static tileLayerWithURLConstructor(constructor: (p1: number, p2: number, p3: number) => NSURL): GMSURLTileLayer;
userAgent: string;
}
declare function GMSUnproject(point: GMSMapPoint): CLLocationCoordinate2D;
interface GMSVisibleRegion {
nearLeft: CLLocationCoordinate2D;
nearRight: CLLocationCoordinate2D;
farLeft: CLLocationCoordinate2D;
farRight: CLLocationCoordinate2D;
}
declare var GMSVisibleRegion: interop.StructType<GMSVisibleRegion>;
declare var kGMSAccessibilityCompass: string;
declare var kGMSAccessibilityMyLocation: string;
declare var kGMSEarthRadius: number;
declare var kGMSEquatorProjectedMeter: number;
declare var kGMSGroundOverlayDefaultAnchor: CGPoint;
declare var kGMSLayerCameraBearingKey: string;
declare var kGMSLayerCameraLatitudeKey: string;
declare var kGMSLayerCameraLongitudeKey: string;
declare var kGMSLayerCameraViewingAngleKey: string;
declare var kGMSLayerCameraZoomLevelKey: string;
declare var kGMSLayerPanoramaFOVKey: string;
declare var kGMSLayerPanoramaHeadingKey: string;
declare var kGMSLayerPanoramaPitchKey: string;
declare var kGMSLayerPanoramaZoomKey: string;
declare var kGMSMarkerDefaultGroundAnchor: CGPoint;
declare var kGMSMarkerDefaultInfoWindowAnchor: CGPoint;
declare var kGMSMarkerLayerLatitude: string;
declare var kGMSMarkerLayerLongitude: string;
declare var kGMSMarkerLayerOpacity: string;
declare var kGMSMarkerLayerRotation: string;
declare var kGMSMaxZoomLevel: number;
declare var kGMSMinZoomLevel: number;
declare var kGMSTileLayerNoTile: UIImage; | the_stack |
import { async, ComponentFixture, TestBed } from "@angular/core/testing";
import { FormsModule } from "@angular/forms";
import { ApproveBuildComponent } from "./approve-build.component";
import { IdpService } from "../idp-service.service";
import { IdpdataService } from "../idpdata.service";
import { IdprestapiService } from "../idprestapi.service";
import { Router, NavigationExtras } from "@angular/router";
import { ParentFormConnectComponent } from "../parent-form-connect/parent-form-connect.component";
import { TranslateModule , TranslateService, TranslateLoader, TranslateParser} from "ng2-translate";
import { NO_ERRORS_SCHEMA} from "@angular/core";
import { IDPEncryption } from "../idpencryption.service";
import { IdpSubmitService } from "../idpsubmit.service";
import { ViewChild } from "@angular/core";
describe("ApproveBuildComponent", () => {
let component: ApproveBuildComponent;
let fixture: ComponentFixture<ApproveBuildComponent>;
let idpService: IdpService;
let idpdataService: IdpdataService;
let idprestapiService: IdprestapiService;
let idpEncryption: IDPEncryption;
let router: Router;
let idpsubmitService: IdpSubmitService;
class IdpdataServiceStub {
constructor() {}
template: any = {
"grantAccess": {
"applicationName": "TestMaven",
"developers": [],
"pipelineAdmins": [],
"releaseManager": [],
"environmentOwnerDetails": [{
"environmentName": "",
"environmentOwners": [],
"dbOwners": []
}],
"slaveDetails": [
{
"slaveName": "",
"buildServerOS": "",
"workspacePath": "",
"createNewSlave": "",
"labels": "",
"sshKeyPath": "",
"slaveUsage": "both"
}
]
},
"basicInfo": {
"additionalMailRecipients": {
"applicationTeam": "",
"emailIds": ""
},
"applicationName": "TestMaven",
"buildInterval": {
"buildInterval": "",
"buildIntervalValue": 0,
"pollSCM": "off"
},
"buildServerOS": "windows",
"engine": "",
"pipelineName": "pipName"
},
"code": {
"category": "standard",
"technology": "",
"scm": [],
"buildScript": [{"tool": "", "antPropertiesArr": []}, {"tool": "", "antPropertiesArr": []}, {}]
},
"buildInfo": {
"buildtool": "",
"castAnalysis": {},
"artifactToStage": {},
"modules": []
},
"deployInfo": {
"deployEnv": [{"deploySteps": []}]
},
"testInfo": {
"testEnv": []
},
"formStatus": {
"basicInfo": {
"appNameStatus": "0",
"formStatus": "0"
},
"codeInfo": "",
"buildInfo": {
"buildToolStatus": "0",
"formStatus": "0",
"ibmsiTypeStatus": "0"
},
"deployInfo": "",
"testInfo": "",
"operation": ""
},
"checkboxStatus": {
"basicInfo": {},
"codeInfo": {},
"buildInfo": {},
"deployInfo": {},
"testInfo": {},
"others": {}
},
"backUp": {
"deployInfo": {},
"testInfo": {}
},
"allFormStatus": {"deployInfo": {}},
"masterJson": {},
};
releaseManagerTemplate: any = {
"applicationName": "",
"releasePipeline": [
{
"pipelineName": "",
"release": [
{
"actualEndDate": "",
"actualStartDate": "",
"additionalMailRecipients": {
"applicationTeam": "",
"emailIds": ""
},
"branchList": [
"na"
],
"expectedEndDate": "",
"expectedStartDate": "",
"releaseNumber": "",
"remarks": "",
"status": "on",
"vstsReleaseName": ""
}
]
}
]
};
passwordEncryptionList: any = {
"code.scm": ["password", "PSpassword"],
"code.buildScript": ["password"],
"buildInfo": ["password", "artifactToStage.artifactRepo.repoPassword", "postBuildScript.password"],
"buildInfo.modules": ["npmProxyPassword", "password", "pegaPassword", "destPassword", "siebelPassword", "ipcPassword",
"servPass", "publishForms.password", "publishForms.dbPassword",
"workFlowPublish.password", "workFlowPublish.dbPassword", "proxy.password", "sourcePassword"],
"deployInfo.deployEnv.deploySteps": ["password", "ipcPassword", "dbPassword", "dbpasswordOTM",
"dbPasswordOTM", "dbOwnerPassword", "bizPassword", "formsDbPass", "databasePassword", "ddltmpPassword",
"datExportPassword", "workFlowDbPass", "deployPassword", "scalaPassword", "pigPassword", "hivePassword", "dbPwd", "staticPassword",
"srfPassword", "admPassword", "adminPassword", "dbOwnerPassword", "appsPass", "tomPwd",
"runScript.password", "deployToContainer.password", "deployToContainer.adminPassword",
"deployToContainer.sshPassword", "deployToContainer.dbOwnerPassword",
"deployToContainer.staticFiles.password", "deployDatabase.restorpassword",
"deployDatabase.dbpassword", "targetPassword", "proxy.password"],
"testInfo.testEnv.testSteps": ["runScript.password", "test.password"],
"virtualServiceServerDetails": ["password"]
};
propertySCM: any = {
};
pipelineListRm= "";
releaseManagerData= JSON.parse(JSON.stringify(this.releaseManagerTemplate));
language = "english";
idpUserName = "";
roles = [];
azureadflag= false;
expireTime: any;
access_token: any;
permissions = [];
createAppflag = false;
createOrganisationflag = false;
createLicenseflag = false;
createPipelineflag = false;
copyPipelineflag = false;
editPipelineflag = false;
deletePipelineflag = false;
test = false;
loadReleasePage= false;
devServerURL: any = "";
subscriptionServerURL: any = "";
IDPDashboardURL = "";
IDPLink = "";
geUrl = "";
role = "";
profile = "";
pausedBuildsData: any= {};
checkPausedBuilds: any= false;
allFormStatus: any= {
"basicInfo": false,
"codeInfo": false,
"buildInfo": false,
"deployInfo": false,
"testInfo": false,
"workflowInfo": false
};
IDPDropdownProperties: any = {};
showConfig: any;
pa= true;
continuecontrol: any;
geFlag: any;
p: any = false;
ejbVal: any;
warVal: any;
jarVal: any;
cloudDeployURL: any;
pipelineData: any;
triggerJobData: any;
jobParamList: any;
application: any;
freezeNavBars= false;
osFlag: any;
op: any;
operation: any;
initMain: any = false;
RestApiDetails: any = false;
buildInfoReset = false;
compMove: any;
unit: any;
uName: any= "";
pass: any= "";
code: any;
serverUrl= "";
authorization= "";
unitTest: any= false;
artifactVariable: any= false;
artifactAppVariable: any= false;
public loading = false;
refreshBuild= false;
showRelease= false;
isSAPApplication= false;
checkpollALM: boolean ;
SAPScmCheck: any ;
authmode= "ldap";
adalConfig: any=
{"clientId": "",
"tenate": "",
"postLogoutRedirectUri": "",
"endpoints": {},
};
pipelineName= "";
appName= "";
pipelineNames: any;
releaseAddSuccess: boolean;
releaseUpdateSuccess: boolean;
releasePipelineName: "";
activeReleasePipelineName: "";
noPipelines: boolean;
hideDashboard: boolean;
sapNewFlag= false;
buildSubscription= false;
deploySubscription= false;
testSubscription= false;
buildSubscriptionSubmit= false;
deploySubscriptionSubmit= false;
noAccess: boolean;
showService: boolean;
flag: boolean;
noAccessNavBars: boolean;
scheduleJob: any;
schedulePage: any= false;
index: any;
buildIntervalData: any= [];
statusCheck: any= [];
workflowData: any = [];
workflowDataTemp: any = [];
createWorkflowSequenceflag= false;
workflowTrigger= false;
triggerWorkflowJobData: any;
approveBuildFlag: any= false;
approveDeployFlag: any= false;
keycloakToken: any;
organization: any;
keycloakUrl: any;
keycloakRealm: any;
keycloakClientId: any;
hideApp= false;
PagePersmission: any= {
"basic" : false,
"code" : false,
"build" : false,
"deploy": false,
"test": false
};
data= JSON.parse(JSON.stringify(this.template));
}
class IdpServiceStub {
copy(o) {
let newO, i;
if (typeof o !== "object") {
return o;
}
if (!o) {
return o;
}
if ("[object Array]" === Object.prototype.toString.apply(o)) {
newO = [];
for (i = 0; i < o.length; i += 1) {
newO[i] = this.copy(o[i]);
}
return newO;
}
newO = {};
for (i in o) {
if (o.hasOwnProperty(i)) {
newO[i] = this.copy(o[i]);
}
}
return newO;
}
}
class IdprestapiServiceStub {
getIDPDropdownProperties() {
const msBuildVersionObj = {
msBuildVersion: ""
};
return msBuildVersionObj;
}
}
class IDPEncryptionStub {
}
class IdpSubmitServiceStub {}
class RouterStub {
navigate(commands: any[], extras?: NavigationExtras) { }
}
const idpdataserviceStub: IdpdataServiceStub = new IdpdataServiceStub();
const routerStub: RouterStub = new RouterStub();
const idpServiceStub: IdpServiceStub = new IdpServiceStub();
const idprestapiServiceStub: IdprestapiServiceStub = new IdprestapiServiceStub();
const idpEncryptionStub: IDPEncryptionStub = new IDPEncryptionStub();
const idpSubmitServiceStub: IdpSubmitServiceStub = new IdpSubmitServiceStub();
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ApproveBuildComponent, ParentFormConnectComponent ],
imports: [FormsModule, TranslateModule],
providers: [{provide: IdprestapiService, useValue: idprestapiServiceStub},
{provide: IdpService, useValue: idpServiceStub},
{provide: IdpdataService, useValue: idpdataserviceStub},
{provide: IDPEncryption, useValue: idpEncryptionStub},
{provide: IdpSubmitService, useValue: idpSubmitServiceStub},
{provide: Router, useValue: routerStub},
TranslateService, TranslateLoader, TranslateParser
],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
router = TestBed.get(Router);
idpService = TestBed.get(IdpService);
idpdataService = TestBed.get(IdpdataService);
idprestapiService = TestBed.get(IdprestapiService);
idpsubmitService = TestBed.get(IdpSubmitService);
idpEncryption = TestBed.get(IDPEncryption);
fixture = TestBed.createComponent(ApproveBuildComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it("should create", () => {
expect(component).toBeTruthy();
});
it("should run", () => {
component.setBuildNum();
});
it("should run", () => {
component.setDetails("detail");
});
it("should run", () => {
component.submitAppr();
});
}); | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as Models from "../models";
import * as Mappers from "../models/configurationStoresMappers";
import * as Parameters from "../models/parameters";
import { AppConfigurationManagementClientContext } from "../appConfigurationManagementClientContext";
/** Class representing a ConfigurationStores. */
export class ConfigurationStores {
private readonly client: AppConfigurationManagementClientContext;
/**
* Create a ConfigurationStores.
* @param {AppConfigurationManagementClientContext} client Reference to the service client.
*/
constructor(client: AppConfigurationManagementClientContext) {
this.client = client;
}
/**
* Lists the configuration stores for a given subscription.
* @param [options] The optional parameters
* @returns Promise<Models.ConfigurationStoresListResponse>
*/
list(options?: Models.ConfigurationStoresListOptionalParams): Promise<Models.ConfigurationStoresListResponse>;
/**
* @param callback The callback
*/
list(callback: msRest.ServiceCallback<Models.ConfigurationStoreListResult>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
list(options: Models.ConfigurationStoresListOptionalParams, callback: msRest.ServiceCallback<Models.ConfigurationStoreListResult>): void;
list(options?: Models.ConfigurationStoresListOptionalParams | msRest.ServiceCallback<Models.ConfigurationStoreListResult>, callback?: msRest.ServiceCallback<Models.ConfigurationStoreListResult>): Promise<Models.ConfigurationStoresListResponse> {
return this.client.sendOperationRequest(
{
options
},
listOperationSpec,
callback) as Promise<Models.ConfigurationStoresListResponse>;
}
/**
* Lists the configuration stores for a given resource group.
* @param resourceGroupName The name of the resource group to which the container registry belongs.
* @param [options] The optional parameters
* @returns Promise<Models.ConfigurationStoresListByResourceGroupResponse>
*/
listByResourceGroup(resourceGroupName: string, options?: Models.ConfigurationStoresListByResourceGroupOptionalParams): Promise<Models.ConfigurationStoresListByResourceGroupResponse>;
/**
* @param resourceGroupName The name of the resource group to which the container registry belongs.
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.ConfigurationStoreListResult>): void;
/**
* @param resourceGroupName The name of the resource group to which the container registry belongs.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, options: Models.ConfigurationStoresListByResourceGroupOptionalParams, callback: msRest.ServiceCallback<Models.ConfigurationStoreListResult>): void;
listByResourceGroup(resourceGroupName: string, options?: Models.ConfigurationStoresListByResourceGroupOptionalParams | msRest.ServiceCallback<Models.ConfigurationStoreListResult>, callback?: msRest.ServiceCallback<Models.ConfigurationStoreListResult>): Promise<Models.ConfigurationStoresListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
options
},
listByResourceGroupOperationSpec,
callback) as Promise<Models.ConfigurationStoresListByResourceGroupResponse>;
}
/**
* Gets the properties of the specified configuration store.
* @param resourceGroupName The name of the resource group to which the container registry belongs.
* @param configStoreName The name of the configuration store.
* @param [options] The optional parameters
* @returns Promise<Models.ConfigurationStoresGetResponse>
*/
get(resourceGroupName: string, configStoreName: string, options?: msRest.RequestOptionsBase): Promise<Models.ConfigurationStoresGetResponse>;
/**
* @param resourceGroupName The name of the resource group to which the container registry belongs.
* @param configStoreName The name of the configuration store.
* @param callback The callback
*/
get(resourceGroupName: string, configStoreName: string, callback: msRest.ServiceCallback<Models.ConfigurationStore>): void;
/**
* @param resourceGroupName The name of the resource group to which the container registry belongs.
* @param configStoreName The name of the configuration store.
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, configStoreName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ConfigurationStore>): void;
get(resourceGroupName: string, configStoreName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ConfigurationStore>, callback?: msRest.ServiceCallback<Models.ConfigurationStore>): Promise<Models.ConfigurationStoresGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
configStoreName,
options
},
getOperationSpec,
callback) as Promise<Models.ConfigurationStoresGetResponse>;
}
/**
* Creates a configuration store with the specified parameters.
* @param resourceGroupName The name of the resource group to which the container registry belongs.
* @param configStoreName The name of the configuration store.
* @param configStoreCreationParameters The parameters for creating a configuration store.
* @param [options] The optional parameters
* @returns Promise<Models.ConfigurationStoresCreateResponse>
*/
create(resourceGroupName: string, configStoreName: string, configStoreCreationParameters: Models.ConfigurationStore, options?: msRest.RequestOptionsBase): Promise<Models.ConfigurationStoresCreateResponse> {
return this.beginCreate(resourceGroupName,configStoreName,configStoreCreationParameters,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.ConfigurationStoresCreateResponse>;
}
/**
* Deletes a configuration store.
* @param resourceGroupName The name of the resource group to which the container registry belongs.
* @param configStoreName The name of the configuration store.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(resourceGroupName: string, configStoreName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> {
return this.beginDeleteMethod(resourceGroupName,configStoreName,options)
.then(lroPoller => lroPoller.pollUntilFinished());
}
/**
* Updates a configuration store with the specified parameters.
* @param resourceGroupName The name of the resource group to which the container registry belongs.
* @param configStoreName The name of the configuration store.
* @param configStoreUpdateParameters The parameters for updating a configuration store.
* @param [options] The optional parameters
* @returns Promise<Models.ConfigurationStoresUpdateResponse>
*/
update(resourceGroupName: string, configStoreName: string, configStoreUpdateParameters: Models.ConfigurationStoreUpdateParameters, options?: msRest.RequestOptionsBase): Promise<Models.ConfigurationStoresUpdateResponse> {
return this.beginUpdate(resourceGroupName,configStoreName,configStoreUpdateParameters,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.ConfigurationStoresUpdateResponse>;
}
/**
* Lists the access key for the specified configuration store.
* @param resourceGroupName The name of the resource group to which the container registry belongs.
* @param configStoreName The name of the configuration store.
* @param [options] The optional parameters
* @returns Promise<Models.ConfigurationStoresListKeysResponse>
*/
listKeys(resourceGroupName: string, configStoreName: string, options?: Models.ConfigurationStoresListKeysOptionalParams): Promise<Models.ConfigurationStoresListKeysResponse>;
/**
* @param resourceGroupName The name of the resource group to which the container registry belongs.
* @param configStoreName The name of the configuration store.
* @param callback The callback
*/
listKeys(resourceGroupName: string, configStoreName: string, callback: msRest.ServiceCallback<Models.ApiKeyListResult>): void;
/**
* @param resourceGroupName The name of the resource group to which the container registry belongs.
* @param configStoreName The name of the configuration store.
* @param options The optional parameters
* @param callback The callback
*/
listKeys(resourceGroupName: string, configStoreName: string, options: Models.ConfigurationStoresListKeysOptionalParams, callback: msRest.ServiceCallback<Models.ApiKeyListResult>): void;
listKeys(resourceGroupName: string, configStoreName: string, options?: Models.ConfigurationStoresListKeysOptionalParams | msRest.ServiceCallback<Models.ApiKeyListResult>, callback?: msRest.ServiceCallback<Models.ApiKeyListResult>): Promise<Models.ConfigurationStoresListKeysResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
configStoreName,
options
},
listKeysOperationSpec,
callback) as Promise<Models.ConfigurationStoresListKeysResponse>;
}
/**
* Regenerates an access key for the specified configuration store.
* @param resourceGroupName The name of the resource group to which the container registry belongs.
* @param configStoreName The name of the configuration store.
* @param regenerateKeyParameters The parameters for regenerating an access key.
* @param [options] The optional parameters
* @returns Promise<Models.ConfigurationStoresRegenerateKeyResponse>
*/
regenerateKey(resourceGroupName: string, configStoreName: string, regenerateKeyParameters: Models.RegenerateKeyParameters, options?: msRest.RequestOptionsBase): Promise<Models.ConfigurationStoresRegenerateKeyResponse>;
/**
* @param resourceGroupName The name of the resource group to which the container registry belongs.
* @param configStoreName The name of the configuration store.
* @param regenerateKeyParameters The parameters for regenerating an access key.
* @param callback The callback
*/
regenerateKey(resourceGroupName: string, configStoreName: string, regenerateKeyParameters: Models.RegenerateKeyParameters, callback: msRest.ServiceCallback<Models.ApiKey>): void;
/**
* @param resourceGroupName The name of the resource group to which the container registry belongs.
* @param configStoreName The name of the configuration store.
* @param regenerateKeyParameters The parameters for regenerating an access key.
* @param options The optional parameters
* @param callback The callback
*/
regenerateKey(resourceGroupName: string, configStoreName: string, regenerateKeyParameters: Models.RegenerateKeyParameters, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ApiKey>): void;
regenerateKey(resourceGroupName: string, configStoreName: string, regenerateKeyParameters: Models.RegenerateKeyParameters, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ApiKey>, callback?: msRest.ServiceCallback<Models.ApiKey>): Promise<Models.ConfigurationStoresRegenerateKeyResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
configStoreName,
regenerateKeyParameters,
options
},
regenerateKeyOperationSpec,
callback) as Promise<Models.ConfigurationStoresRegenerateKeyResponse>;
}
/**
* Lists a configuration store key-value.
* @param resourceGroupName The name of the resource group to which the container registry belongs.
* @param configStoreName The name of the configuration store.
* @param listKeyValueParameters The parameters for retrieving a key-value.
* @param [options] The optional parameters
* @returns Promise<Models.ConfigurationStoresListKeyValueResponse>
*/
listKeyValue(resourceGroupName: string, configStoreName: string, listKeyValueParameters: Models.ListKeyValueParameters, options?: msRest.RequestOptionsBase): Promise<Models.ConfigurationStoresListKeyValueResponse>;
/**
* @param resourceGroupName The name of the resource group to which the container registry belongs.
* @param configStoreName The name of the configuration store.
* @param listKeyValueParameters The parameters for retrieving a key-value.
* @param callback The callback
*/
listKeyValue(resourceGroupName: string, configStoreName: string, listKeyValueParameters: Models.ListKeyValueParameters, callback: msRest.ServiceCallback<Models.KeyValue>): void;
/**
* @param resourceGroupName The name of the resource group to which the container registry belongs.
* @param configStoreName The name of the configuration store.
* @param listKeyValueParameters The parameters for retrieving a key-value.
* @param options The optional parameters
* @param callback The callback
*/
listKeyValue(resourceGroupName: string, configStoreName: string, listKeyValueParameters: Models.ListKeyValueParameters, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.KeyValue>): void;
listKeyValue(resourceGroupName: string, configStoreName: string, listKeyValueParameters: Models.ListKeyValueParameters, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.KeyValue>, callback?: msRest.ServiceCallback<Models.KeyValue>): Promise<Models.ConfigurationStoresListKeyValueResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
configStoreName,
listKeyValueParameters,
options
},
listKeyValueOperationSpec,
callback) as Promise<Models.ConfigurationStoresListKeyValueResponse>;
}
/**
* Creates a configuration store with the specified parameters.
* @param resourceGroupName The name of the resource group to which the container registry belongs.
* @param configStoreName The name of the configuration store.
* @param configStoreCreationParameters The parameters for creating a configuration store.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginCreate(resourceGroupName: string, configStoreName: string, configStoreCreationParameters: Models.ConfigurationStore, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
configStoreName,
configStoreCreationParameters,
options
},
beginCreateOperationSpec,
options);
}
/**
* Deletes a configuration store.
* @param resourceGroupName The name of the resource group to which the container registry belongs.
* @param configStoreName The name of the configuration store.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginDeleteMethod(resourceGroupName: string, configStoreName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
configStoreName,
options
},
beginDeleteMethodOperationSpec,
options);
}
/**
* Updates a configuration store with the specified parameters.
* @param resourceGroupName The name of the resource group to which the container registry belongs.
* @param configStoreName The name of the configuration store.
* @param configStoreUpdateParameters The parameters for updating a configuration store.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginUpdate(resourceGroupName: string, configStoreName: string, configStoreUpdateParameters: Models.ConfigurationStoreUpdateParameters, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
configStoreName,
configStoreUpdateParameters,
options
},
beginUpdateOperationSpec,
options);
}
/**
* Lists the configuration stores for a given subscription.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.ConfigurationStoresListNextResponse>
*/
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ConfigurationStoresListNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ConfigurationStoreListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ConfigurationStoreListResult>): void;
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ConfigurationStoreListResult>, callback?: msRest.ServiceCallback<Models.ConfigurationStoreListResult>): Promise<Models.ConfigurationStoresListNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listNextOperationSpec,
callback) as Promise<Models.ConfigurationStoresListNextResponse>;
}
/**
* Lists the configuration stores for a given resource group.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.ConfigurationStoresListByResourceGroupNextResponse>
*/
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ConfigurationStoresListByResourceGroupNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ConfigurationStoreListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ConfigurationStoreListResult>): void;
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ConfigurationStoreListResult>, callback?: msRest.ServiceCallback<Models.ConfigurationStoreListResult>): Promise<Models.ConfigurationStoresListByResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByResourceGroupNextOperationSpec,
callback) as Promise<Models.ConfigurationStoresListByResourceGroupNextResponse>;
}
/**
* Lists the access key for the specified configuration store.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.ConfigurationStoresListKeysNextResponse>
*/
listKeysNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ConfigurationStoresListKeysNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listKeysNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ApiKeyListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listKeysNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ApiKeyListResult>): void;
listKeysNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ApiKeyListResult>, callback?: msRest.ServiceCallback<Models.ApiKeyListResult>): Promise<Models.ConfigurationStoresListKeysNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listKeysNextOperationSpec,
callback) as Promise<Models.ConfigurationStoresListKeysNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.AppConfiguration/configurationStores",
urlParameters: [
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ConfigurationStoreListResult
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const listByResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ConfigurationStoreListResult
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.configStoreName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ConfigurationStore
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const listKeysOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}/ListKeys",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.configStoreName
],
queryParameters: [
Parameters.apiVersion,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ApiKeyListResult
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const regenerateKeyOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}/RegenerateKey",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.configStoreName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "regenerateKeyParameters",
mapper: {
...Mappers.RegenerateKeyParameters,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.ApiKey
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const listKeyValueOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}/listKeyValue",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.configStoreName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "listKeyValueParameters",
mapper: {
...Mappers.ListKeyValueParameters,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.KeyValue
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const beginCreateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.configStoreName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "configStoreCreationParameters",
mapper: {
...Mappers.ConfigurationStore,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.ConfigurationStore
},
201: {
bodyMapper: Mappers.ConfigurationStore
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const beginDeleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.configStoreName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
202: {},
204: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const beginUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppConfiguration/configurationStores/{configStoreName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.configStoreName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "configStoreUpdateParameters",
mapper: {
...Mappers.ConfigurationStoreUpdateParameters,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.ConfigurationStore
},
201: {
bodyMapper: Mappers.ConfigurationStore
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const listNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ConfigurationStoreListResult
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const listByResourceGroupNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ConfigurationStoreListResult
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const listKeysNextOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ApiKeyListResult
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
}; | the_stack |
import { assertEquals, assertThrows } from 'https://deno.land/std@0.102.0/testing/asserts.ts';
import { dirname, fromFileUrl } from 'https://deno.land/std@0.102.0/path/mod.ts';
import { copy, ensureDir, emptyDir } from 'https://deno.land/std@0.102.0/fs/mod.ts';
import { magenta } from 'https://deno.land/std@0.102.0/fmt/colors.ts';
import { delay } from 'https://deno.land/std@0.102.0/async/mod.ts';
import { Database } from '../lib/database.ts';
// Prepare enviroment
const DIRNAME = dirname(fromFileUrl(import.meta.url));
const TEMP_PATH = DIRNAME + '/temp_database_tests_enviroment';
const ENVIROMENT_PATH = DIRNAME + '/enviroment';
await ensureDir(TEMP_PATH);
await emptyDir(TEMP_PATH)
await copy(ENVIROMENT_PATH, TEMP_PATH, { overwrite: true });
Deno.test({
name: `${magenta('[database.ts]')} Initialization`,
sanitizeResources: false,
sanitizeOps: false,
async fn() {
new Database();
new Database({});
new Database({
path: undefined,
pretty: false,
autoload: true,
autosave: false,
immutable: false,
validator: () => { },
});
}
});
Deno.test({
name: `${magenta('[database.ts]')} Pretty`,
sanitizeResources: false,
sanitizeOps: false,
async fn() {
const pretty = new Database({ path: TEMP_PATH + '/pretty_test.json', pretty: true });
const notPretty = new Database({ path: TEMP_PATH + '/not_pretty_test.json', pretty: false });
pretty.documents = [{ field: 0 }];
notPretty.documents = [{ field: 0 }];
pretty.save();
notPretty.save();
await delay(100);
const prettyContent = await Deno.readTextFile(TEMP_PATH + '/pretty_test.json');
assertEquals(prettyContent.includes('\t'), true);
const notPrettyContent = await Deno.readTextFile(TEMP_PATH + '/not_pretty_test.json');
assertEquals(notPrettyContent.includes('\t'), false);
}
});
Deno.test({
name: `${magenta('[database.ts]')} Return immutability`,
sanitizeResources: false,
sanitizeOps: false,
async fn() {
const immutable = new Database({ immutable: true });
const immutable_insertOne = await immutable.insertOne({ field: 0 });
immutable_insertOne.field = 1;
const immutable_insertMany = await immutable.insertMany([{ field: 0 }]);
immutable_insertMany[0].field = 1;
const immutable_findOne = await immutable.findOne({ field: 0 }) as any;
immutable_findOne.field = 1;
const immutable_findMany = await immutable.findMany({ field: 0 });
immutable_findMany[0].field = 1;
immutable_findMany[1].field = 1;
const immutable_updateOne = await immutable.updateOne({ field: 0 }, { field: 0 }) as any;
immutable_updateOne.field = 1;
const immutable_updateMany = await immutable.updateMany({ field: () => true }, {});
immutable_updateMany[0].field = 1;
immutable_updateMany[1].field = 1;
immutable_updateMany.splice(0, 1);
// Check if something changed
assertEquals(immutable.documents[0].field, 0);
assertEquals(immutable.documents[1].field, 0);
/////////////////////////////////////////////////
const notImmutable = new Database({ immutable: false });
const notImmutable_insertOne = await notImmutable.insertOne({ field: 0 });
notImmutable_insertOne.field = 1;
assertEquals(notImmutable.documents[0].field, 1);
const notImmutable_insertMany = await notImmutable.insertMany([{ field: 0 }]);
notImmutable_insertMany[0].field = 1;
assertEquals(notImmutable.documents[1].field, 1);
const notImmutable_findOne = await notImmutable.findOne({ field: 1 }) as any;
notImmutable_findOne.field = 2;
assertEquals(notImmutable.documents[0].field, 2);
const notImmutable_findMany = await notImmutable.findMany({ field: 1 });
notImmutable_findMany[0].field = 2;
assertEquals(notImmutable.documents[0].field, 2);
assertEquals(notImmutable.documents[1].field, 2);
const notImmutable_updateOne = await notImmutable.updateOne({ field: 2 }, { field: 2 }) as any;
notImmutable_updateOne.field = 3;
assertEquals(notImmutable.documents[0].field, 3);
const notImmutable_updateMany = await notImmutable.updateMany({ field: () => true }, {});
notImmutable_updateMany[0].field = 4;
notImmutable_updateMany[1].field = 4;
assertEquals(notImmutable.documents[0].field, 4);
assertEquals(notImmutable.documents[1].field, 4);
}
});
Deno.test({
name: `${magenta('[database.ts]')} Storage Immutability`,
sanitizeResources: false,
sanitizeOps: false,
async fn() {
const db = new Database({ immutable: false }); // Insert should always be immutable, without any exceptions
const oneDocument: any = { field: [1, 2, { foo: ['bar'] }] };
await db.insertOne(oneDocument);
oneDocument.field[2].foo[0] = 'baz';
const multipleDocuments: any = [{ field: [0] }, { field: [1] }];
await db.insertMany(multipleDocuments);
multipleDocuments[0].field[0] = 999;
multipleDocuments[1].field[0] = 999;
multipleDocuments.push({ field: [999] });
const oneUpdate = [0];
await db.updateOne({ field: [0] }, { field: oneUpdate }) as any;
oneUpdate[0] = 999;
const multipleUpdate = [1];
await db.updateMany({ field: [1] }, { field: multipleUpdate }) as any;
multipleUpdate[0] = 999;
multipleUpdate.push(999);
assertEquals(db.documents, [
{ field: [1, 2, { foo: ['bar'] }] },
{ field: [0] },
{ field: [1] }
]);
}
});
Deno.test({
name: `${magenta('[database.ts]')} insertOne`,
sanitizeResources: false,
sanitizeOps: false,
async fn() {
const db = new Database({ path: TEMP_PATH + '/insertOne_test.json', pretty: false, batching: false });
const inserted = await db.insertOne({ foo: 'bar' });
assertEquals(db.documents, [{ foo: 'bar' }]);
assertEquals(inserted, { foo: 'bar' });
const content = await Deno.readTextFile(TEMP_PATH + '/insertOne_test.json');
assertEquals(content, '[{"foo":"bar"}]');
}
});
Deno.test({
name: `${magenta('[database.ts]')} insertOne (Empty)`,
sanitizeResources: false,
sanitizeOps: false,
async fn() {
const db = new Database({ path: TEMP_PATH + '/insertOne_empty_test.json', pretty: false, batching: false });
const inserted = await db.insertOne({});
assertEquals(db.documents, []);
assertEquals(inserted, {});
const content = await Deno.readTextFile(TEMP_PATH + '/insertOne_empty_test.json');
assertEquals(content, '[]');
}
});
Deno.test({
name: `${magenta('[database.ts]')} insertMany`,
sanitizeResources: false,
sanitizeOps: false,
async fn() {
const db = new Database({ path: TEMP_PATH + '/insertMany_test.json', pretty: false, batching: false });
const inserted = await db.insertMany([{ foo: 'bar' }, { bar: 'foo' }, {},]);
assertEquals(db.documents, [{ foo: 'bar' }, { bar: 'foo' }]);
assertEquals(inserted, [{ foo: 'bar' }, { bar: 'foo' }]);
const content = await Deno.readTextFile(TEMP_PATH + '/insertMany_test.json');
assertEquals(content, '[{"foo":"bar"},{"bar":"foo"}]');
}
});
Deno.test({
name: `${magenta('[database.ts]')} insertMany (Empty)`,
sanitizeResources: false,
sanitizeOps: false,
async fn() {
const db = new Database({ path: TEMP_PATH + '/insertMany_empty_test.json', pretty: false, batching: false });
const inserted = await db.insertMany([{}, {},]);
assertEquals(db.documents, []);
assertEquals(inserted, {});
const content = await Deno.readTextFile(TEMP_PATH + '/insertMany_empty_test.json');
assertEquals(content, '[]');
}
});
Deno.test({
name: `${magenta('[database.ts]')} findOne`,
sanitizeResources: false,
sanitizeOps: false,
async fn() {
const db = new Database({ path: TEMP_PATH + '/findOne_test.json', pretty: false, batching: false });
const initialData = [
{ id: 1, text: 'one', boolean: true, empty: null, array: [1], object: {} },
{ id: 2, text: 'two', boolean: true, empty: null, array: [2], object: {} },
{ id: 3, text: 'three', boolean: true, empty: null, array: [3], object: {} },
];
await db.insertMany(initialData);
const found1 = await db.findOne({ id: 1 });
const found2 = await db.findOne({ id: 2, notDefined: undefined, object: {} });
const found3 = await db.findOne({ id: 3, text: /three/, boolean: (value) => value === true, empty: null, array: [3], object: {} });
const found4 = await db.findOne((value) => value.id === 1);
const found5 = await db.findOne({});
const notFound1 = await db.findOne({ object: [] });
const notFound2 = await db.findOne((value) => value.id === 4);
assertEquals(found1, { id: 1, text: 'one', boolean: true, empty: null, array: [1], object: {} });
assertEquals(found2, { id: 2, text: 'two', boolean: true, empty: null, array: [2], object: {} });
assertEquals(found3, { id: 3, text: 'three', boolean: true, empty: null, array: [3], object: {} });
assertEquals(found4, { id: 1, text: 'one', boolean: true, empty: null, array: [1], object: {} });
assertEquals(found5, { id: 1, text: 'one', boolean: true, empty: null, array: [1], object: {} });
assertEquals(notFound1, null);
assertEquals(notFound2, null);
(found1 as any).id = 999;
(found2 as any).id = 999;
(found3 as any).id = 999;
(found4 as any).array.push(999);
(found5 as any).array.push(999);
assertEquals(db.documents, initialData);
}
});
Deno.test({
name: `${magenta('[database.ts]')} findMany`,
sanitizeResources: false,
sanitizeOps: false,
async fn() {
const db = new Database({ path: TEMP_PATH + '/findMany_test.json', pretty: false, batching: false });
const initialData = [
{ id: 1, text: 'one', boolean: true, empty: null, array: [1], object: {} },
{ id: 2, text: 'two', boolean: true, empty: null, array: [2], object: {} },
{ id: 3, text: 'three', boolean: true, empty: null, array: [3], object: {} },
];
await db.insertMany(initialData);
const found1 = await db.findMany({ id: 1 });
const found2 = await db.findMany({ id: 2, notDefined: undefined, object: {} });
const found3 = await db.findMany({ boolean: (value) => value === true, object: {} });
const found4 = await db.findMany((value) => value.id === 1);
const found5 = await db.findMany({});
const notFound1 = await db.findMany({ object: [] });
const notFound2 = await db.findMany((value) => value.id === 4);
assertEquals(found1, [{ id: 1, text: 'one', boolean: true, empty: null, array: [1], object: {} }]);
assertEquals(found2, [{ id: 2, text: 'two', boolean: true, empty: null, array: [2], object: {} }]);
assertEquals(found3, initialData);
assertEquals(found4, [{ id: 1, text: 'one', boolean: true, empty: null, array: [1], object: {} }]);
assertEquals(found5, initialData);
assertEquals(notFound1, []);
assertEquals(notFound2, []);
(found1[0] as any).id = 999;
(found2[0] as any).id = 999;
(found3[0] as any).id = 999;
(found4[0] as any).array.push(999);
(found5[0] as any).array.push(999);
assertEquals(db.documents, initialData);
}
});
Deno.test({
name: `${magenta('[database.ts]')} updateOne`,
sanitizeResources: false,
sanitizeOps: false,
async fn() {
const db = new Database({ path: TEMP_PATH + '/updateOne_test.json', pretty: false, batching: false });
const initialData = [
{ id: 1, text: 'one', boolean: true, empty: null, array: [1], object: {} },
{ id: 2, text: 'two', boolean: true, empty: null, array: [2], object: {} },
{ id: 3, text: 'three', boolean: true, empty: null, array: [3], object: {} },
];
await db.insertMany(initialData);
const updated1 = await db.updateOne({ id: 1 }, { boolean: false });
const updated2 = await db.updateOne({ id: 2, object: {}, notDefined: undefined }, { object: { foo: 'bar' }, boolean: false });
const updated3 = await db.updateOne({ text: (value) => value === 'three' }, (doc) => {
doc.id = 0;
doc.text = 'zero';
doc.boolean = false;
(doc.array as number[])[0] = 0;
return doc;
});
const updated4 = await db.updateOne((value) => value.id === 1, { array: [1, undefined as any], boolean: false });
const updated5 = await db.updateOne({ id: 0 }, { object: (value) => value, boolean: false });
const deleted1 = await db.updateOne({ id: 1 }, () => null);
const deleted2 = await db.updateOne({ id: 2 }, () => ({ id: undefined as any }));
assertEquals(updated1, { id: 1, text: 'one', boolean: false, empty: null, array: [1], object: {} });
assertEquals(updated2, { id: 2, text: 'two', boolean: false, empty: null, array: [2], object: { foo: 'bar' } });
assertEquals(updated3, { id: 0, text: 'zero', boolean: false, empty: null, array: [0], object: {} });
assertEquals(updated4, { id: 1, text: 'one', boolean: false, empty: null, array: [1, null], object: {} });
assertEquals(updated5, { id: 0, text: 'zero', boolean: false, empty: null, array: [0], object: { } });
assertEquals(deleted1, {});
assertEquals(deleted2, {});
(updated1 as any).id = 999;
(updated2 as any).id = 999;
(updated3 as any).id = 999;
(updated4 as any).array.push(999);
(updated5 as any).array.push(999);
assertEquals(db.documents, [{ id: 0, text: 'zero', boolean: false, empty: null, array: [0], object: {} }]);
}
});
Deno.test({
name: `${magenta('[database.ts]')} count`,
sanitizeResources: false,
sanitizeOps: false,
async fn() {
const db = new Database({ pretty: false, batching: false });
const amount1 = await db.count();
await db.insertOne({ foo: 'bar' });
const amount2 = await db.count({});
const amount3 = await db.count({ foo: 'bar' });
const amount4 = await db.count({ foo: 'baz' });
assertEquals(amount1, 0);
assertEquals(amount2, 1);
assertEquals(amount3, 1);
assertEquals(amount4, 0);
}
});
Deno.test({
name: `${magenta('[database.ts]')} drop`,
sanitizeResources: false,
sanitizeOps: false,
async fn() {
const db = new Database({ path: TEMP_PATH + '/drop_test.json', pretty: false, batching: false });
await db.insertMany([
{ id: 1 },
{ id: 2 },
{ id: undefined as any },
{}
]);
await db.drop();
assertEquals(db.documents, []);
const content = await Deno.readTextFile(TEMP_PATH + '/drop_test.json');
assertEquals(content, '[]');
}
});
// TODO: Finish testing
// Remove temp files
window.addEventListener('unload', () => {
Deno.removeSync(TEMP_PATH, { recursive: true });
}); | the_stack |
* @fileoverview In this file, we will test the functions exported by datastructres/collection.js
*/
import _ from "lodash";
import { expect } from "chai";
import { Collection } from "../../index";
describe("collection", function() {
const createObject = () => ({
item4: Number.NaN,
item5: undefined,
// eslint-disable-next-line no-null/no-null
item6: null,
item7: "",
item8: false,
item9: {},
item10: [],
item11: "test",
item12: 0,
item13: 1,
});
it("should add a value under a key", function(done) {
const collection = new Collection<string>();
expect(collection.add("item1", "test")).to.equal("test");
expect(collection.has("item1")).to.equal(true);
collection.add(0, "test2");
expect(collection.has(0)).to.equal(true);
done();
});
it("should bulk add a key-value object to the list of items", function(done) {
const collection = new Collection<any>();
const objectToAdd = createObject();
expect(collection.bulkAdd(objectToAdd)).to.equal(collection);
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
const itemExists = _.every(objectToAdd, (item, key) => collection.has(key));
expect(itemExists).to.equal(true);
done();
});
it("should remove a value associated with a key", function(done) {
const collection = new Collection<string>();
collection.add("item1", "test");
expect(collection.remove("item1")).to.equal(true);
expect(collection.has("item1")).to.equal(false);
expect(collection.remove("item1")).to.equal(false);
done();
});
it("should bulk remove a key-value object from the list of items", function(done) {
const collection = new Collection();
const objectToAdd = createObject();
collection.bulkAdd(objectToAdd);
collection.bulkRemove(objectToAdd);
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
const itemExists = _.every(objectToAdd, (item, key) => collection.has(key));
expect(itemExists).to.equal(false);
done();
});
it("should check for emptyness", function(done) {
const collection = new Collection<string>();
expect(collection.isEmpty()).to.equal(true);
collection.add("item1", "test");
expect(collection.isEmpty()).to.equal(false);
done();
});
it("should get the first value in the collection", function(done) {
const collection = new Collection<string>();
collection.add("item1", "test1");
collection.add("item2", "test2");
expect(collection.getFirstItem()).to.equal("test1");
done();
});
it("should get the last value in the collection", function(done) {
const collection = new Collection<string>();
collection.add("item1", "test1");
collection.add("item2", "test2");
expect(collection.getLastItem()).to.equal("test2");
done();
});
it("should get the type of the collection", function(done) {
const collection = new Collection("collection1", Array);
expect(collection.getType()).to.equal(Array);
done();
});
it("should filter out values based on a predicate function", function(done) {
const collection = new Collection<number>();
const objectToAdd = {
item1: 0,
item2: 2,
item3: 3,
};
collection.bulkAdd(objectToAdd);
const filteredCollection = collection.filter((key, item) => item > 0);
expect(filteredCollection.has("item1")).to.equal(false);
expect(filteredCollection.has("item2")).to.equal(true);
expect(filteredCollection.has("item3")).to.equal(true);
done();
});
it("should filter out values based on a key predicate", function(done) {
const collection = new Collection();
const objectToAdd = {
item1: 0,
item2: 2,
item3: 3,
};
collection.bulkAdd(objectToAdd);
const filteredCollection = collection.filterByKey(["item2", "item3"]);
expect(filteredCollection.has("item1")).to.equal(false);
expect(filteredCollection.has("item2")).to.equal(true);
expect(filteredCollection.has("item3")).to.equal(true);
const filteredCollection2 = collection.filterByKey("item2");
expect(filteredCollection2.has("item1")).to.equal(false);
expect(filteredCollection2.has("item2")).to.equal(true);
expect(filteredCollection2.has("item3")).to.equal(false);
done();
});
it("should filter out values based on a value predicate", function(done) {
const collection = new Collection();
const objectToAdd = {
item1: 0,
item2: 2,
item3: 3,
};
collection.bulkAdd(objectToAdd);
const filteredCollection = collection.filterByValue(objectToAdd.item1);
expect(filteredCollection.has("item1")).to.equal(true);
expect(filteredCollection.has("item2")).to.equal(false);
expect(filteredCollection.has("item3")).to.equal(false);
done();
});
it("should return the number of elements in the collection", function(done) {
const collection = new Collection();
const objectToAdd = {
item1: 0,
item2: 2,
item3: 3,
};
collection.bulkAdd(objectToAdd);
expect(collection.getCount()).to.equal(3);
done();
});
it("should return the list of items in an array", function(done) {
const collection = new Collection();
const objectToAdd = {
item1: 0,
item2: 2,
item3: 3,
};
collection.bulkAdd(objectToAdd);
const array = collection.getAsArray();
expect(array).to.be.an("array");
const exists = _.every(objectToAdd, (item) => _.includes(array, item));
expect(exists).to.equal(true);
done();
});
it("should check if an item exists", function(done) {
const collection = new Collection();
const objectToAdd = {
item1: 0,
item2: 2,
item3: 3,
};
collection.bulkAdd(objectToAdd);
expect(collection.has("item2")).to.equal(true);
expect(collection.has("foo")).to.equal(false);
done();
});
it("should get an item from the collection", function(done) {
const collection = new Collection();
const objectToAdd = {
item1: 0,
item2: 2,
item3: 3,
};
collection.bulkAdd(objectToAdd);
expect(collection.item("item2")).to.equal(objectToAdd.item2);
done();
});
it("should set the value of a key", function(done) {
const collection = new Collection();
const objectToAdd = {
item1: 0,
item2: 2,
item3: 3,
};
collection.bulkAdd(objectToAdd);
collection.set("item1", 5);
expect(collection.item("item1")).to.equal(5);
done();
});
it("should iterate over the set of items", function(done) {
const collection = new Collection();
const objectToAdd = {
item1: 0,
item2: 2,
item3: 3,
};
collection.bulkAdd(objectToAdd);
const result = {};
collection.iterate(function(key, item) {
result[key] = item;
});
expect(result).to.deep.equal(objectToAdd);
done();
});
it("should iterate over the set of items starting from the tail", function(done) {
const collection = new Collection();
const objectToAdd = {
item1: 0,
item2: 2,
item3: 3,
};
collection.bulkAdd(objectToAdd);
const result = {};
const keys = collection.getKeys();
let i = keys.length - 1;
collection.iterateFromTail(function(key, item) {
result[key] = item;
expect(key).to.equal(keys[i]);
i--;
});
expect(result).to.deep.equal(objectToAdd);
done();
});
it("should return all items in an JSON format", function(done) {
const collection = new Collection();
const objectToAdd = {
item1: 0,
item2: 2,
item3: 3,
};
collection.bulkAdd(objectToAdd);
expect(collection.getItems()).to.deep.equal(objectToAdd);
done();
});
it("should return all keys in an array", function(done) {
const collection = new Collection();
const objectToAdd = {
item1: 0,
item2: 2,
item3: 3,
};
collection.bulkAdd(objectToAdd);
expect(collection.getKeys()).to.deep.equal(_.keys(objectToAdd));
done();
});
it("should return the first item in the collection along with the key", function(done) {
const collection = new Collection();
collection.add("item1", "test1");
collection.add("item2", "test2");
expect(collection.peak()).to.deep.equal({ key: "item1", item: "test1" });
done();
});
describe("clear", function() {
it("should empty the collection", function(done) {
const collection = new Collection();
const objectToAdd = {
item1: 0,
item2: 2,
item3: 3,
};
collection.bulkAdd(objectToAdd);
const ret = collection.clear();
expect(collection.isEmpty()).to.equal(true);
expect(ret).to.equal(collection);
done();
});
it("should return the collection itself", function(done) {
const collection = new Collection();
const ret = collection.clear();
expect(ret).to.equal(collection);
done();
});
});
it("should clone the collection", function(done) {
const collection = new Collection();
const objectToAdd = {
item1: 0,
item2: 2,
item3: 3,
};
collection.bulkAdd(objectToAdd);
expect(collection.clone().items).to.deep.equal(collection.items);
done();
});
it("should copy the collection", function(done) {
const collection = new Collection();
const objectToAdd = {
item1: "test",
item2: true,
item3: 23,
};
collection.bulkAdd(objectToAdd);
const collection2 = new Collection();
collection2.copy(collection);
expect(collection2.items.item1).to.equal(objectToAdd.item1);
expect(collection2.items.item2).to.equal(objectToAdd.item2);
expect(collection2.items.item3).to.equal(objectToAdd.item3);
done();
});
it("should invoke the onAdd callback", function(done) {
const collection = new Collection();
let triggered = false;
collection.onAdd = function(key, item) {
triggered = true;
expect(key).to.equal("item");
expect(item).to.equal("value");
};
collection.add("item", "value");
expect(triggered).to.equal(true);
let callbackCounter = 0;
const objectToAdd = createObject();
// now override the onAdd function and check wiether we call it
// when we bulkAdd
collection.onAdd = function(key, item) {
callbackCounter++;
expect(Object.prototype.hasOwnProperty.call(objectToAdd, key)).to.equal(true);
};
collection.bulkAdd(objectToAdd);
expect(callbackCounter).to.equal(_.keys(objectToAdd).length);
done();
});
it("should invoke the onRemove callback", function(done) {
const collection = new Collection();
let triggered = false;
collection.onRemove = function(key, item) {
triggered = true;
expect(key).to.equal("item");
expect(item).to.equal("value");
};
collection.add("item", "value");
collection.remove("item");
expect(triggered).to.equal(true);
// Should not invoke the onRemove here
triggered = false;
collection.remove("item");
expect(triggered).to.equal(false);
let callbackCounter = 0;
const objectToAdd = createObject();
// now override the onRemove function and check wiether we call it
// when we bulkRemove
collection.onRemove = function(key, item) {
callbackCounter++;
expect(Object.prototype.hasOwnProperty.call(objectToAdd, key)).to.equal(true);
};
collection.bulkAdd(objectToAdd);
collection.bulkRemove(objectToAdd);
expect(callbackCounter).to.equal(_.keys(objectToAdd).length);
done();
});
it("should stop early when iterating", function() {
const collection = new Collection();
const objectToAdd = {
item1: "test",
item2: true,
item3: 23,
};
collection.bulkAdd(objectToAdd);
let iterator = 1;
collection.iterate(function() {
if (iterator === 2) {
return false;
}
iterator++;
return true;
});
expect(iterator).to.equal(2);
iterator = 1;
collection.iterateFromTail(function() {
if (iterator === 2) {
return false;
}
iterator++;
return true;
});
expect(iterator).to.equal(2);
});
it("should invoke the onClear callback", function(done) {
const collection = new Collection();
const objectToAdd = createObject();
let triggered = false;
collection.onClear = function(items) {
triggered = true;
expect(items).to.deep.equal(objectToAdd);
};
// this shouldn't invoke the callback
collection.clear();
expect(triggered).to.equal(false);
collection.bulkAdd(objectToAdd);
collection.clear();
expect(triggered).to.equal(true);
done();
});
}); | the_stack |
import { t } from '@deepkit/type';
import { expect, test } from '@jest/globals';
import 'reflect-metadata';
import { Progress, RpcMessageWriter, RpcMessageWriterOptions } from '../src/writer';
import { DirectClient } from '../src/client/client-direct';
import { rpc } from '../src/decorators';
import {
createRpcCompositeMessage,
createRpcCompositeMessageSourceDest,
createRpcMessage,
createRpcMessagePeer,
createRpcMessageSourceDest,
readRpcMessage,
readUint32LE,
RpcBufferReader,
RpcMessage,
RpcMessageReader,
RpcMessageRouteType
} from '../src/protocol';
import { RpcKernel } from '../src/server/kernel';
import { RpcTypes } from '../src/model';
import { createBuffer, Writer } from '@deepkit/bson';
test('readUint32LE', () => {
{
const writer = new Writer(createBuffer(8));
writer.writeUint32(545);
const view = new DataView(writer.buffer.buffer, writer.buffer.byteOffset);
expect(view.getUint32(0, true)).toBe(545);
expect(readUint32LE(writer.buffer)).toBe(545);
}
{
const writer = new Writer(createBuffer(8));
writer.writeUint32(94388585);
expect(readUint32LE(writer.buffer)).toBe(94388585);
}
});
test('protocol basics', () => {
const schema = t.schema({
name: t.string
});
{
const message = createRpcMessage(1024, 123);
const parsed = readRpcMessage(message);
expect(parsed.id).toBe(1024);
expect(parsed.type).toBe(123);
expect(parsed.composite).toBe(false);
expect(parsed.routeType).toBe(RpcMessageRouteType.client);
expect(parsed.bodySize).toBe(0);
expect(() => parsed.parseBody(schema)).toThrowError('no body');
}
{
const message = createRpcMessage(1024, 130, schema, { name: 'foo' });
const parsed = readRpcMessage(message);
expect(parsed.id).toBe(1024);
expect(parsed.type).toBe(130);
expect(parsed.composite).toBe(false);
expect(parsed.routeType).toBe(RpcMessageRouteType.client);
const body = parsed.parseBody(schema);
expect(body.name).toBe('foo');
}
{
const message = createRpcMessage(1024, 130, schema, { name: 'foo' }, RpcMessageRouteType.server);
const parsed = readRpcMessage(message);
expect(parsed.id).toBe(1024);
expect(parsed.type).toBe(130);
expect(parsed.composite).toBe(false);
expect(parsed.routeType).toBe(RpcMessageRouteType.server);
}
{
const peerSource = Buffer.alloc(16);
peerSource[0] = 22;
const message = createRpcMessagePeer(1024, 130, peerSource, 'myPeer', schema, { name: 'foo' });
const parsed = readRpcMessage(message);
expect(parsed.id).toBe(1024);
expect(parsed.type).toBe(130);
expect(parsed.composite).toBe(false);
expect(parsed.getPeerId()).toBe('myPeer');
const body = parsed.parseBody(schema);
expect(body.name).toBe('foo');
}
{
const source = Buffer.alloc(16);
source[0] = 16;
const destination = Buffer.alloc(16);
destination[0] = 20;
const message = createRpcMessageSourceDest(1024, 130, source, destination, schema, { name: 'foo' });
const parsed = readRpcMessage(message);
expect(parsed.id).toBe(1024);
expect(parsed.type).toBe(130);
expect(parsed.composite).toBe(false);
expect(parsed.getSource()[0]).toBe(16);
expect(parsed.getDestination()[0]).toBe(20);
const body = parsed.parseBody(schema);
expect(body.name).toBe('foo');
}
});
test('protocol composite', () => {
const schema = t.schema({
name: t.string
});
{
const message = createRpcCompositeMessage(1024, 33, [{ type: 4, schema, body: { name: 'foo' } }]);
const parsed = readRpcMessage(message);
expect(parsed.id).toBe(1024);
expect(parsed.type).toBe(33);
expect(parsed.composite).toBe(true);
expect(parsed.routeType).toBe(RpcMessageRouteType.client);
expect(() => parsed.parseBody(schema)).toThrow('Composite message can not be read directly');
const messages = parsed.getBodies();
expect(messages.length).toBe(1);
expect(messages[0].type).toBe(4);
expect(messages[0].bodySize).toBeGreaterThan(10);
expect(messages[0].parseBody(schema).name).toBe('foo');
}
{
const message = createRpcCompositeMessage(1024, 5, [{ type: 4 }, { type: 5, schema, body: { name: 'foo' } }]);
const parsed = readRpcMessage(message);
expect(parsed.id).toBe(1024);
expect(parsed.type).toBe(5);
expect(parsed.composite).toBe(true);
expect(parsed.routeType).toBe(RpcMessageRouteType.client);
expect(() => parsed.parseBody(schema)).toThrow('Composite message can not be read directly');
const messages = parsed.getBodies();
expect(messages.length).toBe(2);
expect(messages[0].type).toBe(4);
expect(messages[0].bodySize).toBe(0);
expect(() => messages[0].parseBody(schema)).toThrow('no body');
expect(messages[1].type).toBe(5);
expect(messages[1].bodySize).toBeGreaterThan(10);
expect(messages[1].parseBody(schema).name).toBe('foo');
}
{
const message = createRpcCompositeMessage(1024, 6, [{ type: 4, schema, body: { name: 'foo' } }, {
type: 12,
schema,
body: { name: 'bar' }
}]);
const parsed = readRpcMessage(message);
expect(parsed.id).toBe(1024);
expect(parsed.type).toBe(6);
expect(parsed.composite).toBe(true);
expect(parsed.routeType).toBe(RpcMessageRouteType.client);
expect(() => parsed.parseBody(schema)).toThrow('Composite message can not be read directly');
const messages = parsed.getBodies();
expect(messages.length).toBe(2);
expect(messages[0].type).toBe(4);
expect(messages[0].parseBody(schema).name).toBe('foo');
expect(messages[1].type).toBe(12);
expect(messages[1].parseBody(schema).name).toBe('bar');
}
{
const source = Buffer.alloc(16);
source[0] = 16;
const destination = Buffer.alloc(16);
destination[0] = 20;
const message = createRpcCompositeMessageSourceDest(1024, source, destination, 55, [{
type: 4,
schema,
body: { name: 'foo' }
}, { type: 12, schema, body: { name: 'bar' } }]);
const parsed = readRpcMessage(message);
expect(parsed.id).toBe(1024);
expect(parsed.type).toBe(55);
expect(parsed.composite).toBe(true);
expect(parsed.routeType).toBe(RpcMessageRouteType.sourceDest);
expect(parsed.getSource()[0]).toBe(16);
expect(parsed.getDestination()[0]).toBe(20);
expect(() => parsed.parseBody(schema)).toThrow('Composite message can not be read directly');
const messages = parsed.getBodies();
expect(messages.length).toBe(2);
expect(messages[0].type).toBe(4);
expect(messages[0].parseBody(schema).name).toBe('foo');
expect(messages[1].type).toBe(12);
expect(messages[1].parseBody(schema).name).toBe('bar');
}
});
test('rpc kernel handshake', async () => {
const kernel = new RpcKernel();
const client = new DirectClient(kernel);
await client.connect();
expect(client.getId()).toBeInstanceOf(Uint8Array);
expect(client.getId().byteLength).toBe(16);
});
test('rpc kernel', async () => {
class Controller {
@rpc.action()
action(value: string): string {
return value;
}
@rpc.action()
sum(a: number, b: number): number {
return a + b;
}
}
const kernel = new RpcKernel();
kernel.registerController('myController', Controller);
const client = new DirectClient(kernel);
const controller = client.controller<Controller>('myController');
expect(await controller.action('foo')).toBe('foo');
expect(await controller.action('foo2')).toBe('foo2');
expect(await controller.action('foo3')).toBe('foo3');
expect(await controller.sum(2, 5)).toBe(7);
expect(await controller.sum(5, 5)).toBe(10);
expect(await controller.sum(10_000_000, 10_000_000)).toBe(20_000_000);
});
test('rpc peer', async () => {
const kernel = new RpcKernel();
const client1 = new DirectClient(kernel);
class Controller {
@rpc.action()
action(value: string): string {
return value;
}
}
await client1.registerAsPeer('peer1');
client1.registerPeerController('foo', Controller);
const client2 = new DirectClient(kernel);
const controller = client2.peer('peer1').controller<Controller>('foo');
const res = await controller.action('bar');
expect(res).toBe('bar');
});
test('message reader', async () => {
const messages: Buffer[] = [];
const reader = new RpcBufferReader(Array.prototype.push.bind(messages));
let buffer: any;
{
messages.length = 0;
buffer = Buffer.alloc(8);
buffer.writeUInt32LE(8);
reader.feed(buffer);
expect(reader.emptyBuffer()).toBe(true);
expect(messages.length).toBe(1);
expect(messages[0].readUInt32LE()).toBe(8);
}
{
messages.length = 0;
buffer = Buffer.alloc(500_000);
buffer.writeUInt32LE(1_000_000);
reader.feed(buffer);
buffer = Buffer.alloc(500_000);
reader.feed(buffer);
expect(reader.emptyBuffer()).toBe(true);
expect(messages.length).toBe(1);
expect(messages[0].readUInt32LE()).toBe(1_000_000);
}
{
messages.length = 0;
buffer = Buffer.alloc(0);
reader.feed(buffer);
buffer = Buffer.alloc(8);
buffer.writeUInt32LE(8);
reader.feed(buffer);
expect(reader.emptyBuffer()).toBe(true);
expect(messages.length).toBe(1);
expect(messages[0].readUInt32LE()).toBe(8);
}
{
messages.length = 0;
buffer = Buffer.alloc(18);
buffer.writeUInt32LE(8);
buffer.writeUInt32LE(10, 8);
reader.feed(buffer);
expect(reader.emptyBuffer()).toBe(true);
expect(messages.length).toBe(2);
expect(messages[0].readUInt32LE()).toBe(8);
expect(messages[1].readUInt32LE()).toBe(10);
}
{
messages.length = 0;
buffer = Buffer.alloc(22);
buffer.writeUInt32LE(8);
buffer.writeUInt32LE(10, 8);
buffer.writeUInt32LE(20, 18);
reader.feed(buffer);
buffer = Buffer.alloc(16);
reader.feed(buffer);
expect(reader.emptyBuffer()).toBe(true);
expect(messages.length).toBe(3);
expect(messages[0].readUInt32LE()).toBe(8);
expect(messages[1].readUInt32LE()).toBe(10);
expect(messages[2].readUInt32LE()).toBe(20);
}
{
messages.length = 0;
buffer = Buffer.alloc(8);
buffer.writeUInt32LE(8);
reader.feed(buffer);
reader.feed(buffer);
expect(reader.emptyBuffer()).toBe(true);
expect(messages.length).toBe(2);
expect(messages[0].readUInt32LE()).toBe(8);
expect(messages[1].readUInt32LE()).toBe(8);
}
{
messages.length = 0;
buffer = Buffer.alloc(4);
buffer.writeUInt32LE(8);
reader.feed(buffer);
buffer = Buffer.alloc(4);
reader.feed(buffer);
expect(reader.emptyBuffer()).toBe(true);
expect(messages.length).toBe(1);
expect(messages[0].readUInt32LE()).toBe(8);
}
{
messages.length = 0;
let buffer = Buffer.alloc(4);
buffer.writeUInt32LE(30);
reader.feed(buffer);
buffer = Buffer.alloc(26);
reader.feed(buffer);
buffer = Buffer.alloc(8);
buffer.writeUInt32LE(8);
reader.feed(buffer);
expect(reader.emptyBuffer()).toBe(true);
expect(messages.length).toBe(2);
expect(messages[0].readUInt32LE()).toBe(30);
expect(messages[1].readUInt32LE()).toBe(8);
}
});
test('message chunks', async () => {
const messages: RpcMessage[] = [];
const reader = new RpcMessageReader(v => messages.push(v));
const schema = t.schema({
v: t.string,
});
const bigString = 'x'.repeat(1_000_000); //1mb
const buffers: Uint8Array[] = [];
const writer = new RpcMessageWriter({
write(b) {
buffers.push(b);
reader.feed(createRpcMessage(2, RpcTypes.ChunkAck)); //confirm chunk, this is done automatically in the kernel
reader.feed(b); //echo back
},
close() {}
}, reader, new RpcMessageWriterOptions);
const message = createRpcMessage(2, RpcTypes.ResponseActionSimple, schema, { v: bigString });
await writer.writeFull(message);
expect(buffers.length).toBe(11); //total size is 1_000_025, chunk is 100k, so we have 11 packages
expect(readRpcMessage(buffers[0]).id).toBe(2);
expect(readRpcMessage(buffers[0]).type).toBe(RpcTypes.Chunk);
expect(readRpcMessage(buffers[10]).id).toBe(2);
expect(readRpcMessage(buffers[10]).type).toBe(RpcTypes.Chunk);
expect(messages.length).toBe(1);
const lastReceivedMessage = messages[0];
expect(lastReceivedMessage.id).toBe(2);
expect(lastReceivedMessage.type).toBe(RpcTypes.ResponseActionSimple);
const body = lastReceivedMessage.parseBody(schema);
expect(body.v).toBe(bigString);
});
test('message progress', async () => {
const messages: RpcMessage[] = [];
const reader = new RpcMessageReader(v => messages.push(v));
const schema = t.schema({
v: t.string,
});
const bigString = 'x'.repeat(1_000_000); //1mb
const writer = new RpcMessageWriter({
write(b) {
reader.feed(createRpcMessage(2, RpcTypes.ChunkAck)); //confirm chunk, this is done automatically in the kernel
reader.feed(b); //echo
},
close() {
}
}, reader, new RpcMessageWriterOptions);
const message = createRpcMessage(2, RpcTypes.ResponseActionSimple, schema, { v: bigString });
const progress = new Progress();
reader.registerProgress(2, progress.download);
await writer.writeFull(message, progress.upload);
await progress.upload.finished;
expect(progress.upload.done).toBe(true);
expect(progress.upload.isStopped).toBe(true);
expect(progress.upload.current).toBe(1_000_025);
expect(progress.upload.total).toBe(1_000_025);
expect(progress.upload.stats).toBe(11); //since 11 packages
await progress.download.finished;
expect(progress.download.done).toBe(true);
expect(progress.download.isStopped).toBe(true);
expect(progress.download.current).toBe(1_000_025);
expect(progress.download.total).toBe(1_000_025);
expect(progress.download.stats).toBe(11); //since 11 packages
const lastReceivedMessage = messages[0];
const body = lastReceivedMessage.parseBody(schema);
expect(body.v).toBe(bigString);
}); | the_stack |
import { GPU } from 'gpu.js';
import * as mathjs from 'mathjs';
const gpu = new GPU();
export class Mat {
// the raw data, the 2D array of matrix elements
val: number[][];
// number of rows and columns of matrix
rows: number;
cols: number;
// mode: the mode of matrix computation. It could only be 'gpu', 'wasm' or ''
mode: string;
// number of digits to show at toString() member function
// -1 (default value) means keeping all digits
// 0 means keeping integer part only
// N means keeping the first N digits
digits: number;
clear() {
this.val = [];
this.rows = 0;
this.cols = 0;
this.digits = -1;
this.mode = '';
return this;
}
constructor(input?: number[][] | number[] | number) {
this.mode = '';
this.digits = -1;
this.val = [];
this.rows = 0;
this.cols = 0;
if (typeof input === 'number') {
this.val = [[input]];
this.rows = 1;
this.cols = 1;
return this;
}
if (Array.isArray(input)) {
//if input is an 2D array
if (Array.isArray(input[0])) {
this.init(input);
}
//else it is a 1D vector
else {
this.initVec(input);
}
}
}
dimensions(): number[] {
return Array.from([this.rows, this.cols]);
}
isVector(): boolean {
return this.rows <= 1;
}
//initialize with a 2D array
init(input2DArray: any): Mat {
this.clear();
this.rows = input2DArray.length;
if (this.rows > 0) {
//find max column
let max_col = 0;
for (let j = 0; j < this.rows; j++) {
if (input2DArray[j].length > max_col) {
max_col = input2DArray[j].length;
}
}
this.cols = max_col;
} else {
this.cols = 0;
}
for (let i = 0; i < input2DArray.length; i++) {
//copy current row of column and fill the remaining space with 0
const current_row = [...input2DArray[i]];
if (this.cols > input2DArray[i].length) {
current_row.push(...Array(this.cols - input2DArray[i].length).fill(0));
}
this.val.push(current_row);
}
return this;
}
dimCheck(row: number, col: number) {
if (
row >= this.rows ||
row < 0 ||
col > this.cols ||
col < 0 ||
Number.isInteger(row) === false ||
Number.isInteger(col) === false
) {
throw new Error('Invalid row or column');
}
}
min(): number {
return Math.min(...this.toArray());
}
max(): number {
return Math.max(...this.toArray());
}
//initialize with 1D array (vector) into an N-by-1 matrix
initVec(input1DArray: any): Mat {
this.clear();
this.rows = 1;
this.cols = input1DArray.length;
this.val.push([...input1DArray]);
return this;
}
//generate a N-by-1 matrix by initializing a range vector [start:end:step].
range(arg1: number, arg2: number | null = null, step = 1): Mat {
const rangeVector = [];
let start = 0,
end = 0;
if (arg2 === null) {
start = 0;
end = arg1;
} // range from 0 to arg1
else {
start = arg1;
end = arg2;
} //range from arg1 to arg2
if (start < end) {
for (let iterator = start; iterator < end; iterator += step) {
rangeVector.push(iterator);
}
return this.initVec(rangeVector);
}
for (let iterator = start; iterator > end; iterator += step) {
//else
rangeVector.push(iterator);
}
return this.initVec(rangeVector);
}
// return a clone of this matrix
clone(): Mat {
const returnMat = new Mat();
returnMat.rows = this.rows;
returnMat.cols = this.cols;
returnMat.digits = this.digits;
returnMat.mode = this.mode;
for (let i = 0; i < this.val.length; i++) {
returnMat.val.push([...this.val[i]]);
}
return returnMat;
}
// initialize a matrix by copying from another matrix
copy(inputMat: Mat): Mat {
this.init(inputMat.val);
this.cols = inputMat.cols;
this.rows = inputMat.rows;
this.digits = inputMat.digits;
this.mode = inputMat.mode;
return this;
}
equals(inMat: Mat, EPSILON = 0.0001): boolean {
if (this.cols !== inMat.cols || this.rows !== inMat.rows) return false;
const sumOfDiff = this.minus(inMat).squareSum();
return sumOfDiff <= EPSILON;
}
//initialze an row-by-col matrix with all elements are N
Ns(row: number, col: number, N: number): Mat {
this.clear();
this.rows = row;
this.cols = col;
for (let i = 0; i < row; i++) {
this.val.push(Array(col).fill(N));
}
return this;
}
//initialze a zero matrix
zeros(row: number, col?: number): Mat {
if (col) {
return this.Ns(row, col, 0);
}
return this.Ns(row, row, 0);
}
//initialize a matrix with all elements === 1
ones(row: number, col?: number): Mat {
if (col) {
return this.Ns(row, col, 1);
}
return this.Ns(row, row, 1);
}
// initiaze an N*N matrix with diag values
diag(input1DArray: number[]): Mat {
this.clear();
this.zeros(input1DArray.length, input1DArray.length);
for (let i = 0; i < input1DArray.length; i++) this.val[i][i] = input1DArray[i];
return this;
}
// initialize eye matrix with diag elements === 1
eye(row: number, col?: number): Mat {
if (col) {
this.clear();
this.zeros(row, col);
for (let i = 0; i < Math.min(row, col); i++) this.val[i][i] = 1;
return this;
}
//else
const diag_ones = Array(row).fill(1);
return this.diag(diag_ones);
}
// initialize a random matrix
random(row: number, col?: number): Mat {
if (!col) {
col = row;
}
this.clear();
this.zeros(row, col);
for (let row = 0; row < this.rows; row++) {
for (let col = 0; col < this.cols; col++) this.val[row][col] = Math.random();
}
return this;
}
T(): Mat {
// transpose
const returnMatrix = new Mat().zeros(this.cols, this.rows);
for (let row = 0; row < this.rows; row++) {
for (let col = 0; col < this.cols; col++) returnMatrix.val[col][row] = this.val[row][col];
}
return returnMatrix;
}
transpose(): Mat {
return this.T();
}
each(func: (element: number) => number): Mat {
for (let row = 0; row < this.rows; row++) {
for (let col = 0; col < this.cols; col++) this.val[row][col] = func(this.val[row][col]);
}
return this;
}
//add, multiply, minus, divide with one scalar value
addScalar(val: number): Mat {
const returnMatrix = this.clone();
returnMatrix.each(function (eachMatrixValue: number): number {
return eachMatrixValue + val;
});
return returnMatrix;
}
multiplyScalar(val: number): Mat {
const returnMatrix = this.clone();
returnMatrix.each(function (eachMatrixValue: number): number {
return eachMatrixValue * val;
});
return returnMatrix.clone();
}
minusScalar(val: number): Mat {
return this.addScalar(val * -1);
}
divideScalar(val: number): Mat {
return this.multiplyScalar(1.0 / val);
}
//matrix operations. All matrix operation member functions are NOT In Place
add(rightMat: Mat): Mat {
return add(this, rightMat);
}
minus(rightMat: Mat): Mat {
return minus(this, rightMat);
}
multiply(rightMat: Mat): Mat {
return multiply(this, rightMat);
}
dotMultiply(rightMat: Mat): Mat {
return dotMultiply(this, rightMat);
}
divide(rightMat: Mat): Mat {
return divide(this, rightMat);
}
// matrix plus operator overload
// mat1 + A
// the right operand A could be a matrix, a 2D array, a 1D array or a scalar number
[Symbol.for('+')](rightOperand: Mat | number | number[] | number[][]): Mat {
//if right operand is a raw array of number or 2D array, initialize the matrix first
if (Array.isArray(rightOperand)) {
return add(this, new Mat(rightOperand));
}
//if right operand is a number, add the number as a scalar
if (typeof rightOperand === 'number') {
return this.addScalar(rightOperand);
}
//otherwise, add the right operand as a matrix
return add(this, rightOperand);
}
// matrix minus operator overload
// mat1 - A
// the right operand A could be a matrix, a 2D array, a 1D array or a scalar number
[Symbol.for('-')](rightOperand: Mat | number | number[] | number[][]): Mat {
//if right operand is a raw array of number or 2D array, initialize the matrix first
if (Array.isArray(rightOperand)) {
return minus(this, new Mat(rightOperand));
}
//if right operand is a number, minus the number as a scalar
if (typeof rightOperand === 'number') {
return this.minusScalar(rightOperand);
}
//otherwise, minus the right operand as a matrix
return minus(this, rightOperand);
}
// matrix multiplication operator overload
// (in Matlab: mat1 * A)
// the right operand A could be a matrix, a 2D array, a 1D array or a scalar number
[Symbol.for('*')](rightOperand: Mat | number | number[] | number[][]): Mat {
//if right operand is a raw array of number or 2D array, initialize the matrix first
if (Array.isArray(rightOperand)) {
const rightOperandMatrix = new Mat(rightOperand);
return multiply(this, rightOperandMatrix);
}
//if right operand is a number, mul the number as a scalar
if (typeof rightOperand === 'number') {
return this.multiplyScalar(rightOperand);
}
//otherwise, multiply the right operand as a matrix
return multiply(this, rightOperand);
}
// matrix element-wise multiply operator overload when right operand is matrix/2D Array/1D Array
// ( in Matlab: matA .* matB)
// or matrix element-wise power of N when right operand is number N
// ( in Matlab: matA.^ N)
[Symbol.for('**')](rightOperand: Mat | number | number[] | number[][]): Mat {
//if right operand is a raw array of number or 2D array, initialize the matrix first
if (Array.isArray(rightOperand)) {
const rightOperandMatrix = new Mat(rightOperand);
//( in Matlab: matA .* matB)
return dotMultiply(this, rightOperandMatrix);
}
// if right operand is a number, matrix element-wise power of N when right operand is number N
// ( in Matlab: matA.^ N)
if (typeof rightOperand === 'number') {
const returnMatrix = this.clone();
for (let i = 1; i < rightOperand; i++) {
dotMultiplyInPlace(returnMatrix, this);
}
return returnMatrix;
}
//otherwise, dot multiply the right operand as a matrix
return dotMultiply(this, rightOperand);
}
//matrix right division A/B = A * inv(B)
[Symbol.for('/')](rightOperand: Mat | number | number[] | number[][]): Mat {
//if right operand is a number/scalar
if (typeof rightOperand === 'number') {
return this.divideScalar(rightOperand);
}
//if right operand is a 1D or 2D array
if (Array.isArray(rightOperand)) {
const rightMatrix = new Mat(rightOperand);
return divide(this, rightMatrix);
}
return divide(this, rightOperand);
}
// Mat ^ N, the power of a matrix
// if N === -1, return the inverse matrix
// otherwise return the result of matrix multiplying itself
[Symbol.for('^')](rightOperand: number): Mat {
if (this.rows !== this.cols) throw new Error('This matrix does not support ^ operator');
//if right operand is -1, return the inverse matrix
if (rightOperand === -1) {
// matrix inverse with mathjs
return new Mat(mathjs.inv(this.val));
}
if (!Number.isInteger(rightOperand) || rightOperand < 1)
throw new Error('This right operand does not support ^ operator');
const returnMatrix = this.clone();
for (let i = 2; i <= rightOperand; i++) {
multiplyInPlace(returnMatrix, this);
}
return returnMatrix;
}
// compare mat1 === mat2, which right operand mat2 could be a matrix object, 2D array, 1D array or a scalar number
[Symbol.for('==')](
rightOperand: Mat | number | number[] | number[][],
EPSILON = 0.0001
): boolean {
//if right operand is a raw array of number or 2D array, initialize the matrix first
if (Array.isArray(rightOperand)) {
const rightOperandMatrix = new Mat(rightOperand);
return this.equals(rightOperandMatrix);
}
//if right operand is a number, mul the number as a scalar
else if (typeof rightOperand === 'number') {
if (this.rows !== 1 || this.cols !== 1) {
throw new Error('This matrix cannot be compared with a scalar');
}
return (this.val[0][0] - rightOperand) * (this.val[0][0] - rightOperand) < EPSILON;
}
//otherwise, minus the right operand as a matrix
return this.equals(rightOperand);
}
//// compare mat1 === mat2, which right operand mat2 could be a matrix object, 2D array, 1D array or a scalar number
[Symbol.for('===')](
rightOperand: Mat | number | number[] | number[][],
EPSILON = 0.0001
): boolean {
//if right operand is a raw array of number or 2D array, initialize the matrix first
if (Array.isArray(rightOperand)) {
const rightOperandMatrix = new Mat(rightOperand);
return this.equals(rightOperandMatrix);
}
//if right operand is a number, mul the number as a scalar
else if (typeof rightOperand === 'number') {
if (this.rows !== 1 || this.cols !== 1) {
throw new Error('This matrix cannot be compared with a scalar');
}
return (this.val[0][0] - rightOperand) * (this.val[0][0] - rightOperand) < EPSILON;
}
//otherwise, minus the right operand as a matrix
return this.equals(rightOperand);
}
//setter and getter
set(row: number, col: number, val: number): Mat {
this.dimCheck(row, col);
this.val[row][col] = val;
return this;
}
get(row: number, col: number): number {
this.dimCheck(row, col);
return this.val[row][col];
}
at(row: number, col: number): number {
this.dimCheck(row, col);
return this.val[row][col];
}
//get a row vector (as an N-by-1 matrix) by index
row(rowIndex: number): Mat {
this.dimCheck(rowIndex, 0);
return new Mat().initVec(this.val[rowIndex]);
}
//get a column vector (as an N-by-1 matrix) by index
col(colIndex: number): Mat {
this.dimCheck(0, colIndex);
const columnVector = Array(this.rows).fill(0);
for (let rowPt = 0; rowPt < this.rows; rowPt++) columnVector[rowPt] = this.val[rowPt][colIndex];
return new Mat().initVec(columnVector);
}
//return a 2D array
to2DArray(): number[][] {
return this.clone().val;
}
//return a 1D array
toArray(): number[] {
return new Array<number>().concat(...this.val);
}
//reshape matrix
reshape(row: number, col: number): Mat {
const returnMatrix = new Mat().zeros(row, col);
const thisArray = this.toArray();
let arrayPt = 0;
for (let i = 0; i < row; i++) {
for (let j = 0; j < col; j++) {
if (arrayPt < thisArray.length) {
returnMatrix.val[i][j] = thisArray[arrayPt];
arrayPt++;
} else {
break;
}
}
if (arrayPt >= thisArray.length) break;
}
return returnMatrix;
}
//resize matrix to a smaller matrix [rowStart , rowEnd), [colStart , colEnd)
//All extra spaces will be filled with zero
subMatrix(rowStart: number, rowEnd: number, colStart: number, colEnd: number): Mat {
if (
rowStart < 0 ||
rowEnd > this.rows ||
colStart < 0 ||
colEnd > this.cols ||
rowStart > rowEnd ||
colStart > colEnd
) {
throw new Error('Please check the dimensions of subMatrix');
}
const returnMatrix = new Mat().zeros(rowEnd - rowStart, colEnd - colStart);
for (let i = rowStart; i < rowEnd; i++) {
const row_index_of_return_matrix = i - rowStart;
for (let j = colStart; j < colEnd; j++) {
const col_index_of_return_matrix = j - colStart;
returnMatrix.val[row_index_of_return_matrix][col_index_of_return_matrix] = this.val[i][j];
}
}
return returnMatrix;
}
//resize the matrix to a larger or smaller matrix
//and fill the extra spaces with defaultValue
resize(row: number, col: number, defaultValue = 0): Mat {
const returnMatrix = new Mat().Ns(row, col, defaultValue);
const min_row = Math.min(row, this.rows);
const min_col = Math.min(col, this.cols);
for (let i = 0; i < min_row; i++) {
for (let j = 0; j < min_col; j++) {
returnMatrix.val[i][j] = this.val[i][j];
}
}
return returnMatrix;
}
//get a few rows of matrix
Rows(rowStart: number, rowEnd: number): Mat {
return this.subMatrix(rowStart, rowEnd, 0, this.cols);
}
//get a few columns of matrix
Cols(colStart: number, colEnd: number): Mat {
return this.subMatrix(0, this.rows, colStart, colEnd);
}
//get a row of matrix in array format
RowVector(row: number): number[] {
return [...this.val[row]];
}
//get a column of matrix in array format
ColVector(col: number): number[] {
const ret = [];
for (let i = 0; i < this.rows; i++) ret.push(this.val[i][col]);
return ret;
}
//get a row of matrix in M-by-1 matrix format
Row(row: number): Mat {
return new Mat(this.RowVector(row));
}
//get a column of matrix in N-by-1 matrix format
Col(col: number): Mat {
return new Mat(this.ColVector(col));
}
squareSum(): number {
let ret = 0;
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++) {
const val = this.val[i][j];
ret += val * val;
}
}
return ret;
}
//set how many digits kept while display the matirx
setDigits(x: number) {
this.digits = x;
return this;
}
/*serialize matrix to JavaScript 2D Array string, for example:
[[1,2],
[3,4]]
(Users should directly copy the string as a JS 2D Array into their code)
*/
toString(): string {
const rowStringList = this.val.map((eachRow) => {
return eachRow
.map((eachValue) => {
if (this.digits <= 0) return String(eachValue);
else return String(eachValue.toFixed(this.digits));
})
.reduce(
(rowAccumulator, currentElementString) => rowAccumulator + ',' + currentElementString
);
});
let returnString = '';
for (let rowIndex = 0; rowIndex < rowStringList.length; rowIndex += 1) {
returnString +=
'[' + rowStringList[rowIndex] + ']' + (rowIndex === rowStringList.length - 1 ? '' : ',\n');
}
return '\n[' + returnString + ']\n';
}
/*serialize matrix to 2D Array with Tab, for example:
1 2
3 4
*/
toStringWithTab(): string {
let returnString = '';
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++) {
// if keeps all digits
if (this.digits <= 0) {
if (j === 0) {
returnString += String(this.val[i][j]);
} else {
returnString += '\t' + String(this.val[i][j]);
}
} else {
if (j === 0) {
returnString += this.val[i][j].toFixed(this.digits);
} else {
returnString += '\t' + this.val[i][j].toFixed(this.digits);
}
}
}
if (i !== this.rows - 1) returnString += '\n';
}
return returnString + '\n';
}
//return the format of matrix as a CSV string
toCsv(): string {
return mat2csv(this);
}
//return the string of current object in JSON format
toJson(): string {
return JSON.stringify(this);
}
//return the matrix in TeX format
toTex(): string {
let returnString = '\\begin{bmatrix} ';
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++) {
// if keeps all digits
if (this.digits === -1) {
if (j === 0) {
returnString += String(this.val[i][j]);
} else {
returnString += ' & ' + String(this.val[i][j]);
}
} else {
if (j === 0) {
returnString += this.val[i][j].toFixed(this.digits);
} else {
returnString += ' & ' + this.val[i][j].toFixed(this.digits);
}
}
}
if (i !== this.rows - 1) returnString += ' \\\\ ';
}
return returnString + ' \\end{bmatrix}';
}
//output the whole information to console
log(): Mat {
console.log(this);
return this;
} //output in console
//append matrix x to the bottom
//A = [A]
// [x]
appendInRow(x_: Mat): Mat {
const x = x_.clone();
if (x.cols !== this.cols) {
throw new Error('Dimension does not match on appendInRow()');
}
this.val.push(...x.val);
this.rows += x.rows;
return this;
}
//append matrix x to the right
//A = [A|x]
appendInColumn(x_: Mat): Mat {
const x = x_.clone();
if (x.rows !== this.rows) {
throw new Error('Dimension does not match on appendInColumn()');
}
for (let i = 0; i < this.rows; i++) {
this.val[i].push(...x.val[i]);
}
this.cols += x.cols;
return this;
}
}
// below are matrix operators, including add, minus, multiply and dot multiply
//leftMatrix + rightMatrix, save the result into left matrix
function addInPlace(leftMatrix: Mat, rightMatrix: Mat): Mat {
if (leftMatrix.rows !== rightMatrix.rows || leftMatrix.cols !== rightMatrix.cols)
throw new Error('Dimension does not match for operation:add');
const rows = leftMatrix.rows,
cols = leftMatrix.cols;
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
leftMatrix.val[i][j] += rightMatrix.val[i][j];
}
}
return leftMatrix;
}
//leftMatrix + rightMatrix, save the result into a new matrix
function add(leftMat: Mat, rightMat: Mat): Mat {
return addInPlace(leftMat.clone(), rightMat);
}
//leftMatrix - rightMatrix, save the result into left matrix
function minusInPlace(leftMatrix: Mat, rightMatrix: Mat): Mat {
if (leftMatrix.rows !== rightMatrix.rows || leftMatrix.cols !== rightMatrix.cols)
throw new Error('Dimension does not match for operation:minus');
const rows = leftMatrix.rows,
cols = leftMatrix.cols;
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
leftMatrix.val[i][j] -= rightMatrix.val[i][j];
}
}
return leftMatrix;
}
//leftMatrix - rightMatrix, save the result into a new matrix
function minus(leftMat: Mat, rightMat: Mat): Mat {
return minusInPlace(leftMat.clone(), rightMat);
}
// leftMat * rightMat and return a new matrix
function multiply(leftMat: Mat, rightMat: Mat): Mat {
if (leftMat.cols !== rightMat.rows)
throw new Error('Dimension does not match for operation:muitiply');
if (leftMat.mode === 'gpu' || rightMat.mode === 'gpu') return multiply_gpu(leftMat, rightMat);
const m = leftMat.rows,
n = leftMat.cols,
p = rightMat.cols;
const returnMatrix = new Mat().zeros(m, p);
for (let i = 0; i < m; i++) {
for (let j = 0; j < p; j++) {
let val = 0;
for (let it = 0; it < n; it++) val += leftMat.val[i][it] * rightMat.val[it][j];
returnMatrix.val[i][j] = val;
}
}
return returnMatrix;
}
// leftMat * rightMat and save the result to left matrix
function multiplyInPlace(leftMat: Mat, rightMat: Mat): Mat {
const resultMatrix = multiply(leftMat, rightMat);
leftMat.copy(resultMatrix);
return leftMat;
}
// leftMat * rightMat in GPU
function multiply_gpu(leftMat: Mat, rightMat: Mat): Mat {
console.log('GPU is used for matrix multiplication acceleration.');
//const gpu = new gpu();
const m = leftMat.rows,
n = leftMat.cols,
p = rightMat.cols;
//here is a tricky thing: if we want to set the for-loop as the column number of left
//matrix n, it will throw an exception because the oprand 'n' cannot be passed
//into the backend. So we create the javascript function and compose the raw function
//string before passing it into the create kernal function of gpu.js
const mulfunction_part_1 = `function (a, b) {
let sum = 0;
for (let i = 0; i < `;
const mulfunction_part_2 = `; i++) {
sum += a[this.thread.y][i] * b[i][this.thread.x];
}
return sum;
}`;
const mulfunction_string = mulfunction_part_1 + n.toString() + mulfunction_part_2;
// FIXME: evil as any
const multiplyMatrix = gpu.createKernel(mulfunction_string as any).setOutput([m, p]);
const c = multiplyMatrix(leftMat.val, rightMat.val);
const returnMat = new Mat();
returnMat.val = c as number[][];
returnMat.rows = m;
returnMat.cols = p;
return returnMat;
}
// leftMat .* rightMat, each element in leftMat multiply corresponding element in rightMat
function dotMultiplyInPlace(leftMat: Mat, rightMat: Mat): Mat {
if (leftMat.rows !== rightMat.rows || leftMat.cols !== rightMat.cols)
throw new Error('Dimension does not match for operation:dot muitiply');
for (let i = 0; i < leftMat.rows; i++) {
for (let j = 0; j < leftMat.cols; j++) {
leftMat.val[i][j] *= rightMat.val[i][j];
}
}
return leftMat;
}
function dotMultiply(leftMat: Mat, rightMat: Mat): Mat {
return dotMultiplyInPlace(leftMat.clone(), rightMat);
}
// leftMat ./ rightMat
function dotDivideInplace(leftMat: Mat, rightMat: Mat): Mat {
if (leftMat.rows !== rightMat.rows || leftMat.cols !== rightMat.cols)
throw new Error('Dimension does not match for operation: divide');
for (let i = 0; i < leftMat.rows; i++) {
for (let j = 0; j < leftMat.cols; j++) {
leftMat.val[i][j] /= rightMat.val[i][j];
}
}
return leftMat.clone();
}
function dotDivide(leftMat: Mat, rightMat: Mat): Mat {
return dotDivideInplace(leftMat.clone(), rightMat);
}
// leftMat / rightMat = leftMat * inv(rightMat)
function divideInPlace(leftMat: Mat, rightMat: Mat): Mat {
return multiplyInPlace(leftMat, new Mat(mathjs.inv(rightMat.val)));
}
function divide(leftMat: Mat, rightMat: Mat): Mat {
return divideInPlace(leftMat.clone(), rightMat);
}
//Matrix to CSV
export function mat2csv(A: Mat): string {
let returnCSV = '';
for (let i = 0; i < A.rows; i++) {
for (let j = 0; j < A.cols; j++) {
if (j === 0) {
returnCSV += String(A.val[i][j]);
} else {
returnCSV += ',' + String(A.val[i][j]);
}
}
returnCSV += '\n';
}
return returnCSV;
}
//CSV to Matrix
export function csv2mat(strCSV: string): Mat {
const A = new Mat();
try {
if (csv2mat.length === 0) return A;
const split_result = strCSV.split('\n');
const linesOfCSVString = split_result.filter((x) => x.length > 0);
const rows = linesOfCSVString.length;
const cols = linesOfCSVString[0].split(',').length;
A.zeros(rows, cols);
//process each line
for (let row = 0; row < rows; row++) {
const eachRowString = linesOfCSVString[row];
const listOfElement = eachRowString.split(',');
if (listOfElement.length !== cols)
throw new Error(
'Current row ' + row.toString() + ' does not have same element as first row'
);
for (let col = 0; col < cols; col++) {
A.val[row][col] = Number(listOfElement[col]);
}
}
} catch (err) {
throw new Error('Cannot parse matrix from csv file. Exception: ' + err);
}
return A;
}
//Matrix to Json
export function mat2json(A: Mat): string {
return JSON.stringify(A);
}
//Json to Matrix
export function json2mat(json_str: string): Mat {
const A = new Mat();
const obj = JSON.parse(json_str);
A.init(obj.val);
if (A.rows === obj.rows && A.cols === obj.cols) {
return A;
}
throw new Error('Fail to read matrix from json');
}
// Class Scalar is ONLY USED FOR OPERATOR OVERLOAD
export class Scalar {
val: number;
constructor(val: number) {
this.val = val;
}
//operator add
// scalar + rightMatrix
[Symbol.for('+')](rightOperand: Mat): Mat {
return rightOperand.addScalar(this.val);
}
// operator minus
// scalar - rightMatrix
[Symbol.for('-')](rightOperand: Mat): Mat {
return rightOperand.multiplyScalar(-1).addScalar(this.val);
}
// operator multiply
// scalar * rightMatrix === rightMatrix .* scalar
[Symbol.for('*')](rightOperand: Mat | number | number[] | number[][]): Mat {
if (rightOperand instanceof Mat) {
return rightOperand.multiplyScalar(this.val);
}
return new Mat(rightOperand).multiplyScalar(this.val);
}
} | the_stack |
import logger from '../logger';
import * as WebSocket from 'ws';
import { BlockExtended, TransactionExtended, WebsocketResponse, MempoolBlock, MempoolBlockDelta,
OptimizedStatistic, ILoadingIndicators, IConversionRates } from '../mempool.interfaces';
import blocks from './blocks';
import memPool from './mempool';
import backendInfo from './backend-info';
import mempoolBlocks from './mempool-blocks';
import fiatConversion from './fiat-conversion';
import { Common } from './common';
import loadingIndicators from './loading-indicators';
import config from '../config';
import transactionUtils from './transaction-utils';
import rbfCache from './rbf-cache';
import difficultyAdjustment from './difficulty-adjustment';
import feeApi from './fee-api';
class WebsocketHandler {
private wss: WebSocket.Server | undefined;
private extraInitProperties = {};
constructor() { }
setWebsocketServer(wss: WebSocket.Server) {
this.wss = wss;
}
setExtraInitProperties(property: string, value: any) {
this.extraInitProperties[property] = value;
}
setupConnectionHandling() {
if (!this.wss) {
throw new Error('WebSocket.Server is not set');
}
this.wss.on('connection', (client: WebSocket) => {
client.on('error', logger.info);
client.on('message', async (message: string) => {
try {
const parsedMessage: WebsocketResponse = JSON.parse(message);
const response = {};
if (parsedMessage.action === 'want') {
client['want-blocks'] = parsedMessage.data.indexOf('blocks') > -1;
client['want-mempool-blocks'] = parsedMessage.data.indexOf('mempool-blocks') > -1;
client['want-live-2h-chart'] = parsedMessage.data.indexOf('live-2h-chart') > -1;
client['want-stats'] = parsedMessage.data.indexOf('stats') > -1;
}
if (parsedMessage && parsedMessage['track-tx']) {
if (/^[a-fA-F0-9]{64}$/.test(parsedMessage['track-tx'])) {
client['track-tx'] = parsedMessage['track-tx'];
// Client is telling the transaction wasn't found
if (parsedMessage['watch-mempool']) {
const rbfCacheTx = rbfCache.get(client['track-tx']);
if (rbfCacheTx) {
response['txReplaced'] = {
txid: rbfCacheTx.txid,
};
client['track-tx'] = null;
} else {
// It might have appeared before we had the time to start watching for it
const tx = memPool.getMempool()[client['track-tx']];
if (tx) {
if (config.MEMPOOL.BACKEND === 'esplora') {
response['tx'] = tx;
} else {
// tx.prevout is missing from transactions when in bitcoind mode
try {
const fullTx = await transactionUtils.$getTransactionExtended(tx.txid, true);
response['tx'] = fullTx;
} catch (e) {
logger.debug('Error finding transaction: ' + (e instanceof Error ? e.message : e));
}
}
} else {
try {
const fullTx = await transactionUtils.$getTransactionExtended(client['track-tx'], true);
response['tx'] = fullTx;
} catch (e) {
logger.debug('Error finding transaction. ' + (e instanceof Error ? e.message : e));
client['track-mempool-tx'] = parsedMessage['track-tx'];
}
}
}
}
} else {
client['track-tx'] = null;
}
}
if (parsedMessage && parsedMessage['track-address']) {
if (/^([a-km-zA-HJ-NP-Z1-9]{26,35}|[a-km-zA-HJ-NP-Z1-9]{80}|[a-z]{2,5}1[ac-hj-np-z02-9]{8,100}|[A-Z]{2,5}1[AC-HJ-NP-Z02-9]{8,100})$/
.test(parsedMessage['track-address'])) {
let matchedAddress = parsedMessage['track-address'];
if (/^[A-Z]{2,5}1[AC-HJ-NP-Z02-9]{8,100}$/.test(parsedMessage['track-address'])) {
matchedAddress = matchedAddress.toLowerCase();
}
client['track-address'] = matchedAddress;
} else {
client['track-address'] = null;
}
}
if (parsedMessage && parsedMessage['track-asset']) {
if (/^[a-fA-F0-9]{64}$/.test(parsedMessage['track-asset'])) {
client['track-asset'] = parsedMessage['track-asset'];
} else {
client['track-asset'] = null;
}
}
if (parsedMessage && parsedMessage['track-mempool-block'] !== undefined) {
if (Number.isInteger(parsedMessage['track-mempool-block']) && parsedMessage['track-mempool-block'] >= 0) {
const index = parsedMessage['track-mempool-block'];
client['track-mempool-block'] = index;
const mBlocksWithTransactions = mempoolBlocks.getMempoolBlocksWithTransactions();
response['projected-block-transactions'] = {
index: index,
blockTransactions: mBlocksWithTransactions[index]?.transactions || [],
};
} else {
client['track-mempool-block'] = null;
}
}
if (parsedMessage.action === 'init') {
const _blocks = blocks.getBlocks().slice(-config.MEMPOOL.INITIAL_BLOCKS_AMOUNT);
if (!_blocks) {
return;
}
client.send(JSON.stringify(this.getInitData(_blocks)));
}
if (parsedMessage.action === 'ping') {
response['pong'] = true;
}
if (parsedMessage['track-donation'] && parsedMessage['track-donation'].length === 22) {
client['track-donation'] = parsedMessage['track-donation'];
}
if (parsedMessage['track-bisq-market']) {
if (/^[a-z]{3}_[a-z]{3}$/.test(parsedMessage['track-bisq-market'])) {
client['track-bisq-market'] = parsedMessage['track-bisq-market'];
} else {
client['track-bisq-market'] = null;
}
}
if (Object.keys(response).length) {
client.send(JSON.stringify(response));
}
} catch (e) {
logger.debug('Error parsing websocket message: ' + (e instanceof Error ? e.message : e));
}
});
});
}
handleNewDonation(id: string) {
if (!this.wss) {
throw new Error('WebSocket.Server is not set');
}
this.wss.clients.forEach((client: WebSocket) => {
if (client.readyState !== WebSocket.OPEN) {
return;
}
if (client['track-donation'] === id) {
client.send(JSON.stringify({ donationConfirmed: true }));
}
});
}
handleLoadingChanged(indicators: ILoadingIndicators) {
if (!this.wss) {
throw new Error('WebSocket.Server is not set');
}
this.wss.clients.forEach((client: WebSocket) => {
if (client.readyState !== WebSocket.OPEN) {
return;
}
client.send(JSON.stringify({ loadingIndicators: indicators }));
});
}
handleNewConversionRates(conversionRates: IConversionRates) {
if (!this.wss) {
throw new Error('WebSocket.Server is not set');
}
this.wss.clients.forEach((client: WebSocket) => {
if (client.readyState !== WebSocket.OPEN) {
return;
}
client.send(JSON.stringify({ conversions: conversionRates }));
});
}
getInitData(_blocks?: BlockExtended[]) {
if (!_blocks) {
_blocks = blocks.getBlocks().slice(-config.MEMPOOL.INITIAL_BLOCKS_AMOUNT);
}
return {
'mempoolInfo': memPool.getMempoolInfo(),
'vBytesPerSecond': memPool.getVBytesPerSecond(),
'blocks': _blocks,
'conversions': fiatConversion.getConversionRates(),
'mempool-blocks': mempoolBlocks.getMempoolBlocks(),
'transactions': memPool.getLatestTransactions(),
'backendInfo': backendInfo.getBackendInfo(),
'loadingIndicators': loadingIndicators.getLoadingIndicators(),
'da': difficultyAdjustment.getDifficultyAdjustment(),
'fees': feeApi.getRecommendedFee(),
...this.extraInitProperties
};
}
handleNewStatistic(stats: OptimizedStatistic) {
if (!this.wss) {
throw new Error('WebSocket.Server is not set');
}
this.wss.clients.forEach((client: WebSocket) => {
if (client.readyState !== WebSocket.OPEN) {
return;
}
if (!client['want-live-2h-chart']) {
return;
}
client.send(JSON.stringify({
'live-2h-chart': stats
}));
});
}
handleMempoolChange(newMempool: { [txid: string]: TransactionExtended },
newTransactions: TransactionExtended[], deletedTransactions: TransactionExtended[]) {
if (!this.wss) {
throw new Error('WebSocket.Server is not set');
}
mempoolBlocks.updateMempoolBlocks(newMempool);
const mBlocks = mempoolBlocks.getMempoolBlocks();
const mBlockDeltas = mempoolBlocks.getMempoolBlockDeltas();
const mempoolInfo = memPool.getMempoolInfo();
const vBytesPerSecond = memPool.getVBytesPerSecond();
const rbfTransactions = Common.findRbfTransactions(newTransactions, deletedTransactions);
const da = difficultyAdjustment.getDifficultyAdjustment();
memPool.handleRbfTransactions(rbfTransactions);
const recommendedFees = feeApi.getRecommendedFee();
this.wss.clients.forEach(async (client: WebSocket) => {
if (client.readyState !== WebSocket.OPEN) {
return;
}
const response = {};
if (client['want-stats']) {
response['mempoolInfo'] = mempoolInfo;
response['vBytesPerSecond'] = vBytesPerSecond;
response['transactions'] = newTransactions.slice(0, 6).map((tx) => Common.stripTransaction(tx));
response['da'] = da;
response['fees'] = recommendedFees;
}
if (client['want-mempool-blocks']) {
response['mempool-blocks'] = mBlocks;
}
if (client['track-mempool-tx']) {
const tx = newTransactions.find((t) => t.txid === client['track-mempool-tx']);
if (tx) {
if (config.MEMPOOL.BACKEND !== 'esplora') {
try {
const fullTx = await transactionUtils.$getTransactionExtended(tx.txid, true);
response['tx'] = fullTx;
} catch (e) {
logger.debug('Error finding transaction in mempool: ' + (e instanceof Error ? e.message : e));
}
} else {
response['tx'] = tx;
}
client['track-mempool-tx'] = null;
}
}
if (client['track-address']) {
const foundTransactions: TransactionExtended[] = [];
for (const tx of newTransactions) {
const someVin = tx.vin.some((vin) => !!vin.prevout && vin.prevout.scriptpubkey_address === client['track-address']);
if (someVin) {
if (config.MEMPOOL.BACKEND !== 'esplora') {
try {
const fullTx = await transactionUtils.$getTransactionExtended(tx.txid, true);
foundTransactions.push(fullTx);
} catch (e) {
logger.debug('Error finding transaction in mempool: ' + (e instanceof Error ? e.message : e));
}
} else {
foundTransactions.push(tx);
}
return;
}
const someVout = tx.vout.some((vout) => vout.scriptpubkey_address === client['track-address']);
if (someVout) {
if (config.MEMPOOL.BACKEND !== 'esplora') {
try {
const fullTx = await transactionUtils.$getTransactionExtended(tx.txid, true);
foundTransactions.push(fullTx);
} catch (e) {
logger.debug('Error finding transaction in mempool: ' + (e instanceof Error ? e.message : e));
}
} else {
foundTransactions.push(tx);
}
}
}
if (foundTransactions.length) {
response['address-transactions'] = foundTransactions;
}
}
if (client['track-asset']) {
const foundTransactions: TransactionExtended[] = [];
newTransactions.forEach((tx) => {
if (client['track-asset'] === Common.nativeAssetId) {
if (tx.vin.some((vin) => !!vin.is_pegin)) {
foundTransactions.push(tx);
return;
}
if (tx.vout.some((vout) => !!vout.pegout)) {
foundTransactions.push(tx);
}
} else {
if (tx.vin.some((vin) => !!vin.issuance && vin.issuance.asset_id === client['track-asset'])) {
foundTransactions.push(tx);
return;
}
if (tx.vout.some((vout) => !!vout.asset && vout.asset === client['track-asset'])) {
foundTransactions.push(tx);
}
}
});
if (foundTransactions.length) {
response['address-transactions'] = foundTransactions;
}
}
if (client['track-tx']) {
const outspends: object = {};
newTransactions.forEach((tx) => tx.vin.forEach((vin, i) => {
if (vin.txid === client['track-tx']) {
outspends[vin.vout] = {
vin: i,
txid: tx.txid,
};
}
}));
if (Object.keys(outspends).length) {
response['utxoSpent'] = outspends;
}
if (rbfTransactions[client['track-tx']]) {
for (const rbfTransaction in rbfTransactions) {
if (client['track-tx'] === rbfTransaction) {
response['rbfTransaction'] = {
txid: rbfTransactions[rbfTransaction].txid,
};
break;
}
}
}
}
if (client['track-mempool-block'] >= 0) {
const index = client['track-mempool-block'];
if (mBlockDeltas[index]) {
response['projected-block-transactions'] = {
index: index,
delta: mBlockDeltas[index],
};
}
}
if (Object.keys(response).length) {
client.send(JSON.stringify(response));
}
});
}
handleNewBlock(block: BlockExtended, txIds: string[], transactions: TransactionExtended[]) {
if (!this.wss) {
throw new Error('WebSocket.Server is not set');
}
let mBlocks: undefined | MempoolBlock[];
let mBlockDeltas: undefined | MempoolBlockDelta[];
let matchRate = 0;
const _memPool = memPool.getMempool();
const _mempoolBlocks = mempoolBlocks.getMempoolBlocksWithTransactions();
if (_mempoolBlocks[0]) {
const matches: string[] = [];
for (const txId of txIds) {
if (_mempoolBlocks[0].transactionIds.indexOf(txId) > -1) {
matches.push(txId);
}
delete _memPool[txId];
}
matchRate = Math.round((matches.length / (txIds.length - 1)) * 100);
mempoolBlocks.updateMempoolBlocks(_memPool);
mBlocks = mempoolBlocks.getMempoolBlocks();
mBlockDeltas = mempoolBlocks.getMempoolBlockDeltas();
}
if (block.extras) {
block.extras.matchRate = matchRate;
}
const da = difficultyAdjustment.getDifficultyAdjustment();
const fees = feeApi.getRecommendedFee();
this.wss.clients.forEach((client) => {
if (client.readyState !== WebSocket.OPEN) {
return;
}
if (!client['want-blocks']) {
return;
}
const response = {
'block': block,
'mempoolInfo': memPool.getMempoolInfo(),
'da': da,
'fees': fees,
};
if (mBlocks && client['want-mempool-blocks']) {
response['mempool-blocks'] = mBlocks;
}
if (client['track-tx'] && txIds.indexOf(client['track-tx']) > -1) {
response['txConfirmed'] = true;
}
if (client['track-address']) {
const foundTransactions: TransactionExtended[] = [];
transactions.forEach((tx) => {
if (tx.vin && tx.vin.some((vin) => !!vin.prevout && vin.prevout.scriptpubkey_address === client['track-address'])) {
foundTransactions.push(tx);
return;
}
if (tx.vout && tx.vout.some((vout) => vout.scriptpubkey_address === client['track-address'])) {
foundTransactions.push(tx);
}
});
if (foundTransactions.length) {
foundTransactions.forEach((tx) => {
tx.status = {
confirmed: true,
block_height: block.height,
block_hash: block.id,
block_time: block.timestamp,
};
});
response['block-transactions'] = foundTransactions;
}
}
if (client['track-asset']) {
const foundTransactions: TransactionExtended[] = [];
transactions.forEach((tx) => {
if (client['track-asset'] === Common.nativeAssetId) {
if (tx.vin && tx.vin.some((vin) => !!vin.is_pegin)) {
foundTransactions.push(tx);
return;
}
if (tx.vout && tx.vout.some((vout) => !!vout.pegout)) {
foundTransactions.push(tx);
}
} else {
if (tx.vin && tx.vin.some((vin) => !!vin.issuance && vin.issuance.asset_id === client['track-asset'])) {
foundTransactions.push(tx);
return;
}
if (tx.vout && tx.vout.some((vout) => !!vout.asset && vout.asset === client['track-asset'])) {
foundTransactions.push(tx);
}
}
});
if (foundTransactions.length) {
foundTransactions.forEach((tx) => {
tx.status = {
confirmed: true,
block_height: block.height,
block_hash: block.id,
block_time: block.timestamp,
};
});
response['block-transactions'] = foundTransactions;
}
}
if (client['track-mempool-block'] >= 0) {
const index = client['track-mempool-block'];
if (mBlockDeltas && mBlockDeltas[index]) {
response['projected-block-transactions'] = {
index: index,
delta: mBlockDeltas[index],
};
}
}
client.send(JSON.stringify(response));
});
}
}
export default new WebsocketHandler(); | the_stack |
import { ColorInput, TinyColor } from '@ctrl/tinycolor';
import _ from 'lodash';
export class Color {
private _name!: string;
private _value!: ColorInput;
private _computed!: TinyColor;
/**
* Creates a color.
*/
constructor(name: string, value: ColorInput) {
this.setName(name);
this.setValue(value);
}
/**
* Gets the color's name.
*/
getName(): string {
return this._name;
}
/**
* Sets the color's name.
*/
setName(name: string): this {
this._name = name;
return this;
}
/**
* Get the computed color value.
*/
getValue(): TinyColor {
return this._computed;
}
/**
* Set the color.
*/
setValue(value: ColorInput): this {
this._value = value;
this._computed = new TinyColor(value);
return this;
}
/**
* Gets the original value.
*/
getOriginalValue(): ColorInput {
return this._value;
}
}
/**
* A color that may be affected by multiple variants.
*/
export class VariableColor extends Color {
private _variants: CustomVariant[];
constructor(name: string, value: ColorInput) {
super(name, value);
this._variants = [];
}
/**
* Adds a variant to that color.
*/
setVariant(variant: CustomVariant): this {
this._variants.push(variant);
return this;
}
/**
* Sets a color variant for that color.
*/
setColorVariant(name: string, value: ColorInput): this {
this._variants.push(new ColorVariant(name, value));
return this;
}
/**
* Sets a color variant for that color.
*/
setOpacityVariant(name: string, value: number): this {
this._variants.push(new OpacityVariant(name, value));
return this;
}
/**
* Sets a custom variant for that color.
*/
setCustomVariant(name: string, transformer: VariantTransformer): this {
this._variants.push(new CustomVariant(name, transformer));
return this;
}
/**
* Gets every variants for this color.
*/
getVariants(): Variant[] {
return this._variants;
}
/**
* Gets every color variant for this color.
*/
getColorVariants(): ColorVariant[] {
return this.getVariantsByType(VariantType.Color) as ColorVariant[];
}
/**
* Gets every opacity variant for this color.
*/
getOpacityVariants(): OpacityVariant[] {
return this.getVariantsByType(VariantType.Opacity) as OpacityVariant[];
}
/**
* Gets every custom variant for this color.
*/
getCustomVariants(): CustomVariant[] {
return this.getVariantsByType(VariantType.Custom) as CustomVariant[];
}
/**
* Gets every variant of the specified type.
*/
getVariantsByType(type: VariantType): Variant[] {
return this._variants.filter((variant) => variant.getType() === type) as Variant[];
}
/**
* Get the name used for the Tailwind configuration. Kebab-cased.
*/
getTailwindConfigurationName(): string {
return _.kebabCase(this.getName());
}
/**
* Get the value used for the Tailwind configuration.
*/
getTailwindConfigurationValue(): string {
// https://github.com/tailwindcss/tailwindcss/pull/1676
// If that PR passes, this method will instead return a closure
// which will have an opacity variable name as a parameter,
// so that the opacity of this color can be changed via Tailwind CSS
// opacity utilities instead of being hardcoded in its value
const alpha = parseFloat(this.getValue().a.toFixed(8));
const colorVariable = `var(${this.getCssVariableName()})`;
return `rgba(${colorVariable}, ${alpha})`;
}
/**
* Get the CSS color variable name generated in the final CSS.
*/
getCssVariableName(): string {
return `--color-${this.getTailwindConfigurationName()}`;
}
/**
* Get the CSS variable value used in the final CSS.
*/
getCssVariableValue(): string {
// Opacity is hard-coded to the Tailwind configuration, because
// opacity variants exist, and if this PR passes, Tailwind's opacity
// utilities can be used instead.
const { r, g, b } = this.getValue();
return `${r}, ${g}, ${b}`;
}
}
export interface ColorObject {
[name: string]: ColorInput | ColorObject;
}
export interface SingleLevelColorObject {
[name: string]: ColorInput;
}
/**
* Represents the color schemes usable by the themes.
*
* @see https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme
*/
export enum ColorScheme {
/**
* Indicates that the theme has no specified color scheme.
*/
Undefined = 'no-preference',
/**
* Indicates that the theme is created for light themes.
*/
Light = 'light',
/**
* Indicates that the theme is created for dark themes.
*/
Dark = 'dark',
}
/**
* Represents the possible types of variants.
*/
export enum VariantType {
/**
* A normal variant.
*/
Custom,
/**
* A variant that replaces the color by another.
*/
Color,
/**
* A variant that changes the opacity of the color.
*/
Opacity,
}
/**
* Takes a color and returns a possibly transformed color.
*/
export type VariantTransformer = (color: TinyColor) => TinyColor;
/**
* Represents a variant.
*/
export interface Variant {
/**
* The type of the variant.
*/
getType(): VariantType;
/**
* The name of the variant.
*/
getName(): string;
/**
* Gets the variant type name for registering CSS variables.
*/
getVariantTypeName(): string;
/**
* Applies the variant on a color.
*
* @param input The color to apply the variant on.
*/
apply(input: ColorInput): TinyColor;
/**
* Gets the name of the variant key for the Tailwind configuration.
*/
getTailwindConfigurationName(): string;
/**
* Gets the value for this variant for the Tailwind configuration.
*/
getTailwindConfigurationValue(color: VariableColor): string;
/**
* Gets the name of the CSS variable for this variant.
*/
getCssVariableName(color: VariableColor): string;
/**
* Gets the value of the CSS variable for this variant.
*/
getCssVariableValue(color: VariableColor): string;
}
/**
* A variant that replaces its color thanks to a given logic.
*/
export class CustomVariant implements Variant {
private _name: string;
private _transformer: VariantTransformer;
/**
* Creates a variant.
*
* @param {string} name The variant's name.
* @param {VariantTransformer} transformer The method to transform the color.
*/
constructor(name: string, transformer: VariantTransformer) {
this._name = name;
this._transformer = transformer;
}
getType(): VariantType {
return VariantType.Custom;
}
getName(): string {
return this._name;
}
getVariantTypeName(): string {
return 'custom-variant';
}
getTailwindConfigurationName(): string {
return _.kebabCase(this.getName());
}
getCssVariableName(color: VariableColor): string {
const variantTypeName = this.getVariantTypeName();
const colorName = color.getTailwindConfigurationName(); // kebab-cased name
const variantName = this.getTailwindConfigurationName(); // kebab-case name
return `--${variantTypeName}-${colorName}-${variantName}`;
}
/**
* Gets the computed value of the color.
*/
apply(input: ColorInput): TinyColor {
return this._transformer(new TinyColor(input));
}
/**
* Gets an RGBA value separated by comas.
*/
getCssVariableValue(color: VariableColor): string {
const { r, g, b, a } = this.apply(color.getValue());
const alpha = parseFloat(a.toFixed(8));
return `${r.toFixed(0)}, ${g.toFixed(0)}, ${b.toFixed(0)}, ${alpha}`;
}
/**
* Gets an RGBA value with the name of this variant's variable as a parameter.
*/
getTailwindConfigurationValue(color: VariableColor): string {
const variantVariable = `var(${this.getCssVariableName(color)})`;
return `rgba(${variantVariable})`;
}
}
/**
* A variant that replaces its color by another color.
*/
export class ColorVariant extends CustomVariant {
private _replacement: ColorInput;
/**
* Creates a color variant.
*
* @param name This variant's name.
* @param replacement The replacement color.
*/
constructor(name: string, replacement: ColorInput) {
super(name, () => new TinyColor(replacement));
this._replacement = replacement;
}
getType(): VariantType {
return VariantType.Color;
}
getVariantTypeName(): string {
return 'color-variant';
}
/**
* Gets the replacement color.
*/
getReplacement(): ColorInput {
return this._replacement;
}
}
/**
* A variant that changes the opacity of its color.
*/
export class OpacityVariant extends CustomVariant {
private _opacity: number;
/**
* Creates an opacity variant.
*
* @param name This variant's name.
* @param opacity The new opacity.
*/
constructor(name: string, opacity: number) {
super(name, (color) => new TinyColor(color).setAlpha(opacity));
this._opacity = opacity;
}
getType(): VariantType {
return VariantType.Opacity;
}
getVariantTypeName(): string {
return 'opacity-variant';
}
/**
* Gets the opacity.
*/
getOpacity(): number {
return this._opacity;
}
/**
* Gets an RGB value separated by comas.
*/
getCssVariableValue(color: VariableColor): string {
return parseFloat(this.getOpacity().toFixed(8)).toString();
}
/**
* Gets an RGBA value with the name of the color variable as
* the first parameter and this variant's variable as the second
*/
getTailwindConfigurationValue(color: VariableColor): string {
const colorVariable = `var(${color.getCssVariableName()})`;
const opacityVariable = `var(${this.getCssVariableName(color)})`;
return `rgba(${colorVariable}, ${opacityVariable})`;
}
}
/**
* Represents all the types accepted for an object-based variant value.
*/
export type VariantInput = ColorInput | VariantTransformer | number;
/**
* An object that contains multiple variants of multiple types.
*/
export interface VariantsObject {
[variantName: string]: VariantInput | MappedVariant;
}
/**
* Represents a variant mapped to one or multiple colors.
*/
export interface MappedVariant {
variant: VariantInput;
colors: string | string[];
} | the_stack |
import * as React from 'react';
import { composeEventHandlers } from '@radix-ui/primitive';
import { useComposedRefs } from '@radix-ui/react-compose-refs';
import { createContextScope } from '@radix-ui/react-context';
import { useControllableState } from '@radix-ui/react-use-controllable-state';
import * as PopperPrimitive from '@radix-ui/react-popper';
import { createPopperScope } from '@radix-ui/react-popper';
import { DismissableLayer } from '@radix-ui/react-dismissable-layer';
import { FocusScope } from '@radix-ui/react-focus-scope';
import { Portal } from '@radix-ui/react-portal';
import { useFocusGuards } from '@radix-ui/react-focus-guards';
import { Presence } from '@radix-ui/react-presence';
import { Primitive } from '@radix-ui/react-primitive';
import { useId } from '@radix-ui/react-id';
import { RemoveScroll } from 'react-remove-scroll';
import { hideOthers } from 'aria-hidden';
import type * as Radix from '@radix-ui/react-primitive';
import type { Scope } from '@radix-ui/react-context';
/* -------------------------------------------------------------------------------------------------
* Popover
* -----------------------------------------------------------------------------------------------*/
const POPOVER_NAME = 'Popover';
type ScopedProps<P> = P & { __scopePopover?: Scope };
const [createPopoverContext, createPopoverScope] = createContextScope(POPOVER_NAME, [
createPopperScope,
]);
const usePopperScope = createPopperScope();
type PopoverContextValue = {
triggerRef: React.RefObject<HTMLButtonElement>;
contentId: string;
open: boolean;
onOpenChange(open: boolean): void;
onOpenToggle(): void;
hasCustomAnchor: boolean;
onCustomAnchorAdd(): void;
onCustomAnchorRemove(): void;
modal: boolean;
};
const [PopoverProvider, usePopoverContext] =
createPopoverContext<PopoverContextValue>(POPOVER_NAME);
interface PopoverProps {
open?: boolean;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
modal?: boolean;
children?: React.ReactNode;
}
const Popover: React.FC<PopoverProps> = (props: ScopedProps<PopoverProps>) => {
const {
__scopePopover,
children,
open: openProp,
defaultOpen,
onOpenChange,
modal = false,
} = props;
const popperScope = usePopperScope(__scopePopover);
const triggerRef = React.useRef<HTMLButtonElement>(null);
const [hasCustomAnchor, setHasCustomAnchor] = React.useState(false);
const [open = false, setOpen] = useControllableState({
prop: openProp,
defaultProp: defaultOpen,
onChange: onOpenChange,
});
return (
<PopperPrimitive.Root {...popperScope}>
<PopoverProvider
scope={__scopePopover}
contentId={useId()}
triggerRef={triggerRef}
open={open}
onOpenChange={setOpen}
onOpenToggle={React.useCallback(() => setOpen((prevOpen) => !prevOpen), [setOpen])}
hasCustomAnchor={hasCustomAnchor}
onCustomAnchorAdd={React.useCallback(() => setHasCustomAnchor(true), [])}
onCustomAnchorRemove={React.useCallback(() => setHasCustomAnchor(false), [])}
modal={modal}
>
{children}
</PopoverProvider>
</PopperPrimitive.Root>
);
};
Popover.displayName = POPOVER_NAME;
/* -------------------------------------------------------------------------------------------------
* PopoverAnchor
* -----------------------------------------------------------------------------------------------*/
const ANCHOR_NAME = 'PopoverAnchor';
type PopoverAnchorElement = React.ElementRef<typeof PopperPrimitive.Anchor>;
type PopperAnchorProps = Radix.ComponentPropsWithoutRef<typeof PopperPrimitive.Anchor>;
interface PopoverAnchorProps extends PopperAnchorProps {}
const PopoverAnchor = React.forwardRef<PopoverAnchorElement, PopoverAnchorProps>(
(props: ScopedProps<PopoverAnchorProps>, forwardedRef) => {
const { __scopePopover, ...anchorProps } = props;
const context = usePopoverContext(ANCHOR_NAME, __scopePopover);
const popperScope = usePopperScope(__scopePopover);
const { onCustomAnchorAdd, onCustomAnchorRemove } = context;
React.useEffect(() => {
onCustomAnchorAdd();
return () => onCustomAnchorRemove();
}, [onCustomAnchorAdd, onCustomAnchorRemove]);
return <PopperPrimitive.Anchor {...popperScope} {...anchorProps} ref={forwardedRef} />;
}
);
PopoverAnchor.displayName = ANCHOR_NAME;
/* -------------------------------------------------------------------------------------------------
* PopoverTrigger
* -----------------------------------------------------------------------------------------------*/
const TRIGGER_NAME = 'PopoverTrigger';
type PopoverTriggerElement = React.ElementRef<typeof Primitive.button>;
type PrimitiveButtonProps = Radix.ComponentPropsWithoutRef<typeof Primitive.button>;
interface PopoverTriggerProps extends PrimitiveButtonProps {}
const PopoverTrigger = React.forwardRef<PopoverTriggerElement, PopoverTriggerProps>(
(props: ScopedProps<PopoverTriggerProps>, forwardedRef) => {
const { __scopePopover, ...triggerProps } = props;
const context = usePopoverContext(TRIGGER_NAME, __scopePopover);
const popperScope = usePopperScope(__scopePopover);
const composedTriggerRef = useComposedRefs(forwardedRef, context.triggerRef);
const trigger = (
<Primitive.button
type="button"
aria-haspopup="dialog"
aria-expanded={context.open}
aria-controls={context.contentId}
data-state={getState(context.open)}
{...triggerProps}
ref={composedTriggerRef}
onClick={composeEventHandlers(props.onClick, context.onOpenToggle)}
/>
);
return context.hasCustomAnchor ? (
trigger
) : (
<PopperPrimitive.Anchor asChild {...popperScope}>
{trigger}
</PopperPrimitive.Anchor>
);
}
);
PopoverTrigger.displayName = TRIGGER_NAME;
/* -------------------------------------------------------------------------------------------------
* PopoverContent
* -----------------------------------------------------------------------------------------------*/
const CONTENT_NAME = 'PopoverContent';
interface PopoverContentProps extends PopoverContentTypeProps {
/**
* Used to force mounting when more control is needed. Useful when
* controlling animation with React animation libraries.
*/
forceMount?: true;
}
const PopoverContent = React.forwardRef<PopoverContentTypeElement, PopoverContentProps>(
(props: ScopedProps<PopoverContentProps>, forwardedRef) => {
const { forceMount, ...contentProps } = props;
const context = usePopoverContext(CONTENT_NAME, props.__scopePopover);
return (
<Presence present={forceMount || context.open}>
{context.modal ? (
<PopoverContentModal {...contentProps} ref={forwardedRef} />
) : (
<PopoverContentNonModal {...contentProps} ref={forwardedRef} />
)}
</Presence>
);
}
);
PopoverContent.displayName = CONTENT_NAME;
/* -----------------------------------------------------------------------------------------------*/
type RemoveScrollProps = React.ComponentProps<typeof RemoveScroll>;
type PopoverContentTypeElement = PopoverContentImplElement;
interface PopoverContentTypeProps
extends Omit<PopoverContentImplProps, 'trapFocus' | 'disableOutsidePointerEvents'> {
/**
* @see https://github.com/theKashey/react-remove-scroll#usage
*/
allowPinchZoom?: RemoveScrollProps['allowPinchZoom'];
/**
* Whether the `Popover` should render in a `Portal`
* (default: `true`)
*/
portalled?: boolean;
}
const PopoverContentModal = React.forwardRef<PopoverContentTypeElement, PopoverContentTypeProps>(
(props: ScopedProps<PopoverContentTypeProps>, forwardedRef) => {
const { allowPinchZoom, portalled = true, ...contentModalProps } = props;
const context = usePopoverContext(CONTENT_NAME, props.__scopePopover);
const contentRef = React.useRef<HTMLDivElement>(null);
const composedRefs = useComposedRefs(forwardedRef, contentRef);
const isRightClickOutsideRef = React.useRef(false);
// aria-hide everything except the content (better supported equivalent to setting aria-modal)
React.useEffect(() => {
const content = contentRef.current;
if (content) return hideOthers(content);
}, []);
const PortalWrapper = portalled ? Portal : React.Fragment;
return (
<PortalWrapper>
<RemoveScroll allowPinchZoom={allowPinchZoom}>
<PopoverContentImpl
{...contentModalProps}
ref={composedRefs}
// we make sure we're not trapping once it's been closed
// (closed !== unmounted when animating out)
trapFocus={context.open}
disableOutsidePointerEvents
onCloseAutoFocus={composeEventHandlers(props.onCloseAutoFocus, (event) => {
event.preventDefault();
if (!isRightClickOutsideRef.current) context.triggerRef.current?.focus();
})}
onPointerDownOutside={composeEventHandlers(
props.onPointerDownOutside,
(event) => {
const originalEvent = event.detail.originalEvent;
const ctrlLeftClick = originalEvent.button === 0 && originalEvent.ctrlKey === true;
const isRightClick = originalEvent.button === 2 || ctrlLeftClick;
isRightClickOutsideRef.current = isRightClick;
},
{ checkForDefaultPrevented: false }
)}
// When focus is trapped, a `focusout` event may still happen.
// We make sure we don't trigger our `onDismiss` in such case.
onFocusOutside={composeEventHandlers(
props.onFocusOutside,
(event) => event.preventDefault(),
{ checkForDefaultPrevented: false }
)}
/>
</RemoveScroll>
</PortalWrapper>
);
}
);
const PopoverContentNonModal = React.forwardRef<PopoverContentTypeElement, PopoverContentTypeProps>(
(props: ScopedProps<PopoverContentTypeProps>, forwardedRef) => {
const { portalled = true, ...contentNonModalProps } = props;
const context = usePopoverContext(CONTENT_NAME, props.__scopePopover);
const hasInteractedOutsideRef = React.useRef(false);
const PortalWrapper = portalled ? Portal : React.Fragment;
return (
<PortalWrapper>
<PopoverContentImpl
{...contentNonModalProps}
ref={forwardedRef}
trapFocus={false}
disableOutsidePointerEvents={false}
onCloseAutoFocus={(event) => {
props.onCloseAutoFocus?.(event);
if (!event.defaultPrevented) {
if (!hasInteractedOutsideRef.current) context.triggerRef.current?.focus();
// Always prevent auto focus because we either focus manually or want user agent focus
event.preventDefault();
}
hasInteractedOutsideRef.current = false;
}}
onInteractOutside={(event) => {
props.onInteractOutside?.(event);
if (!event.defaultPrevented) hasInteractedOutsideRef.current = true;
// Prevent dismissing when clicking the trigger.
// As the trigger is already setup to close, without doing so would
// cause it to close and immediately open.
//
// We use `onInteractOutside` as some browsers also
// focus on pointer down, creating the same issue.
const target = event.target as HTMLElement;
const targetIsTrigger = context.triggerRef.current?.contains(target);
if (targetIsTrigger) event.preventDefault();
}}
/>
</PortalWrapper>
);
}
);
/* -----------------------------------------------------------------------------------------------*/
type PopoverContentImplElement = React.ElementRef<typeof PopperPrimitive.Content>;
type FocusScopeProps = Radix.ComponentPropsWithoutRef<typeof FocusScope>;
type DismissableLayerProps = Radix.ComponentPropsWithoutRef<typeof DismissableLayer>;
type PopperContentProps = Radix.ComponentPropsWithoutRef<typeof PopperPrimitive.Content>;
interface PopoverContentImplProps
extends PopperContentProps,
Omit<DismissableLayerProps, 'onDismiss'> {
/**
* Whether focus should be trapped within the `Popover`
* (default: false)
*/
trapFocus?: FocusScopeProps['trapped'];
/**
* Event handler called when auto-focusing on open.
* Can be prevented.
*/
onOpenAutoFocus?: FocusScopeProps['onMountAutoFocus'];
/**
* Event handler called when auto-focusing on close.
* Can be prevented.
*/
onCloseAutoFocus?: FocusScopeProps['onUnmountAutoFocus'];
}
const PopoverContentImpl = React.forwardRef<PopoverContentImplElement, PopoverContentImplProps>(
(props: ScopedProps<PopoverContentImplProps>, forwardedRef) => {
const {
__scopePopover,
trapFocus,
onOpenAutoFocus,
onCloseAutoFocus,
disableOutsidePointerEvents,
onEscapeKeyDown,
onPointerDownOutside,
onFocusOutside,
onInteractOutside,
...contentProps
} = props;
const context = usePopoverContext(CONTENT_NAME, __scopePopover);
const popperScope = usePopperScope(__scopePopover);
// Make sure the whole tree has focus guards as our `Popover` may be
// the last element in the DOM (beacuse of the `Portal`)
useFocusGuards();
return (
<FocusScope
asChild
loop
trapped={trapFocus}
onMountAutoFocus={onOpenAutoFocus}
onUnmountAutoFocus={onCloseAutoFocus}
>
<DismissableLayer
asChild
disableOutsidePointerEvents={disableOutsidePointerEvents}
onInteractOutside={onInteractOutside}
onEscapeKeyDown={onEscapeKeyDown}
onPointerDownOutside={onPointerDownOutside}
onFocusOutside={onFocusOutside}
onDismiss={() => context.onOpenChange(false)}
>
<PopperPrimitive.Content
data-state={getState(context.open)}
role="dialog"
id={context.contentId}
{...popperScope}
{...contentProps}
ref={forwardedRef}
style={{
...contentProps.style,
// re-namespace exposed content custom property
['--radix-popover-content-transform-origin' as any]:
'var(--radix-popper-transform-origin)',
}}
/>
</DismissableLayer>
</FocusScope>
);
}
);
/* -------------------------------------------------------------------------------------------------
* PopoverClose
* -----------------------------------------------------------------------------------------------*/
const CLOSE_NAME = 'PopoverClose';
type PopoverCloseElement = React.ElementRef<typeof Primitive.button>;
interface PopoverCloseProps extends PrimitiveButtonProps {}
const PopoverClose = React.forwardRef<PopoverCloseElement, PopoverCloseProps>(
(props: ScopedProps<PopoverCloseProps>, forwardedRef) => {
const { __scopePopover, ...closeProps } = props;
const context = usePopoverContext(CLOSE_NAME, __scopePopover);
return (
<Primitive.button
type="button"
{...closeProps}
ref={forwardedRef}
onClick={composeEventHandlers(props.onClick, () => context.onOpenChange(false))}
/>
);
}
);
PopoverClose.displayName = CLOSE_NAME;
/* -------------------------------------------------------------------------------------------------
* PopoverArrow
* -----------------------------------------------------------------------------------------------*/
const ARROW_NAME = 'PopoverArrow';
type PopoverArrowElement = React.ElementRef<typeof PopperPrimitive.Arrow>;
type PopperArrowProps = Radix.ComponentPropsWithoutRef<typeof PopperPrimitive.Arrow>;
interface PopoverArrowProps extends PopperArrowProps {}
const PopoverArrow = React.forwardRef<PopoverArrowElement, PopoverArrowProps>(
(props: ScopedProps<PopoverArrowProps>, forwardedRef) => {
const { __scopePopover, ...arrowProps } = props;
const popperScope = usePopperScope(__scopePopover);
return <PopperPrimitive.Arrow {...popperScope} {...arrowProps} ref={forwardedRef} />;
}
);
PopoverArrow.displayName = ARROW_NAME;
/* -----------------------------------------------------------------------------------------------*/
function getState(open: boolean) {
return open ? 'open' : 'closed';
}
const Root = Popover;
const Anchor = PopoverAnchor;
const Trigger = PopoverTrigger;
const Content = PopoverContent;
const Close = PopoverClose;
const Arrow = PopoverArrow;
export {
createPopoverScope,
//
Popover,
PopoverAnchor,
PopoverTrigger,
PopoverContent,
PopoverClose,
PopoverArrow,
//
Root,
Anchor,
Trigger,
Content,
Close,
Arrow,
};
export type {
PopoverProps,
PopoverAnchorProps,
PopoverTriggerProps,
PopoverContentProps,
PopoverCloseProps,
PopoverArrowProps,
}; | the_stack |
import { Trans, t } from "@lingui/macro";
import { i18nMark, withI18n } from "@lingui/react";
import PropTypes from "prop-types";
import * as React from "react";
import { Confirm } from "reactjs-components";
import { InfoBoxInline } from "@dcos/ui-kit";
import FullScreenModal from "#SRC/js/components/modals/FullScreenModal";
import FullScreenModalHeader from "#SRC/js/components/modals/FullScreenModalHeader";
import FullScreenModalHeaderActions from "#SRC/js/components/modals/FullScreenModalHeaderActions";
import ToggleButton from "#SRC/js/components/ToggleButton";
import ModalHeading from "#SRC/js/components/modals/ModalHeading";
import UniversePackage from "#SRC/js/structs/UniversePackage";
import Util from "#SRC/js/utils/Util";
import { getFirstTabAndField } from "#SRC/js/utils/FrameworkConfigurationUtil";
import StringUtil from "#SRC/js/utils/StringUtil";
import CosmosErrorMessage from "#SRC/js/components/CosmosErrorMessage";
import FrameworkConfigurationForm from "#SRC/js/components/FrameworkConfigurationForm";
import FrameworkConfigurationReviewScreen from "#SRC/js/components/FrameworkConfigurationReviewScreen";
import UserSettingsStore from "#SRC/js/stores/UserSettingsStore";
import CosmosPackagesStore from "#SRC/js/stores/CosmosPackagesStore";
import FrameworkUtil from "#PLUGINS/services/src/js/utils/FrameworkUtil";
import * as LastUpdated from "#SRC/js/components/LastUpdated";
class FrameworkConfiguration extends React.Component {
static propTypes = {
formData: PropTypes.object.isRequired,
formErrors: PropTypes.object.isRequired,
onFormDataChange: PropTypes.func.isRequired,
onFormErrorChange: PropTypes.func.isRequired,
packageDetails: PropTypes.instanceOf(UniversePackage).isRequired,
handleRun: PropTypes.func.isRequired,
handleGoBack: PropTypes.func.isRequired,
isInitialDeploy: PropTypes.bool,
deployErrors: PropTypes.object,
defaultConfigWarning: PropTypes.string,
};
constructor(props) {
super(props);
const { packageDetails } = this.props;
const { activeTab, focusField } = getFirstTabAndField(packageDetails);
this.state = {
reviewActive: false,
activeTab,
focusField,
jsonEditorActive: UserSettingsStore.JSONEditorExpandedSetting,
isConfirmOpen: false,
isOpen: true,
liveValidate: false,
};
}
deleteDeployErrors = () => {
if (this.props.onCosmosPackagesStoreInstallError) {
this.props.onCosmosPackagesStoreInstallError(null);
} else {
this.props.onCosmosPackagesStoreServiceUpdateError(null);
}
};
handleFocusFieldChange = (activeTab, focusField) => {
this.setState({ focusField, activeTab });
};
handleActiveTabChange = (activeTab) => {
const { packageDetails } = this.props;
const schema = packageDetails.getConfig();
const [focusField] = Object.keys(
Util.findNestedPropertyInObject(
schema,
`properties.${activeTab}.properties`
)
);
this.setState({ activeTab, focusField });
};
handleEditConfigurationButtonClick = () => {
this.deleteDeployErrors();
const { activeTab, focusField } = getFirstTabAndField(
this.props.packageDetails
);
this.setState({ reviewActive: false, activeTab, focusField });
};
handleJSONToggle = () => {
UserSettingsStore.setJSONEditorExpandedSetting(
!this.state.jsonEditorActive
);
this.setState({ jsonEditorActive: !this.state.jsonEditorActive });
};
handleCloseConfirmModal = () => {
this.setState({ isConfirmOpen: false });
};
handleGoBack = () => {
const { reviewActive } = this.state;
if (reviewActive) {
this.deleteDeployErrors();
this.setState({ reviewActive: false });
return;
}
this.setState({ isConfirmOpen: true });
};
handleServiceReview = () => {
const { handleRun } = this.props;
const { reviewActive } = this.state;
if (reviewActive) {
handleRun();
return;
}
// Only live validate once the form is submitted.
this.setState({ liveValidate: true }, () => {
// This is the prescribed method for submitting a react-jsonschema-form
// using an external control.
// https://github.com/mozilla-services/react-jsonschema-form#tips-and-tricks
this.submitButton.click();
});
};
handleConfirmGoBack = () => {
const { handleGoBack } = this.props;
this.setState({ isConfirmOpen: false, isOpen: false }, () => {
// Once state is set, start a timer for the length of the animation and
// navigate away once the animation is over.
setTimeout(handleGoBack, 300);
});
};
handleFormSubmit = () => {
this.setState({ liveValidate: false, reviewActive: true });
};
getSecondaryActions() {
const { reviewActive } = this.state;
return [
{
className: "button-primary-link button-flush-horizontal",
clickHandler: this.handleGoBack,
label: reviewActive ? i18nMark("Back") : i18nMark("Cancel"),
},
];
}
getPrimaryActions() {
const { jsonEditorActive, reviewActive } = this.state;
const { formErrors, isPending } = this.props;
const runButtonLabel = reviewActive
? i18nMark("Run Service")
: i18nMark("Review & Run");
const actions = [
{
className: "button-primary flush-vertical",
clickHandler: this.handleServiceReview,
label: isPending ? i18nMark("Installing...") : runButtonLabel,
disabled:
isPending ||
Object.keys(formErrors).some((tab) => formErrors[tab] > 0),
},
];
if (!reviewActive) {
actions.unshift({
node: (
<ToggleButton
className="flush"
checkboxClassName="toggle-button toggle-button-align-left"
checked={jsonEditorActive}
onChange={this.handleJSONToggle}
key="json-editor"
>
<Trans render="span">JSON Editor</Trans>
</ToggleButton>
),
});
}
return actions;
}
getTermsAndConditions() {
const { packageDetails, i18n } = this.props;
const termsUrl = packageDetails.isCertified()
? "https://mesosphere.com/catalog-terms-conditions/#certified-services"
: "https://mesosphere.com/catalog-terms-conditions/#community-services";
const termsAndConditions = i18n._(t`Terms and Conditions`);
return (
<Trans render="span">
By running this service you agree to the{" "}
<a href={termsUrl} target="_blank" title={termsAndConditions}>
terms and conditions
</a>
.
</Trans>
);
}
getWarningMessage() {
const { packageDetails } = this.props;
const preInstallNotes = packageDetails.getPreInstallNotes();
if (preInstallNotes) {
const notes = StringUtil.parseMarkdown(preInstallNotes);
return (
<div className="infoBoxWrapper">
<InfoBoxInline
appearance="warning"
message={
<div className="pre-install-notes">
<Trans render="strong">Preinstall Notes: </Trans>
<span dangerouslySetInnerHTML={notes} />
{this.getTermsAndConditions()}
</div>
}
/>
</div>
);
}
return (
<div className="infoBoxWrapper">
<InfoBoxInline
appearance="warning"
message={
<div className="pre-install-notes">
{this.getTermsAndConditions()}
</div>
}
/>
</div>
);
}
getReviewScreen() {
const {
deployErrors,
isInitialDeploy,
formData,
defaultConfigWarning,
} = this.props;
let warningMessage = null;
if (isInitialDeploy) {
warningMessage = this.getWarningMessage();
}
let defaultConfigWarningMessage = null;
if (defaultConfigWarning) {
defaultConfigWarningMessage = (
<InfoBoxInline
appearance="warning"
message={
<div>
<Trans render="strong">Warning: </Trans>
<Trans id={defaultConfigWarning} render="span" />
</div>
}
/>
);
}
const errorsAlert = deployErrors ? (
<CosmosErrorMessage error={deployErrors} />
) : null;
return (
<div className="flex-item-grow-1">
<div className="container">
{errorsAlert}
{warningMessage}
{defaultConfigWarningMessage}
<FrameworkConfigurationReviewScreen
frameworkData={formData}
onEditClick={this.handleEditConfigurationButtonClick}
/>
</div>
</div>
);
}
getHeader() {
const { reviewActive } = this.state;
const { packageDetails } = this.props;
const title = reviewActive
? i18nMark("Review Configuration")
: i18nMark("Edit Configuration");
const cosmosPackage = CosmosPackagesStore.getPackageDetails();
const lastUpdated = FrameworkUtil.getLastUpdated(cosmosPackage);
return (
<FullScreenModalHeader>
<FullScreenModalHeaderActions
actions={this.getSecondaryActions()}
type="secondary"
/>
<div className="modal-full-screen-header-title">
<Trans id={title} render="span" />
<div className="small">
{lastUpdated ? LastUpdated.warningIcon(lastUpdated) : null}{" "}
{StringUtil.capitalize(packageDetails.getName()) +
" " +
packageDetails.getVersion()}
</div>
</div>
<FullScreenModalHeaderActions
actions={this.getPrimaryActions()}
type="primary"
/>
</FullScreenModalHeader>
);
}
render() {
const {
isConfirmOpen,
isOpen,
reviewActive,
jsonEditorActive,
focusField,
activeTab,
} = this.state;
const {
packageDetails,
formErrors,
formData,
onFormDataChange,
onFormErrorChange,
defaultConfigWarning,
i18n,
} = this.props;
let pageContents;
if (reviewActive) {
pageContents = this.getReviewScreen();
} else {
pageContents = (
<FrameworkConfigurationForm
jsonEditorActive={jsonEditorActive}
focusField={focusField}
activeTab={activeTab}
handleActiveTabChange={this.handleActiveTabChange}
handleFocusFieldChange={this.handleFocusFieldChange}
formData={formData}
formErrors={formErrors}
packageDetails={packageDetails}
onFormDataChange={onFormDataChange}
onFormErrorChange={onFormErrorChange}
onFormSubmit={this.handleFormSubmit}
defaultConfigWarning={defaultConfigWarning}
submitRef={(el) => (this.submitButton = el)} // ref forwarding https://reactjs.org/docs/forwarding-refs.html
liveValidate={this.state.liveValidate}
/>
);
}
return (
<FullScreenModal
header={this.getHeader()}
useGemini={reviewActive}
open={isOpen}
>
{pageContents}
<Confirm
closeByBackdropClick={true}
header={
<ModalHeading>
<Trans render="span">Discard Changes?</Trans>
</ModalHeading>
}
open={isConfirmOpen}
onClose={this.handleCloseConfirmModal}
leftButtonText={i18n._(t`Cancel`)}
leftButtonCallback={this.handleCloseConfirmModal}
rightButtonText={i18n._(t`Discard`)}
rightButtonClassName="button button-danger"
rightButtonCallback={this.handleConfirmGoBack}
showHeader={true}
>
<Trans render="p">
Are you sure you want to leave this page? Any data you entered will
be lost.
</Trans>
</Confirm>
</FullScreenModal>
);
}
}
export default withI18n()(FrameworkConfiguration); | the_stack |
import { Component, OnInit, Input } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { UtilityCompanyService } from './UtilityCompany.service';
import 'rxjs/add/operator/toPromise';
//provide associated components
@Component({
selector: 'app-UtilityCompany',
templateUrl: './UtilityCompany.component.html',
styleUrls: ['./UtilityCompany.component.css'],
providers: [UtilityCompanyService]
})
//UtilityCompanyComponent class
export class UtilityCompanyComponent {
//define variables
myForm: FormGroup;
private allUtilityCompanys;
private utilityCompany;
private currentId;
private errorMessage;
private coins;
private energy;
//initialize form variables
utilityID = new FormControl("", Validators.required);
name = new FormControl("", Validators.required);
coinsValue = new FormControl("", Validators.required);
energyValue = new FormControl("", Validators.required);
energyUnits = new FormControl("", Validators.required);
constructor(private serviceUtilityCompany:UtilityCompanyService, fb: FormBuilder) {
//intialize form
this.myForm = fb.group({
utilityID:this.utilityID,
name:this.name,
coinsValue:this.coinsValue,
energyValue:this.energyValue,
energyUnits:this.energyUnits,
});
};
//on page initialize, load all utility companies
ngOnInit(): void {
this.loadAll();
}
//load all Utility Companies and the coins and energy assets associated to it
loadAll(): Promise<any> {
//retrieve all utilityCompanys in the utilityCompanyList array
let utilityCompanyList = [];
//call serviceUtilityCompany to get all utility company objects
return this.serviceUtilityCompany.getAllUtilityCompanys()
.toPromise()
.then((result) => {
this.errorMessage = null;
//append utilityCompanyList with the utility company objects returned
result.forEach(utilityCompany => {
utilityCompanyList.push(utilityCompany);
});
})
.then(() => {
//for each utility company, get the associated coins and energy asset
for (let utilityCompany of utilityCompanyList) {
//get coinsID from the utilityCompany.coins string
var splitted_coinsID = utilityCompany.coins.split("#", 2);
var coinsID = String(splitted_coinsID[1]);
//call serviceUtilityCompany to get coins asset
this.serviceUtilityCompany.getCoins(coinsID)
.toPromise()
.then((result) => {
this.errorMessage = null;
//update utilityCompany
if(result.value){
utilityCompany.coinsValue = result.value;
}
});
//get energyID from the utilityCompany.energy string
var splitted_energyID = utilityCompany.energy.split("#", 2);
var energyID = String(splitted_energyID[1]);
//call serviceUtilityCompany to get energy asset
this.serviceUtilityCompany.getEnergy(energyID)
.toPromise()
.then((result) => {
this.errorMessage = null;
//update utilityCompany
if(result.value){
utilityCompany.energyValue = result.value;
}
if(result.units){
utilityCompany.energyUnits = result.units;
}
});
}
//assign utilityCompanyList to allUtilityCompanys
this.allUtilityCompanys = utilityCompanyList;
});
}
//add Utility Company participant
addUtilityCompany(form: any): Promise<any> {
//create assets for utility company and the utility company on the blockchain network
return this.createAssetsUtility()
.then(() => {
this.errorMessage = null;
this.myForm.setValue({
"utilityID":null,
"name":null,
"coinsValue":null,
"energyValue":null,
"energyUnits":null
});
})
.catch((error) => {
if(error == 'Server error'){
this.errorMessage = "Could not connect to REST server. Please check your configuration details";
}
else if (error == '500 - Internal Server Error') {
this.errorMessage = "Input error";
}
else{
this.errorMessage = error;
}
});
}
//create coins and energy assets associated with the Resident, followed by the Resident
createAssetsUtility(): Promise<any> {
//create coins asset json
this.coins = {
$class: "org.decentralized.energy.network.Coins",
"coinsID":"CO_" + this.utilityID.value,
"value":this.coinsValue.value,
"ownerID":this.utilityID.value,
"ownerEntity":'UtilityCompany'
};
//create energy asset json
this.energy = {
$class: "org.decentralized.energy.network.Energy",
"energyID":"EN_" + this.utilityID.value,
"units":this.energyUnits.value,
"value":this.energyValue.value,
"ownerID":this.utilityID.value,
"ownerEntity":'UtilityCompany'
};
//create utility company participant json
this.utilityCompany = {
$class: "org.decentralized.energy.network.UtilityCompany",
"utilityID":this.utilityID.value,
"name":this.name.value,
"coins":"CO_" + this.utilityID.value,
"energy":"EN_" + this.utilityID.value,
};
//call serviceUtilityCompany to add coins asset, pass created coins asset json as parameter
return this.serviceUtilityCompany.addCoins(this.coins)
.toPromise()
.then(() => {
//call serviceUtilityCompany to add energy asset, pass created energy asset json as parameter
this.serviceUtilityCompany.addEnergy(this.energy)
.toPromise()
.then(() => {
//call serviceUtilityCompany to add utility participant, pass created utility participant json as parameter
this.serviceUtilityCompany.addUtilityCompany(this.utilityCompany)
.toPromise()
.then(() => {
//reload page to display the created utility company
location.reload();
});
});
});
}
//allow update name of Utility Company
updateUtilityCompany(form: any): Promise<any> {
//create json of utility company participant to update name
this.utilityCompany = {
$class: "org.decentralized.energy.network.UtilityCompany",
"name":this.name.value,
"coins": "resource:org.decentralized.energy.network.Coins#CO_" + form.get("utilityID").value,
"energy": "resource:org.decentralized.energy.network.Energy#EN_" + form.get("utilityID").value
};
//call serviceUtilityCompany to update utility company, pass utilityID of which utility company to update as parameter
return this.serviceUtilityCompany.updateUtilityCompany(form.get("utilityID").value,this.utilityCompany)
.toPromise()
.then(() => {
this.errorMessage = null;
})
.catch((error) => {
if(error == 'Server error'){
this.errorMessage = "Could not connect to REST server. Please check your configuration details";
}
else if(error == '404 - Not Found'){
this.errorMessage = "404 - Could not find API route. Please check your available APIs."
}
else{
this.errorMessage = error;
}
});
}
//delete Utility Company and the coins and energy assets associated to it
deleteUtilityCompany(): Promise<any> {
//call serviceUtilityCompany to delete utilty company, pass utilityID as parameter
return this.serviceUtilityCompany.deleteUtilityCompany(this.currentId)
.toPromise()
.then(() => {
this.errorMessage = null;
//call serviceUtilityCompany to delete coins asset, pass coinsID as parameter
this.serviceUtilityCompany.deleteCoins("CO_"+this.currentId)
.toPromise()
.then(() => {
//call serviceUtilityCompany to delete energy asset, pass energyID as parameter
this.serviceUtilityCompany.deleteEnergy("EN_"+this.currentId)
.toPromise()
.then(() => {
console.log("Deleted")
});
});
})
.catch((error) => {
if(error == 'Server error'){
this.errorMessage = "Could not connect to REST server. Please check your configuration details";
}
else if(error == '404 - Not Found'){
this.errorMessage = "404 - Could not find API route. Please check your available APIs."
}
else{
this.errorMessage = error;
}
});
}
//set id
setId(id: any): void{
this.currentId = id;
}
//get form based on utilityID
getForm(id: any): Promise<any>{
//call serviceUtilityCompany to get utility company participant object
return this.serviceUtilityCompany.getUtilityCompany(id)
.toPromise()
.then((result) => {
this.errorMessage = null;
let formObject = {
"utilityID":null,
"name":null,
"coinsValue":null,
"energyValue":null,
"energyUnits":null
};
//update formObject
if(result.utilityID){
formObject.utilityID = result.utilityID;
}else{
formObject.utilityID = null;
}
if(result.name){
formObject.name = result.name;
}else{
formObject.name = null;
}
this.myForm.setValue(formObject);
})
.catch((error) => {
if(error == 'Server error'){
this.errorMessage = "Could not connect to REST server. Please check your configuration details";
}
else if(error == '404 - Not Found'){
this.errorMessage = "404 - Could not find API route. Please check your available APIs."
}
else{
this.errorMessage = error;
}
});
}
//reset form
resetForm(): void{
this.myForm.setValue({
"utilityID":null,
"name":null,
"coinsValue":null,
"energyValue":null,
"energyUnits":null,
});
}
} | the_stack |
import {
GraphHttpClient, HttpClientResponse,
} from '@microsoft/sp-http';
export default class GraphEvalClient {
_context: any;
_graphClient: GraphHttpClient;
_urlToEvaluate: URL;
_isList = false;
_isLibrary = false;
constructor(graphClient: any) {
// use locally stored graphHttpClient
this._graphClient = graphClient;
}
private _getUrlJunks(urlPath: string): string[] {
return urlPath
.toLowerCase() // convert urlPath to lowerstring
.split('\/') // split out all slashes
// Filter all empty values
.filter((junk) => {
if (junk !== '') {
return junk;
}
})
}
/**
* Assume the site collectio on an URL
* @param urlPath URL that should be evaluated
*/
private _getSiteCollectionUrl(urlPath: string): string {
let urlPathElements = this._getUrlJunks(urlPath);
// Use the root site collection
if (urlPathElements[0] !== 'sites') {
return ''
}
// found sub site collection and use only /sites/<your subweb>
if (urlPathElements.length >= 2) {
// assumes we have a /sites/something
return `/${urlPathElements[0]}/${urlPathElements[1]}/`
}
}
/**
* Assume the url on an URL
* @param urlPath URL that should be evaluated
*/
private _getAssumedWeburl(urlPath: string) {
let siteColleciton = this._getSiteCollectionUrl(urlPath),
urlPathElements = this._getUrlJunks(urlPath);
/* Get location if there is for form or lists to identify
docuemnt library or list
*/
let formLocation = urlPathElements.indexOf('forms'),
listLocation = urlPathElements.indexOf('lists'),
sitePages = urlPathElements.indexOf('sitepages');
/* Check if it is a full list url
* otherwise check if it is a list
* otherwise truncate the path for ine level
*/
if (formLocation !== -1) {
this._isLibrary = true;
return `/${urlPathElements.slice(0, formLocation - 1).join('/')}`;
} else if (listLocation !== -1) {
this._isList = true;
return `/${urlPathElements.slice(0, listLocation).join('/')}`;
} else if (sitePages !== -1) {
console.log(urlPathElements.slice(0, sitePages));
return `/${urlPathElements.slice(0, sitePages).join('/')}`;
} else {
// just return path one higher then the final web or list in case no one have entered no view
return `/${urlPathElements.slice(0, urlPathElements.length).join('/')}`;
}
}
/**
* Assume the list or library url based on a path
* @param urlPath URL that should be evaluated
*/
private _getAssumedList(urlPath: string) {
let webUrl = this._getAssumedWeburl(urlPath),
urlPathElements = this._getUrlJunks(urlPath);
// Check if a list should be found otherwise docuemnt library or unspecified
if (this._isList) {
let listIndex = urlPathElements.indexOf('lists');
// +2 for adding /lists/<listname>
return urlPathElements.slice(0, listIndex + 2).join('/');
} else if (this._isLibrary) {
let formIndex = urlPathElements.indexOf('forms');
/*
No additional index needs to be added bcause document libraries already exist
in root folder of Site Collection
*/
return `/${urlPathElements.slice(0, formIndex).join('/')}`;
} if (urlPathElements[urlPathElements.length - 1].indexOf('.apsx')) {
return `/${urlPathElements.slice(0, urlPathElements.length - 1).join('/')}`;
} else {
throw 'Neither list nor document library could be identified';
}
}
/**
* Try to parse the url to a JavaScript Url Object
* @param url
*/
private _evaluateUrl(url: string) {
console.log(url);
try {
return new URL(url)
} catch (Exception) {
throw Exception;
}
}
/**
* Graph query to resturn a site collection or web
* @param hostname
* @param scUrl
*/
private _evaluateWeb(hostname: string, scUrl: string): Promise<any> {
let graphQuery;
if (scUrl !== '' && scUrl.indexOf('sites') !== -1) {
// query just a regular sub site collection
graphQuery = `beta/sites/${hostname}:${scUrl}`;
} else if (scUrl !== '' && scUrl.indexOf('sites') === -1) {
// query just a regular sub site collection
graphQuery = `beta/sites/${hostname}/sites/`;
} else {
// query only the root
graphQuery = `beta/sites/${hostname}`;
}
console.log(graphQuery, scUrl);
return this._graphClient.get(
graphQuery,
GraphHttpClient.configurations.v1
).then(
(response: HttpClientResponse) => {
return response.json();
}
).catch(
(error) => {
throw error;
}
);
}
/**
* Graph query that returns all lists in a specific web
* @param siteId
* @param url
*/
private _evaluateLists(siteId: string, url: string): Promise<any> {
// Transfer result values to the group variable
// TODO: Check until you find the final subsite
const NO_RESULT = 'No document library could be found under the give path';
let pathToFileQuery = `beta/sites/${siteId}/Lists`;
return this._graphClient.get(
pathToFileQuery,
GraphHttpClient.configurations.v1
).then(
(response) => {
return response.json();
}
)
}
/**
* Evaluate if site collection exists and return it if found
* @param url
*/
public EvaluateSiteCollection(url: string): Promise<any> {
let scUrl;
// General url evaluation
try {
this._urlToEvaluate = this._evaluateUrl(url);
} catch (Exception) {
throw Exception;
}
// Try to make site collection url
try {
scUrl = this._getSiteCollectionUrl(this._urlToEvaluate.pathname);
} catch (Exception) {
throw Exception
}
// if building a site collection url worked well
if (scUrl !== null && scUrl !== undefined) {
return this._evaluateWeb(this._urlToEvaluate.hostname, scUrl)
.then(
(response) => {
return response;
}
)
.catch(
(error) => {
throw `Error retrieving Site Collection at ${scUrl} - ${error}`;
}
)
}
}
/**
* Evaluate a web by URL and returns the web object
* @param url
*/
public EvaluateWeb(url: string): Promise<any> {
let scUrl;
// General url evaluation
try {
this._urlToEvaluate = this._evaluateUrl(url);
} catch (Exception) {
throw Exception;
}
// Try to make web url
try {
scUrl = this._getAssumedWeburl(this._urlToEvaluate.pathname);
} catch (Exception) {
console.log('Error: Identify Site Collection URL');
throw Exception
}
if (scUrl !== null && scUrl !== undefined) {
return this._evaluateWeb(this._urlToEvaluate.hostname, scUrl)
.then(
(response) => {
return response;
}
)
.catch(
(error) => {
throw `Error retrieving Site Collection at ${scUrl} - ${error}`;
}
)
}
}
/**
* Evaluate if web and a specific list exists in the web
* @param url
* @param webid
*/
public EvaluateList(url: string): Promise<any> {
let webUrl,
listUrl;
// General url evaluation
try {
this._urlToEvaluate = this._evaluateUrl(url);
} catch (Exception) {
throw Exception;
}
// Try to make web url url
try {
webUrl = this._getAssumedWeburl(this._urlToEvaluate.pathname);
} catch (Exception) {
throw Exception
}
// try to find a list or document library url
try {
listUrl = this._getAssumedList(this._urlToEvaluate.pathname);
} catch (Exception) {
throw Exception
}
// If list and web are ok proceed
if (webUrl !== null && webUrl !== undefined &&
listUrl !== null && listUrl !== undefined) {
/**
* Evaluate web because the graph ID is needed to evaluate a list
*/
return this._evaluateWeb(this._urlToEvaluate.hostname, webUrl)
.then(
(response) => {
let webIdResults,
webId;
// just in case multiple items got returned by the graph
if (response.value !== undefined) {
// filter the best match
webIdResults = response.value.filter((obj) => {
return obj.webUrl.toLowerCase().indexOf(webUrl) !== -1;
});
// return first found id
webId = webIdResults[0].id;
} else {
// if only single item was returned
webId = response.id;
}
return this._evaluateLists(webId, listUrl)
.then(
(response) => {
/**
* Graph always returns all lists and docuemnt libraries from site collection
* This filters out to return only the searched List or library instead of all
* In case none could be found only a empty array will get returned
*/
const suiteableLists = response.value.filter((obj) => {
return obj.webUrl.toLowerCase().indexOf(listUrl) !== -1;
});
response.value = suiteableLists;
return response;
}
)
.catch(
(error) => {
throw `List cannot be found or evaluated - ${error}`;
}
)
}
)
.catch(
(error) => {
throw `Error retrieving Site Collection at ${webUrl} - ${error}`;
}
)
}
}
} | the_stack |
import React, { useEffect, useRef, useState } from 'react'
import { makeStyles } from '@material-ui/core/styles'
import OutsidePage from 'src/components/blocks/OutsidePage'
import { useDispatch } from 'react-redux'
import { setSettings } from 'src/store/actions/settings'
import { useSelector } from 'src/hooks'
import {
BACKGROUND_COLORS_DEFAULT,
BACKGROUND_COLORS_PAPER,
MIN_WIDTH,
PaletteType,
THEMES,
THEME_NAMES,
THEME_PRIMARY_COLORS,
THEME_TEXT_COLORS,
THEME_TYPES,
} from 'src/config/constants'
import {
Radio,
Typography,
Grid,
useTheme,
GridSize,
ButtonBase,
FormControl,
darken,
lighten,
ListItem,
ListItemText,
Switch,
fade,
Divider,
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
TextField,
FormControlLabel,
RadioGroup,
} from '@material-ui/core'
import AddCircleRoundedIcon from '@material-ui/icons/AddCircleRounded'
import getInvertedContrastPaperColor from 'src/utils/getInvertedContrastPaperColor'
import isMobile from 'is-mobile'
import isDarkTheme from 'src/utils/isDarkTheme'
import { useHistory } from 'react-router'
import { CustomTheme } from 'src/interfaces/UserSettings'
import { EditRounded } from '@material-ui/icons'
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
flexDirection: 'column',
width: '100%',
},
section: {
backgroundColor: theme.palette.background.paper,
marginTop: 12,
paddingBottom: theme.spacing(1.5),
[theme.breakpoints.up(MIN_WIDTH)]: {
borderRadius: 8,
},
},
sectionHeader: {
fontSize: 13,
color: theme.palette.text.hint,
textTransform: 'uppercase',
fontWeight: 500,
lineHeight: 'normal',
fontFamily: 'Google Sans',
marginBottom: theme.spacing(1.5),
paddingBottom: 0,
padding: theme.spacing(1.5, 2),
},
singleRowGrid: {
display: 'flex',
width: '100%',
[theme.breakpoints.down('xs')]: {
display: 'none',
},
},
oneByTwoGrid: {
display: 'none',
width: '100%',
[theme.breakpoints.down('xs')]: {
display: 'flex',
},
},
previewContainer: {
position: 'relative',
background: lighten(
theme.palette.background.default,
isDarkTheme(theme) ? 0.01 : 0.3
),
[theme.breakpoints.up(MIN_WIDTH)]: {
border: '1px solid ' + fade(theme.palette.divider, 0.03),
borderRadius: 8,
marginTop: theme.spacing(1.5),
},
},
leftItem: {
[theme.breakpoints.up(MIN_WIDTH)]: {
borderBottomLeftRadius: 8,
},
},
rightItem: {
[theme.breakpoints.up(MIN_WIDTH)]: {
borderBottomRightRadius: 8,
},
},
themeCardsContainer: {
whiteSpace: 'nowrap',
flexDirection: 'row',
alignItems: 'baseline',
display: 'flex',
flexWrap: 'nowrap',
// Promote the list into his own layer on Chrome. This cost memory but helps keeping high FPS.
transform: 'translateZ(0)',
overflowX: 'auto',
overflowY: 'hidden',
paddingTop: 1,
// Do not change the scrollbar on mobile due to design flaws
// If the -webkit-scrollbar is empty, any other scrollbar style will not be applied.
'&::-webkit-scrollbar': !isMobile() && {
background: isDarkTheme(theme)
? lighten(theme.palette.background.default, 0.03)
: theme.palette.background.paper,
border: '1px solid ' + darken(theme.palette.background.paper, 0.05),
borderRadius: 4,
height: 12,
},
'&::-webkit-scrollbar-thumb': {
minHeight: 12,
borderRadius: 4,
background: isDarkTheme(theme)
? lighten(theme.palette.background.paper, 0.08)
: darken(theme.palette.background.paper, 0.08),
transition: '0.1s',
'&:hover': {
background: isDarkTheme(theme)
? lighten(theme.palette.background.paper, 0.1)
: darken(theme.palette.background.paper, 0.1),
},
'&:active': {
background: isDarkTheme(theme)
? lighten(theme.palette.background.paper, 0.2)
: darken(theme.palette.background.paper, 0.2),
},
},
},
newThemeButton: {
marginRight: theme.spacing(2),
display: 'inline-flex',
marginLeft: theme.spacing(2),
justifyContent: 'center',
height: 128,
width: 96,
borderRadius: 12,
alignItems: 'center',
flexDirection: 'column',
background: getInvertedContrastPaperColor(theme),
boxShadow: '0 0 0 1px ' + theme.palette.divider,
},
newThemeButtonText: {
fontSize: 14,
marginTop: theme.spacing(0.5),
},
dividerHolder: {
display: 'inline-flex',
flexDirection: 'column',
marginLeft: theme.spacing(2),
alignItems: 'center',
justifyContent: 'center',
},
divider: {
position: 'absolute',
height: 96,
},
editThemeButton: {
width: '100%',
justifyContent: 'start',
padding: theme.spacing(1.5, 2),
},
editThemeIcon: {
marginRight: theme.spacing(2),
},
editThemeText: {
fontWeight: 500,
fontFamily: 'Google Sans',
},
}))
export const usePaletteGridItemStyles = makeStyles((theme) => ({
gridItem: {
position: 'relative',
alignItems: 'baseline',
justifyContent: 'start',
width: '100%',
'&::before': {
content: '""',
paddingBottom: (p: number) => p * 100 + '%',
},
},
floatText: {
position: 'absolute',
marginTop: 4,
marginLeft: 8,
fontSize: 14,
fontWeight: 700,
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden',
maxWidth: 'calc(100% - ' + theme.spacing(2) + 'px)',
},
floatSubtext: {
position: 'absolute',
marginTop: 22,
marginLeft: 8,
fontSize: 14,
fontWeight: 500,
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden',
opacity: 0.8,
maxWidth: 'calc(100% - ' + theme.spacing(2) + 'px)',
},
paletteSymbolContainer: {
height: 30,
left: '50%',
position: 'absolute',
top: '50%',
width: 30,
transform: 'translate(-50%, -50%)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: 16,
fontWeight: 700,
background: theme.palette.getContrastText(theme.palette.primary.main),
color: theme.palette.primary.main,
borderRadius: '50%',
},
}))
const useThemeCardStyles = makeStyles((theme) => ({
root: {
display: 'inline-flex',
flexDirection: 'column',
marginLeft: theme.spacing(2),
alignItems: 'center',
justifyContent: 'center',
position: 'relative',
'&:last-child': {
paddingRight: theme.spacing(2),
},
},
border: {
boxShadow: '0 0 0 1px ' + theme.palette.divider,
},
box: {
height: 128,
width: 96,
borderRadius: 12,
alignItems: 'baseline',
},
item: {
height: '50%',
},
type: {
fontSize: 14,
marginTop: theme.spacing(0.5),
maxWidth: 100,
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
},
radioHolder: {
height: '50%',
width: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
radio: {
color: ({ color }: { color: string }) => color,
},
radioChecked: {
color: theme.palette.primary.main,
},
}))
const makeCustomThemeFromThemeType = (type: PaletteType): CustomTheme => ({
name: THEME_NAMES[type],
type,
palette: {
type: THEME_TYPES[type],
primary: THEME_PRIMARY_COLORS[type],
background: {
paper: BACKGROUND_COLORS_PAPER[type],
default: BACKGROUND_COLORS_DEFAULT[type],
},
text: THEME_TEXT_COLORS[type],
},
})
const ThemeCard = ({ theme }: { theme: CustomTheme }) => {
const paper = theme.palette.background.paper
const defaultColor = theme.palette.background.default
const primaryColor = theme.palette.primary.main
const textColor = theme.palette.text.primary
const dispatch = useDispatch()
const classes = useThemeCardStyles({ color: textColor })
const themeType = useSelector((state) => state.settings.themeType)
const isCurrent = themeType === theme.type
const ref = useRef<HTMLDivElement>()
const changeTheme: React.MouseEventHandler<HTMLButtonElement> = (_event) => {
if (!isCurrent) dispatch(setSettings({ themeType: theme.type }))
}
// Scroll to the element on page first load
useEffect(() => {
if (ref.current && isCurrent) {
ref.current.scrollIntoView({
behavior: 'auto',
block: 'end',
inline: 'center',
})
}
}, [])
return (
<div className={classes.root} ref={ref}>
<Grid
component={ButtonBase}
onClick={changeTheme}
container
justify="center"
className={`${classes.box} ${isCurrent ? classes.border : ''}`}
style={{ background: paper }}
>
<Grid
item
xs={6}
style={{ background: primaryColor, borderTopLeftRadius: 12 }}
className={classes.item}
/>
<Grid
item
xs={6}
style={{ background: defaultColor, borderTopRightRadius: 12 }}
className={classes.item}
/>
<div className={classes.radioHolder}>
<Radio
disableRipple
value={theme.type}
color="primary"
checked={isCurrent}
classes={{
colorPrimary: classes.radio,
}}
/>
</div>
</Grid>
<Typography className={classes.type}>{theme.name}</Typography>
</div>
)
}
const PaletteGridItem = ({
width,
color,
text,
withSymbol,
height = 1,
className = '',
}: {
width: number
color: string
text: string
withSymbol?: boolean
height?: number
className?: string
}) => {
const theme = useTheme()
const classes = usePaletteGridItemStyles(height)
return (
<Grid
item
component={ButtonBase}
xs={width as boolean | GridSize}
className={classes.gridItem + ' ' + className}
style={{
background: color,
color: theme.palette.getContrastText(color),
}}
>
<Typography className={classes.floatText}>{text}</Typography>
<Typography className={classes.floatSubtext}>{color}</Typography>
{withSymbol && <span className={classes.paletteSymbolContainer}>P</span>}
</Grid>
)
}
const Switcher = ({
onClick: onSwitcherClick = null,
primary,
secondary,
checked = false,
}) => {
const [isChecked, setChecked] = useState(checked)
const onClick = () => {
setChecked((prev) => !prev)
onSwitcherClick()
}
return (
<ListItem button onClick={onClick}>
<ListItemText primary={primary} secondary={secondary} />
<Switch disableRipple checked={isChecked} color="primary" />
</ListItem>
)
}
export const OneByTwoGrid = ({ component: Item = PaletteGridItem }) => {
const classes = useStyles()
const theme = useTheme()
return (
<div className={classes.oneByTwoGrid}>
<Grid item xs={6}>
<Grid container direction="column">
<Item
width={12}
color={theme.palette.primary.main}
text="main"
height={0.5}
withSymbol
/>
<Grid container direction="row">
<Item
width={6}
height={1}
color={theme.palette.primary.light}
text="light"
/>
<Item
width={6}
height={1}
color={theme.palette.primary.dark}
text="dark"
/>
</Grid>
</Grid>
</Grid>
<Grid item xs={6}>
<Grid container direction="column">
<Item
width={12}
height={0.5}
color={theme.palette.background.paper}
text="paper"
/>
<Grid container direction="row">
<Item
width={6}
height={1}
color={theme.palette.background.default}
text="default"
/>
<Item
width={6}
height={1}
color={theme.palette.text.primary}
text="text"
/>
</Grid>
</Grid>
</Grid>
</div>
)
}
export const SingleRowGrid = ({ component: Item = PaletteGridItem }) => {
const theme = useTheme()
const classes = useStyles()
return (
<Grid
item
xs={12}
container
direction="row"
className={classes.singleRowGrid}
>
<Item
width={2}
height={1}
color={theme.palette.primary.light}
text="light"
className={classes.leftItem}
/>
<Item
width={2}
height={1}
color={theme.palette.primary.main}
text="main"
withSymbol
/>
<Item
width={2}
height={1}
color={theme.palette.primary.dark}
text="dark"
/>
<Item
width={2}
height={1}
color={theme.palette.background.default}
text="default"
/>
<Item
width={2}
height={1}
color={theme.palette.background.paper}
text="paper"
/>
<Item
width={2}
height={1}
color={theme.palette.text.primary}
text="text"
className={classes.rightItem}
/>
</Grid>
)
}
interface AddDialogProps {
isOpen: boolean
setOpen: React.Dispatch<React.SetStateAction<boolean>>
onSubmit: (login: string) => void
placeholder: string
title: string
}
const AddDialog: React.FC<AddDialogProps> = ({
isOpen,
setOpen,
onSubmit,
placeholder,
title,
}) => {
const textInputRef = useRef<HTMLInputElement>()
const handleClose = () => setOpen(false)
const handleSubmit = () => {
if (textInputRef.current) {
onSubmit(textInputRef.current.value)
setOpen(false)
}
}
return (
<Dialog fullWidth maxWidth="xs" open={isOpen} onClose={handleClose}>
<DialogTitle style={{ paddingBottom: 0 }} id="add-dialog-title">
{title}
</DialogTitle>
<DialogContent>
<TextField
inputRef={textInputRef}
autoFocus
margin="dense"
name="title"
label="Логин"
placeholder={placeholder}
type="text"
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={handleClose} color="default">
Отмена
</Button>
<Button
color="primary"
variant="contained"
disableElevation
onClick={handleSubmit}
>
Добавить
</Button>
</DialogActions>
</Dialog>
)
}
export interface ThemeSelectDialogProps {
classes?: Record<'paper', string>
id: string
keepMounted?: boolean
value: string
open: boolean
onClose: (value?: string) => void
}
const ThemeSelectDialog = (props: ThemeSelectDialogProps) => {
const { onClose, value: valueProp, open, ...other } = props
const [value, setValue] = React.useState(valueProp)
const radioGroupRef = React.useRef<HTMLElement>(null)
const customThemes = useSelector((store) => store.settings.customThemes)
const options = THEMES.map((e) => makeCustomThemeFromThemeType(e)).concat(
customThemes
)
useEffect(() => {
if (!open) {
setValue(valueProp)
}
}, [valueProp, open])
const handleEntering = () => {
if (radioGroupRef.current != null) {
radioGroupRef.current.focus()
}
}
const handleCancel = () => onClose()
const handleOk = () => onClose(value)
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setValue((event.target as HTMLInputElement).value)
}
return (
<Dialog
disableBackdropClick
disableEscapeKeyDown
maxWidth="xs"
onEntering={handleEntering}
aria-labelledby="theme-select-dialog-title"
open={open}
{...other}
>
<DialogTitle id="theme-select-dialog-title">Выбор темы</DialogTitle>
<DialogContent dividers>
<RadioGroup
ref={radioGroupRef}
aria-label="theme-select"
name="theme-select"
value={value}
onChange={handleChange}
>
{options.map((option) => (
<FormControlLabel
value={option.type}
key={option.type}
control={<Radio color="primary" />}
label={option.name}
/>
))}
</RadioGroup>
</DialogContent>
<DialogActions>
<Button autoFocus onClick={handleCancel} color="primary">
Отмена
</Button>
<Button onClick={handleOk} color="primary">
Ok
</Button>
</DialogActions>
</Dialog>
)
}
const Appearance = () => {
const classes = useStyles()
const history = useHistory()
const theme = useTheme()
const dispatch = useDispatch()
const customThemes = useSelector((store) => store.settings.customThemes)
const autoChangeTheme = useSelector((store) => store.settings.autoChangeTheme)
const preferredLightTheme = useSelector(
(store) => store.settings.preferredLightTheme
)
const preferredDarkTheme = useSelector(
(store) => store.settings.preferredDarkTheme
)
const themeType = useSelector((state) => state.settings.themeType)
const isCustomThemeChosen = customThemes.some((e) => e.type === themeType)
const preferredLightThemeName =
preferredLightTheme in THEME_NAMES
? THEME_NAMES[preferredLightTheme]
: customThemes.find((e) => e.type === preferredLightTheme)?.name
const preferredDarkThemeName =
preferredDarkTheme in THEME_NAMES
? THEME_NAMES[preferredDarkTheme]
: customThemes.find((e) => e.type === preferredDarkTheme)?.name
const [
isPreferredLightThemeDialogOpen,
setPreferredLightThemeDialogOpen,
] = useState(false)
const [
isPreferredDarkThemeDialogOpen,
setPreferredDarkThemeDialogOpen,
] = useState(false)
const handlePreferredLightThemeDialogClose = (value?: string) => {
setPreferredLightThemeDialogOpen(false)
value &&
dispatch(
setSettings({
preferredLightTheme: value,
})
)
}
const handlePreferredDarkThemeDialogClose = (value?: string) => {
setPreferredDarkThemeDialogOpen(false)
value &&
dispatch(
setSettings({
preferredDarkTheme: value,
})
)
}
return (
<OutsidePage
headerText={'Внешний вид'}
disableShrinking
backgroundColor={theme.palette.background.paper}
>
<div className={classes.root}>
<Grid container className={classes.previewContainer} direction="row">
<Typography className={classes.sectionHeader}>Палитра</Typography>
<SingleRowGrid />
<OneByTwoGrid />
</Grid>
<div
className={classes.section}
style={{ paddingBottom: isCustomThemeChosen ? 0 : null }}
>
<Typography className={classes.sectionHeader}>Темы</Typography>
<FormControl
component="fieldset"
aria-label="theme-type"
name="theme-type"
className={classes.themeCardsContainer}
>
{THEMES.map((e, i) => (
<ThemeCard theme={makeCustomThemeFromThemeType(e)} key={i} />
))}
<div className={classes.dividerHolder}>
<Divider className={classes.divider} orientation="vertical" />
</div>
{customThemes.map((e, i) => (
<ThemeCard theme={e} key={i} />
))}
<div style={{ display: 'inline-flex' }}>
<ButtonBase
className={classes.newThemeButton}
onClick={() =>
history.push('/settings/appearance/new-theme', {
from: history.location.pathname,
})
}
>
<AddCircleRoundedIcon />
<Typography className={classes.newThemeButtonText}>
Создать
</Typography>
</ButtonBase>
</div>
</FormControl>
{isCustomThemeChosen && (
<ButtonBase
className={classes.editThemeButton}
onClick={() =>
history.push('/settings/appearance/edit-theme/' + themeType, {
from: history.location.pathname,
})
}
>
<EditRounded className={classes.editThemeIcon} />
<Typography className={classes.editThemeText}>
Изменить тему
</Typography>
</ButtonBase>
)}
</div>
<div className={classes.section}>
<Typography
className={classes.sectionHeader}
style={{ marginBottom: 0 }}
>
Настройки
</Typography>
<Switcher
primary={'Использовать системную тему'}
secondary={
'Внешний вид приложения будет меняться автоматически при изменении темы на устройстве'
}
checked={autoChangeTheme}
onClick={() => {
dispatch(
setSettings({
autoChangeTheme: !autoChangeTheme,
})
)
}}
/>
<ListItem
button
disabled={!autoChangeTheme}
onClick={() => setPreferredLightThemeDialogOpen(true)}
>
<ListItemText
primary={'Предпочитаемая светлая тема'}
secondary={preferredLightThemeName}
/>
</ListItem>
<ListItem
button
disabled={!autoChangeTheme}
onClick={() => setPreferredDarkThemeDialogOpen(true)}
>
<ListItemText
primary={'Предпочитаемая темная тема'}
secondary={preferredDarkThemeName}
/>
</ListItem>
<ThemeSelectDialog
keepMounted={false}
id="preferred-light-theme-select-dialog"
open={isPreferredLightThemeDialogOpen}
onClose={handlePreferredLightThemeDialogClose}
value={preferredLightTheme}
/>
<ThemeSelectDialog
keepMounted={false}
id="preferred-dark-theme-select-dialog"
open={isPreferredDarkThemeDialogOpen}
onClose={handlePreferredDarkThemeDialogClose}
value={preferredDarkTheme}
/>
</div>
</div>
</OutsidePage>
)
}
export default React.memo(Appearance) | the_stack |
import { AWSError } from "aws-sdk"
import {
AuthenticationClient,
translate
} from "clients/authentication"
import { chance } from "_/helpers"
import {
mockAuthenticateRequestWithCredentials,
mockAuthenticateRequestWithToken,
mockRegisterRequest,
mockResetRequest
} from "_/mocks/common"
import {
mockCognitoAdminGetUserWithError,
mockCognitoAdminGetUserWithResult,
mockCognitoInitiateAuthWithChallenge,
mockCognitoInitiateAuthWithCredentials,
mockCognitoInitiateAuthWithError,
mockCognitoInitiateAuthWithToken,
mockCognitoSignUpWithError,
mockCognitoSignUpWithSuccess,
restoreCognitoAdminGetUser,
restoreCognitoInitiateAuth,
restoreCognitoSignUp
} from "_/mocks/vendor/aws-sdk"
import {
mockVerificationCode,
mockVerificationIssueWithError,
mockVerificationIssueWithResult
} from "_/mocks/verification"
/* ----------------------------------------------------------------------------
* Tests
* ------------------------------------------------------------------------- */
/* Authentication client */
describe("clients/authentication", () => {
/* Error translation */
describe("translate", () => {
/* Test: should translate empty username and password error */
it("should translate empty username and password error", () => {
expect(translate({
code: "InvalidParameterException",
message: chance.string()
} as AWSError))
.toEqual({
code: "TypeError",
message: "Invalid request"
} as AWSError)
})
/* Test: should translate invalid username error */
it("should translate invalid username error", () => {
expect(translate({
code: "UserNotFoundException",
message: chance.string()
} as AWSError))
.toEqual({
code: "NotAuthorizedException",
message: "Incorrect username or password"
} as AWSError)
})
/* Test: should pass-through all other errors */
it("should pass-through all other errors", () => {
const message = chance.string()
const err = { code: chance.string(), message } as AWSError
expect(translate(err)).toBe(err)
})
})
/* AuthenticationClient */
describe("AuthenticationClient", () => {
/* #register */
describe("#register", () => {
/* Registration request and verification code */
const { email, password } = mockRegisterRequest()
const code = mockVerificationCode()
/* Restore AWS mocks */
afterEach(() => {
restoreCognitoSignUp()
})
/* Test: should resolve with verification code */
it("should resolve with verification code", async () => {
mockCognitoSignUpWithSuccess()
mockVerificationIssueWithResult(code)
const auth = new AuthenticationClient()
expect(await auth.register(email, password))
.toEqual(code)
})
/* Test: should initialize username to uuid */
it("should initialize username to uuid", async () => {
const signUpMock = mockCognitoSignUpWithSuccess()
mockVerificationIssueWithResult()
const auth = new AuthenticationClient()
await auth.register(email, password)
expect(signUpMock).toHaveBeenCalledWith(
jasmine.objectContaining({
Username: jasmine.stringMatching(
/^[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12}$/
)
}))
})
/* Test: should pass provided password */
it("should pass provided password", async () => {
const signUpMock = mockCognitoSignUpWithSuccess()
mockVerificationIssueWithResult()
const auth = new AuthenticationClient()
await auth.register(email, password)
expect(signUpMock).toHaveBeenCalledWith(
jasmine.objectContaining({
Password: password
}))
})
/* Test: should pass provided email address */
it("should pass provided email address", async () => {
const signUpMock = mockCognitoSignUpWithSuccess()
mockVerificationIssueWithResult()
const auth = new AuthenticationClient()
await auth.register(email, password)
expect(signUpMock).toHaveBeenCalledWith(
jasmine.objectContaining({
UserAttributes: jasmine.arrayContaining([
{
Name: "email",
Value: email
}
])
}))
})
/* Test: should reject on invalid email address */
it("should reject on invalid email address", async done => {
mockCognitoSignUpWithSuccess()
mockVerificationIssueWithResult()
try {
const auth = new AuthenticationClient()
await auth.register(chance.string(), password)
done.fail()
} catch (err) {
expect(err).toEqual(new Error("Invalid email address"))
done()
}
})
/* Test: should reject on verification error */
it("should reject on verification error", async done => {
const errMock = new Error()
mockCognitoSignUpWithSuccess()
const issueMock = mockVerificationIssueWithError(errMock)
try {
const auth = new AuthenticationClient()
await auth.register(email, password)
done.fail()
} catch (err) {
expect(issueMock).toHaveBeenCalled()
expect(err).toBe(errMock)
done()
}
})
/* Test: should reject on AWS Cognito error */
it("should reject on AWS Cognito error", async done => {
const errMock = new Error()
const signUpMock = mockCognitoSignUpWithError(errMock)
mockVerificationIssueWithResult()
try {
const auth = new AuthenticationClient()
await auth.register(email, password)
done.fail()
} catch (err) {
expect(signUpMock).toHaveBeenCalled()
expect(err).toBe(errMock)
done()
}
})
})
/* #authenticateWithCredentials */
describe("#authenticateWithCredentials", () => {
/* Authentication request */
const { username, password } = mockAuthenticateRequestWithCredentials()
/* Restore AWS mocks */
afterEach(() => {
restoreCognitoInitiateAuth()
})
/* Test: should resolve with identity token */
it("should resolve with identity token", async () => {
mockCognitoInitiateAuthWithCredentials()
const auth = new AuthenticationClient()
const { id } =
await auth.authenticateWithCredentials(username, password)
expect(id.token).toEqual(jasmine.any(String))
expect(id.expires)
.toBeGreaterThan(Date.now() + 1000 * 59 * 60)
})
/* Test: should resolve with access token */
it("should resolve with access token", async () => {
mockCognitoInitiateAuthWithCredentials()
const auth = new AuthenticationClient()
const { access } =
await auth.authenticateWithCredentials(username, password)
expect(access.token).toEqual(jasmine.any(String))
expect(access.expires)
.toBeGreaterThan(Date.now() + 1000 * 59 * 60)
})
/* Test: should resolve with refresh token */
it("should resolve with refresh token", async () => {
mockCognitoInitiateAuthWithCredentials()
const auth = new AuthenticationClient()
const { refresh } =
await auth.authenticateWithCredentials(username, password)
expect(refresh).toBeDefined()
expect(refresh!.token).toEqual(jasmine.any(String))
expect(refresh!.expires)
.toBeGreaterThan(Date.now() + 1000 * 59 * 60 * 24 * 30)
})
/* Test: should pass provided credentials */
it("should pass provided credentials", async () => {
const initiateAuthMock = mockCognitoInitiateAuthWithCredentials()
const auth = new AuthenticationClient()
await auth.authenticateWithCredentials(username, password)
expect(initiateAuthMock).toHaveBeenCalledWith(
jasmine.objectContaining({
AuthParameters: {
USERNAME: username,
PASSWORD: password
}
}))
})
/* Test: should reject on pending challenge */
it("should reject on pending challenge", async done => {
const challenge = chance.string()
const initiateAuthMock =
mockCognitoInitiateAuthWithChallenge(challenge)
try {
const auth = new AuthenticationClient()
await auth.authenticateWithCredentials(username, password)
done.fail()
} catch (err) {
expect(initiateAuthMock).toHaveBeenCalled()
expect(err).toEqual(
new Error(`Invalid authentication: challenge "${challenge}"`))
done()
}
})
/* Test: should reject on AWS Cognito error */
it("should reject on AWS Cognito error", async done => {
const errMock = new Error()
const initiateAuthMock =
mockCognitoInitiateAuthWithError(errMock)
try {
const auth = new AuthenticationClient()
await auth.authenticateWithCredentials(username, password)
done.fail()
} catch (err) {
expect(initiateAuthMock).toHaveBeenCalled()
expect(err).toBe(errMock)
done()
}
})
})
/* #authenticateWithToken */
describe("#authenticateWithToken", () => {
/* Authentication request */
const { token } = mockAuthenticateRequestWithToken()
/* Restore AWS mocks */
afterEach(() => {
restoreCognitoInitiateAuth()
})
/* Test: should resolve with identity token */
it("should resolve with identity token", async () => {
mockCognitoInitiateAuthWithToken()
const auth = new AuthenticationClient()
const { id } = await auth.authenticateWithToken(token)
expect(id.token).toEqual(jasmine.any(String))
expect(id.expires)
.toBeGreaterThan(Date.now() + 1000 * 59 * 60)
})
/* Test: should resolve with access token */
it("should resolve with access token", async () => {
mockCognitoInitiateAuthWithToken()
const auth = new AuthenticationClient()
const { access } = await auth.authenticateWithToken(token)
expect(access.token).toEqual(jasmine.any(String))
expect(access.expires)
.toBeGreaterThan(Date.now() + 1000 * 59 * 60)
})
/* Test: should resolve with refresh token */
it("should resolve without refresh token", async () => {
mockCognitoInitiateAuthWithToken()
const auth = new AuthenticationClient()
const { refresh } = await auth.authenticateWithToken(token)
expect(refresh).toBeUndefined()
})
/* Test: should pass provided refresh token */
it("should pass provided refresh token", async () => {
const initiateAuthMock = mockCognitoInitiateAuthWithToken()
const auth = new AuthenticationClient()
await auth.authenticateWithToken(token)
expect(initiateAuthMock).toHaveBeenCalledWith(
jasmine.objectContaining({
AuthParameters: {
REFRESH_TOKEN: token
}
}))
})
/* Test: should reject on pending challenge */
it("should reject on pending challenge", async done => {
const challenge = chance.string()
const initiateAuthMock =
mockCognitoInitiateAuthWithChallenge(challenge)
try {
const auth = new AuthenticationClient()
await auth.authenticateWithToken(token)
done.fail()
} catch (err) {
expect(initiateAuthMock).toHaveBeenCalled()
expect(err).toEqual(
new Error(`Invalid authentication: challenge "${challenge}"`))
done()
}
})
/* Test: should reject on AWS Cognito error */
it("should reject on AWS Cognito error", async done => {
const errMock = new Error()
const initiateAuthMock =
mockCognitoInitiateAuthWithError(errMock)
try {
const auth = new AuthenticationClient()
await auth.authenticateWithToken(token)
done.fail()
} catch (err) {
expect(initiateAuthMock).toHaveBeenCalled()
expect(err).toBe(errMock)
done()
}
})
})
/* #forgotPassword */
describe("#forgotPassword", () => {
/* Reset requests and verification code */
const { username } = mockResetRequest()
const code = mockVerificationCode()
/* Restore AWS mocks */
afterEach(() => {
restoreCognitoAdminGetUser()
})
/* Test: should resolve with verification code */
it("should resolve with verification code", async () => {
mockCognitoAdminGetUserWithResult()
mockVerificationIssueWithResult(code)
const auth = new AuthenticationClient()
expect(await auth.forgotPassword(username))
.toEqual(code)
})
/* Test: should retrieve user */
it("should retrieve user", async () => {
const adminGetUserMock = mockCognitoAdminGetUserWithResult()
mockVerificationIssueWithResult(code)
const auth = new AuthenticationClient()
await auth.forgotPassword(username)
expect(adminGetUserMock).toHaveBeenCalledWith(
jasmine.objectContaining({
Username: username
}))
})
/* Test: should issue verification code */
it("should issue verification code", async () => {
mockCognitoAdminGetUserWithResult()
const issueMock = mockVerificationIssueWithResult(code)
const auth = new AuthenticationClient()
await auth.forgotPassword(username)
expect(issueMock)
.toHaveBeenCalledWith("reset", jasmine.any(String))
})
/* Test: should reject on AWS Cognito error */
it("should reject on AWS Cognito error", async done => {
const errMock = new Error()
const adminGetUserMock = mockCognitoAdminGetUserWithError(errMock)
mockVerificationIssueWithResult()
try {
const auth = new AuthenticationClient()
await auth.forgotPassword(username)
done.fail()
} catch (err) {
expect(adminGetUserMock).toHaveBeenCalled()
expect(err).toBe(errMock)
done()
}
})
/* Test: should reject on verification error */
it("should reject on verification error", async done => {
const errMock = new Error()
mockCognitoAdminGetUserWithResult()
const issueMock = mockVerificationIssueWithError(errMock)
try {
const auth = new AuthenticationClient()
await auth.forgotPassword(username)
done.fail()
} catch (err) {
expect(issueMock).toHaveBeenCalled()
expect(err).toBe(errMock)
done()
}
})
})
})
}) | the_stack |
import Component from '../foundation/core/Component';
import EntityRepository from '../foundation/core/EntityRepository';
import {WellKnownComponentTIDs} from '../foundation/components/WellKnownComponentTIDs';
import {ProcessStage} from '../foundation/definitions/ProcessStage';
import Matrix44 from '../foundation/math/Matrix44';
import CameraComponent from '../foundation/components/CameraComponent';
import ComponentRepository from '../foundation/core/ComponentRepository';
import WebGLResourceRepository from '../webgl/WebGLResourceRepository';
import SceneGraphComponent from '../foundation/components/SceneGraphComponent';
import ModuleManager from '../foundation/system/ModuleManager';
import {ComponentTID, EntityUID, ComponentSID} from '../types/CommonTypes';
import {IMatrix44} from '../foundation/math/IMatrix';
declare let window: any;
declare let _SPARK_Data_Delete: Function;
declare let _SPARK_Instance_Create: Function;
declare let _SPARK_Draw: Function;
declare let _SPARK_Instance_Play: Function;
declare let _SPARK_Instance_Stop: Function;
declare let _SPARK_Instance_Pause: Function;
declare let _SPARK_Instance_IsPlaying: Function;
declare let _SPARK_Instance_KickTrigger: Function;
declare let _SPARK_InitializeFor3D: Function;
declare let _SPARK_Uninitialize: Function;
declare let _SPARK_SetMatrix: Function;
declare let _SPARK_Instance_SetTransformFor3D: Function;
declare let _SPARK_Update: Function;
declare let _SPARK_DrawAll: Function;
declare let _SPARK_DrawDebugInfo: Function;
export default class SparkGearComponent extends Component {
public url?: string;
private __hSPFXInst: any;
private static __isInitialized = false;
private __sceneGraphComponent?: SceneGraphComponent;
private static SPFX_WebGLResourceRepository: WebGLResourceRepository;
private static SPFX_TempVAO: any;
private static SPFX_CurrentVAO: any;
private static SPFX_UsingVAO: any;
private static SPFX_ArrayBuffer: any;
private static SPFX_ElementArrayBuffer: any;
private static SPFX_CurrentProgram: any;
private static SPFX_FrontFace: any;
private static SPFX_DepthFunc: any;
private static SPFX_DepthWriteMask: any;
private static SPFX_StencilTestEnabled: any;
private static SPFX_DepthTestEnabled: any;
private static SPFX_CullFaceEnabled: any;
private static SPFX_BlendEnabled: any;
private static SPFX_BlendSrcRgb: any;
private static SPFX_BlendDstRgb: any;
private static SPFX_BlendSrcAlpha: any;
private static SPFX_BlendDstAlpha: any;
private static SPFX_ActiveTexture: any;
private static SPFX_Texture: any[] = [];
private static __tmp_indentityMatrix: IMatrix44 = Matrix44.identity();
constructor(
entityUid: EntityUID,
componentSid: ComponentSID,
entityRepository: EntityRepository
) {
super(entityUid, componentSid, entityRepository);
}
static get componentTID(): ComponentTID {
return WellKnownComponentTIDs.SparkGearComponentTID;
}
onBeforeRender() {}
onAfterRender() {
const ThisClass = SparkGearComponent;
ThisClass.SPARK_BackupStatus();
_SPARK_Draw(this.__hSPFXInst);
ThisClass.SPARK_RestoreStatus();
}
// clone() {
// return new this.constructor(this._LoadingManager, this._Url).copy(this);
// }
play() {
_SPARK_Instance_Play(this.__hSPFXInst, 1.0, false, 0);
}
stop() {
_SPARK_Instance_Stop(this.__hSPFXInst);
}
pause() {
_SPARK_Instance_Pause(this.__hSPFXInst);
}
isPlaying() {
return _SPARK_Instance_IsPlaying(this.__hSPFXInst);
}
kickTrigger(trigger: any) {
_SPARK_Instance_KickTrigger(this.__hSPFXInst, trigger);
}
static SPARK_BackupStatus() {
const ThisClass = SparkGearComponent;
const gl = ThisClass.SPFX_WebGLResourceRepository.currentWebGLContextWrapper!.getRawContext();
ThisClass.SPFX_ArrayBuffer = gl.getParameter(gl.ARRAY_BUFFER_BINDING);
ThisClass.SPFX_ElementArrayBuffer = gl.getParameter(
gl.ELEMENT_ARRAY_BUFFER_BINDING
);
ThisClass.SPFX_CurrentProgram = gl.getParameter(gl.CURRENT_PROGRAM);
ThisClass.SPFX_FrontFace = gl.getParameter(gl.FRONT_FACE);
ThisClass.SPFX_DepthFunc = gl.getParameter(gl.DEPTH_FUNC);
ThisClass.SPFX_DepthWriteMask = gl.getParameter(gl.DEPTH_WRITEMASK);
ThisClass.SPFX_StencilTestEnabled = gl.isEnabled(gl.STENCIL_TEST);
ThisClass.SPFX_DepthTestEnabled = gl.isEnabled(gl.DEPTH_TEST);
ThisClass.SPFX_CullFaceEnabled = gl.isEnabled(gl.CULL_FACE);
ThisClass.SPFX_BlendEnabled = gl.isEnabled(gl.BLEND);
ThisClass.SPFX_BlendSrcRgb = gl.getParameter(gl.BLEND_SRC_RGB);
ThisClass.SPFX_BlendDstRgb = gl.getParameter(gl.BLEND_DST_RGB);
ThisClass.SPFX_BlendSrcAlpha = gl.getParameter(gl.BLEND_SRC_ALPHA);
ThisClass.SPFX_BlendDstAlpha = gl.getParameter(gl.BLEND_DST_ALPHA);
ThisClass.SPFX_ActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
for (let i = 0; i < 8; i++) {
gl.activeTexture(gl.TEXTURE0 + i);
ThisClass.SPFX_Texture[i] = gl.getParameter(gl.TEXTURE_BINDING_2D);
}
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
}
static SPARK_RestoreStatus = function () {
const ThisClass = SparkGearComponent;
const gl = ThisClass.SPFX_WebGLResourceRepository.currentWebGLContextWrapper!.getRawContext();
gl.useProgram(ThisClass.SPFX_CurrentProgram);
gl.bindBuffer(gl.ARRAY_BUFFER, ThisClass.SPFX_ArrayBuffer);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ThisClass.SPFX_ElementArrayBuffer);
gl.frontFace(ThisClass.SPFX_FrontFace);
gl.depthFunc(ThisClass.SPFX_DepthFunc);
gl.depthMask(ThisClass.SPFX_DepthWriteMask);
gl.blendFuncSeparate(
ThisClass.SPFX_BlendSrcRgb,
ThisClass.SPFX_BlendDstRgb,
ThisClass.SPFX_BlendSrcAlpha,
ThisClass.SPFX_BlendDstAlpha
);
ThisClass.SPFX_StencilTestEnabled
? gl.enable(gl.STENCIL_TEST)
: gl.disable(gl.STENCIL_TEST);
ThisClass.SPFX_DepthTestEnabled
? gl.enable(gl.DEPTH_TEST)
: gl.disable(gl.DEPTH_TEST);
ThisClass.SPFX_CullFaceEnabled
? gl.enable(gl.CULL_FACE)
: gl.disable(gl.CULL_FACE);
ThisClass.SPFX_BlendEnabled ? gl.enable(gl.BLEND) : gl.disable(gl.BLEND);
for (let i = 0; i < 8; i++) {
gl.activeTexture(gl.TEXTURE0 + i);
gl.bindTexture(gl.TEXTURE_2D, ThisClass.SPFX_Texture[i]);
}
gl.activeTexture(ThisClass.SPFX_ActiveTexture);
};
static SPFX_Initialize = function (repository: WebGLResourceRepository) {
const ThisClass = SparkGearComponent;
if (repository.currentWebGLContextWrapper == null) {
return;
}
ThisClass.SPFX_WebGLResourceRepository = repository;
window.GLctx = ThisClass.SPFX_WebGLResourceRepository.currentWebGLContextWrapper!.getRawContext();
ThisClass.SPARK_BackupStatus();
const glw = ThisClass.SPFX_WebGLResourceRepository
.currentWebGLContextWrapper!;
_SPARK_InitializeFor3D(glw.width, glw.height);
ThisClass.SPARK_RestoreStatus();
ThisClass.__isInitialized = true;
};
static SPFX_Uninitialize() {
const ThisClass = SparkGearComponent;
ThisClass.SPARK_BackupStatus();
_SPARK_Uninitialize();
ThisClass.SPARK_RestoreStatus();
}
static SPARK_SetCameraMatrix(
viewMatrix: IMatrix44,
projectionMatrix: IMatrix44
) {
const vMv = (viewMatrix as Matrix44)._v;
_SPARK_SetMatrix(
0,
vMv[0],
vMv[1],
vMv[2],
vMv[3],
vMv[4],
vMv[5],
vMv[6],
vMv[7],
vMv[8],
vMv[9],
vMv[10],
vMv[11],
vMv[12],
vMv[13],
vMv[14],
vMv[15]
);
const pMv = (projectionMatrix as Matrix44)._v;
_SPARK_SetMatrix(
1,
pMv[0],
pMv[1],
pMv[2],
pMv[3],
pMv[4],
pMv[5],
pMv[6],
pMv[7],
pMv[8],
pMv[9],
pMv[10],
pMv[11],
pMv[12],
pMv[13],
pMv[14],
pMv[15]
);
}
static SPFX_Update = function (DeltaTime: number) {
_SPARK_Update(DeltaTime);
};
static SPARK_Draw() {
const ThisClass = SparkGearComponent;
ThisClass.SPARK_BackupStatus();
_SPARK_DrawAll();
ThisClass.SPARK_RestoreStatus();
}
static SPARK_DrawDebugInfo(InfoType: any) {
const ThisClass = SparkGearComponent;
ThisClass.SPARK_BackupStatus();
_SPARK_DrawDebugInfo(InfoType);
ThisClass.SPARK_RestoreStatus();
}
$create() {
this.__sceneGraphComponent = this.__entityRepository.getComponentOfEntity(
this.__entityUid,
SceneGraphComponent
) as SceneGraphComponent;
this.moveStageTo(ProcessStage.Load);
}
static common_$load() {
if (SparkGearComponent.__isInitialized) {
return;
}
const moduleManager = ModuleManager.getInstance();
const moduleName = 'webgl';
const webglModule = moduleManager.getModule(moduleName)! as any;
// Initialize SPARKGEAR
SparkGearComponent.SPFX_Initialize(
webglModule.WebGLResourceRepository.getInstance()
);
}
$load() {
if (this.url == null) {
return;
}
const loadBytes = function (
path: string,
type: XMLHttpRequestResponseType,
callback: Function
) {
const request = new XMLHttpRequest();
request.open('GET', path, true);
request.responseType = type;
request.onload = () => {
switch (request.status) {
case 200:
callback(request.response);
break;
default:
console.error('Failed to load (' + request.status + ') : ' + path);
break;
}
};
request.send(null);
};
const ThisClass = SparkGearComponent;
loadBytes(this.url, 'arraybuffer', (data: ArrayBuffer) => {
const buffer = new Uint8Array(data);
ThisClass.SPARK_BackupStatus();
const SPFXData = window.Module.ccall(
'SPARK_Data_Create',
'number',
['string', 'number', 'array', 'number'],
[this.url, this.url!.length, buffer, buffer.length]
);
this.__hSPFXInst = _SPARK_Instance_Create(SPFXData);
_SPARK_Data_Delete(SPFXData);
ThisClass.SPARK_RestoreStatus();
this.moveStageTo(ProcessStage.Logic);
});
}
$logic() {
// Keep Playing
if (!this.isPlaying()) {
this.play();
}
const cameraComponent = ComponentRepository.getInstance().getComponent(
CameraComponent,
CameraComponent.main
) as CameraComponent;
let viewMatrix = SparkGearComponent.__tmp_indentityMatrix;
let projectionMatrix = SparkGearComponent.__tmp_indentityMatrix;
if (cameraComponent) {
viewMatrix = cameraComponent.viewMatrix;
projectionMatrix = cameraComponent.projectionMatrix;
}
SparkGearComponent.SPARK_SetCameraMatrix(viewMatrix, projectionMatrix);
SparkGearComponent.SPFX_Update(1.0);
const m = this.__sceneGraphComponent!.worldMatrixInner;
_SPARK_Instance_SetTransformFor3D(
this.__hSPFXInst,
m._v[0],
m._v[4],
m._v[8],
m._v[12],
m._v[1],
m._v[5],
m._v[9],
m._v[13],
m._v[2],
m._v[6],
m._v[10],
m._v[14],
m._v[3],
m._v[7],
m._v[11],
m._v[15]
);
this.moveStageTo(ProcessStage.Render);
}
$render() {
this.onAfterRender();
this.moveStageTo(ProcessStage.Logic);
}
}
ComponentRepository.registerComponentClass(SparkGearComponent); | the_stack |
import * as _fs from 'fs';
// TODO: change this to type-only import once TS 3.8 gets released
// tslint:disable-next-line:import-blacklist
import * as _ from 'lodash';
import { expect } from 'chai';
import {
balena,
givenLoggedInUser,
givenInitialOrganization,
IS_BROWSER,
loginPaidUser,
} from '../setup';
import { timeSuite } from '../../util';
import type * as BalenaSdk from '../../..';
describe('Billing Model', function () {
timeSuite(before);
describe('Free Account', function () {
givenLoggedInUser(before);
givenInitialOrganization(before);
describe('balena.models.billing.getAccount()', function () {
it('should not return a billing account info object', function () {
const promise = balena.models.billing.getAccount(this.initialOrg.id);
return expect(promise).to.be.rejected.then(function (error) {
expect(error).to.have.property('code', 'BalenaRequestError');
expect(error).to.have.property('statusCode', 404);
expect(error)
.to.have.property('message')
.that.contains('Billing Account was not found.');
});
});
});
describe('balena.models.billing.getPlan()', function () {
it('should return a free tier billing plan object', function () {
return balena.models.billing.getPlan(this.initialOrg.id).then((plan) =>
expect(plan).to.deep.match({
title: 'Free',
name: 'Free plan',
code: 'free',
tier: 'free',
addOns: [],
billing: {
currency: 'USD',
charges: [
{
itemType: 'plan',
name: 'Free plan',
code: 'free',
unitCostCents: '0',
quantity: '1',
},
{
itemType: 'support',
name: 'Community support',
code: 'community',
unitCostCents: '0',
quantity: '1',
},
],
totalCostCents: '0',
},
support: {
title: 'Community',
name: 'Community support',
},
}),
);
});
});
describe('balena.models.billing.getBillingInfo()', function () {
it('should return a free tier billing info object', function () {
const promise = balena.models.billing.getBillingInfo(
this.initialOrg.id,
);
return expect(promise).to.become({});
});
});
describe('balena.models.billing.updateBillingInfo()', function () {
it('should throw when no parameters are provided', function () {
const promise = (balena.models.billing.updateBillingInfo as any)();
return expect(promise).to.be.rejected.and.eventually.have.property(
'code',
'BalenaInvalidParameterError',
);
});
it('should throw when no billing info parameter is provided', function () {
const promise = (balena.models.billing.updateBillingInfo as any)(
this.initialOrg.id,
);
return expect(promise).to.be.rejected.then((error) =>
expect(error).to.have.property('statusCode', 400),
);
});
it('should throw when an empty parameter object is provided', function () {
const promise = balena.models.billing.updateBillingInfo(
this.initialOrg.id,
{} as any,
);
return expect(promise).to.be.rejected.then((error) =>
expect(error).to.have.property('statusCode', 400),
);
});
it('should throw when the token_id is empty', function () {
const promise = balena.models.billing.updateBillingInfo(
this.initialOrg.id,
{
token_id: '',
},
);
return expect(promise).to.be.rejected.then((error) =>
expect(error).to.have.property('statusCode', 400),
);
});
});
describe('balena.models.billing.getInvoices()', function () {
it('should return no invoices', function () {
const promise = balena.models.billing.getInvoices(this.initialOrg.id);
return expect(promise).to.become([]);
});
});
describe('balena.models.billing.downloadInvoice()', function () {
before(function () {
return balena.models.billing
.getInvoices(this.initialOrg.id)
.then((invoices) => {
this.firstInvoiceNumber = invoices?.[0]?.invoice_number;
})
.catch(_.noop);
});
it('should not be able to download any invoice', function () {
expect(this.firstInvoiceNumber).to.be.a('undefined');
const promise = balena.models.billing.downloadInvoice(
this.initialOrg.id,
'anyinvoicenumber',
);
return expect(promise).to.be.rejected;
});
it('should throw when an invoice number is not provided', function () {
const promise = (balena.models.billing.downloadInvoice as any)();
return expect(promise).to.be.rejected;
});
it('should throw when an empty string invoice number is provided', function () {
const promise = balena.models.billing.downloadInvoice(
this.initialOrg.id,
'',
);
return expect(promise).to.be.rejected;
});
it('should throw when trying to retrieve an non-existing invoice', function () {
const promise = balena.models.billing.downloadInvoice(
this.initialOrg.id,
'notfound',
);
return expect(promise).to.be.rejected;
});
it('should not return an invoice of a different user', function () {
const promise = balena.models.billing.downloadInvoice(
this.initialOrg.id,
'1000',
);
return expect(promise).to.be.rejected;
});
});
});
describe('Paid Account', function () {
let hasActiveBillingAccount = false;
const givenABillingAccountIt = (
description: string,
testFn: (...args: any[]) => any,
) => {
const $it = hasActiveBillingAccount ? it : it.skip;
$it(description, testFn);
};
before(function () {
return loginPaidUser()
.then(() => balena.models.billing.getAccount(this.initialOrg.id))
.then((accountInfo) => {
hasActiveBillingAccount =
(accountInfo != null ? accountInfo.account_state : undefined) ===
'active';
})
.catch(_.noop);
});
givenInitialOrganization(before);
describe('balena.models.billing.getAccount()', function () {
givenABillingAccountIt(
'should return a paid tier billing account info object',
function () {
const promise = balena.models.billing.getAccount(this.initialOrg.id);
return expect(promise).to.become({
account_state: 'active',
address: {
address1: 'One London Wall',
address2: '6th Floor',
city: 'London',
country: 'GB',
phone: '6970000000',
state: 'Greater London',
zip: 'EC2Y 5EB',
},
cc_emails: 'testdev-cc@nomail.com',
company_name: 'Resin.io',
first_name: 'John',
last_name: 'Doe',
vat_number: '',
});
},
);
});
describe('balena.models.billing.getPlan()', function () {
givenABillingAccountIt(
'should return a paid tier billing plan object',
function () {
return balena.models.billing
.getPlan(this.initialOrg.id)
.then(function (plan) {
expect(plan).to.deep.match({
title: 'Team member',
name: 'Team member plan',
code: 'free',
tier: 'free',
addOns: [],
addonPlan: {
addOns: [],
billing: {
charges: [],
currency: 'USD',
totalCostCents: '0',
},
code: 'addons',
currentPeriodEndDate: '',
uuid: '',
},
billing: {
currency: 'USD',
charges: [
{
itemType: 'plan',
name: 'Team member plan',
code: 'free',
unitCostCents: '0',
quantity: '1',
},
{
itemType: 'support',
name: 'Standard support',
code: 'core',
unitCostCents: '0',
quantity: '1',
},
],
totalCostCents: '0',
},
support: {
title: 'Standard',
name: 'Standard support',
},
});
expect(plan)
.to.have.property('currentPeriodEndDate')
.that.is.a('string');
});
},
);
});
describe('balena.models.billing.getBillingInfo()', function () {
givenABillingAccountIt(
'should return a billing info object',
function () {
return balena.models.billing
.getBillingInfo(this.initialOrg.id)
.then(function (billingInfo) {
expect(billingInfo).to.not.be.null;
// this is for local tests
if (
(billingInfo as BalenaSdk.CardBillingInfo).card_type === 'Visa'
) {
expect(billingInfo).to.deep.equal({
first_name: 'John',
last_name: 'Doe',
company: 'Resin.io',
vat_number: 'GBUK00000000000',
address1: 'One London Wall',
address2: '6th floor',
city: 'London',
state: 'Greater London',
zip: 'EC2Y 5EB',
country: 'GB',
phone: '6970000000',
card_type: 'Visa',
last_four: '1111',
type: 'credit_card',
first_one: '4',
year: '2018',
month: '8',
full_name: 'John Doe',
});
} else {
expect(billingInfo).to.deep.equal({});
}
});
},
);
});
describe('balena.models.billing.getInvoices()', function () {
givenABillingAccountIt(
'should return an array of invoice objects',
function () {
return balena.models.billing
.getInvoices(this.initialOrg.id)
.then(function (invoices) {
expect(Array.isArray(invoices)).to.be.true;
expect(invoices.length).to.not.equal(0);
const invoice = invoices[0];
expect(invoice).to.have.property('closed_at').that.is.a('string');
expect(invoice)
.to.have.property('created_at')
.that.is.a('string');
expect(invoice).to.have.property('due_on').that.is.a('string');
expect(invoice)
.to.have.property('invoice_number')
.that.is.a('string');
expect(invoice).to.have.property('uuid').that.is.a('string');
expect(invoice).to.have.property('currency', 'USD');
expect(invoice).to.have.property('total_in_cents', '0');
expect(invoice).to.have.property('subtotal_in_cents', '0');
expect(invoice).to.have.property('state', 'paid');
});
},
);
});
describe('balena.models.billing.downloadInvoice()', function () {
before(function () {
return balena.models.billing
.getInvoices(this.initialOrg.id)
.then((invoices) => {
this.firstInvoiceNumber = invoices?.[0]?.invoice_number;
})
.catch(_.noop);
});
if (IS_BROWSER) {
givenABillingAccountIt(
'should be able to download an invoice on the browser',
function () {
return balena.models.billing
.downloadInvoice(this.firstInvoiceNumber, this.initialOrg.id)
.then(function (result: Blob) {
expect(result).to.be.an.instanceof(Blob);
expect(result.size).to.not.equal(0);
expect(result.type).to.equal('application/pdf');
});
},
);
} else {
const rindle = require('rindle');
const tmp = require('tmp');
const fs = require('fs') as typeof _fs;
givenABillingAccountIt(
'should be able to download an invoice on node',
function () {
return balena.models.billing
.downloadInvoice(this.initialOrg.id, this.firstInvoiceNumber)
.then(function (result) {
const stream = result as Exclude<typeof result, Blob>;
expect(stream.mime).to.equal('application/pdf');
const tmpFile = tmp.tmpNameSync();
return rindle
.wait(stream.pipe(fs.createWriteStream(tmpFile)))
.then(() => fs.promises.stat(tmpFile))
.then((stat: _fs.Stats) => expect(stat.size).to.not.equal(0))
.finally(() => fs.promises.unlink(tmpFile));
});
},
);
}
});
});
}); | the_stack |
import { expect, use } from "chai";
import ChaiAsPromised from "chai-as-promised";
import * as sinon from "sinon";
import * as moq from "typemoq";
import { ArrayValue, PrimitiveValue, StructValue } from "@itwin/appui-abstract";
import { BeEvent, Guid, Id64String } from "@itwin/core-bentley";
import { IModelConnection } from "@itwin/core-frontend";
import {
ArrayTypeDescription, CategoryDescription, Content, DefaultContentDisplayTypes, Descriptor, DisplayValue, Field, Item, KeySet,
PrimitiveTypeDescription, PropertyValueFormat, RegisteredRuleset, Ruleset, StructTypeDescription, TypeDescription, Value, ValuesDictionary,
ValuesMap,
} from "@itwin/presentation-common";
import { Presentation, PresentationManager, RulesetManager } from "@itwin/presentation-frontend";
import { ContentBuilder, IContentBuilderDataProvider } from "../presentation-testing/ContentBuilder";
use(ChaiAsPromised);
class EmptyDataProvider implements IContentBuilderDataProvider {
// Verifies that given keyset matches a template, otherwise it throws an error
private _keyVerificationFunction: ((keyset: KeySet) => void) | undefined;
constructor(keyVerificationFunction?: (keyset: KeySet) => void) {
this._keyVerificationFunction = keyVerificationFunction;
}
private _keyset: KeySet | undefined;
public getContentSetSize = async () => 0;
public getContent = async (): Promise<Readonly<Content> | undefined> => undefined;
public set keys(keyset: KeySet) {
if (this._keyVerificationFunction)
this._keyVerificationFunction(keyset);
this._keyset = keyset;
}
public get keys() {
return this._keyset ? this._keyset : new KeySet();
}
}
function createItem(values: ValuesDictionary<Value>) {
const displayValues: ValuesDictionary<DisplayValue> = {};
for (const key in values) {
if (values.hasOwnProperty(key)) {
displayValues[key] = "";
}
}
return new Item(
Object.keys(values).map((key) => ({ className: "testClass", id: key })),
"Test class",
"",
undefined,
values,
displayValues,
[],
);
}
async function getContent(items: Array<ValuesDictionary<Value>>, descriptor: Descriptor) {
return new Content(descriptor, items.map(createItem));
}
const createCategoryDescription = (): CategoryDescription => ({
name: "test",
label: "test",
priority: 1,
description: "",
expand: false,
});
const createPrimitiveTypeDescription = (typeName: string): PrimitiveTypeDescription => ({
valueFormat: PropertyValueFormat.Primitive,
typeName,
});
const createStringTypeDescription = () => createPrimitiveTypeDescription("string");
const createIntTypeDescription = () => createPrimitiveTypeDescription("int");
const createDoubleTypeDescription = () => createPrimitiveTypeDescription("double");
const createPoint2dTypeDescription = () => createPrimitiveTypeDescription("pt2d");
const createPoint3dTypeDescription = () => createPrimitiveTypeDescription("pt3d");
const createArrayTypeDescription = (itemType: TypeDescription): ArrayTypeDescription => ({
valueFormat: PropertyValueFormat.Array,
typeName: "array",
memberType: itemType,
});
const createStructTypeDescription = (members: { [name: string]: TypeDescription }): StructTypeDescription => ({
valueFormat: PropertyValueFormat.Struct,
typeName: "struct",
members: Object.keys(members).map((key) => ({ name: key, label: key, type: members[key] })),
});
const createContentDescriptor = () => {
const category = createCategoryDescription();
return new Descriptor({
displayType: "Grid",
selectClasses: [],
categories: [category],
fields: [
new Field(category, "width", "width", createStringTypeDescription(), false, 1),
new Field(category, "title", "title", createStringTypeDescription(), false, 1),
new Field(category, "radius", "radius", createStringTypeDescription(), false, 1),
],
contentFlags: 1,
});
};
class DataProvider extends EmptyDataProvider {
public descriptor = createContentDescriptor();
public values = [
{ title: "Item", height: 15, width: 16 },
{ title: "Circle", radius: 13 },
];
public override getContentSetSize = async () => this.values.length;
public override getContent = async () => getContent(this.values, this.descriptor);
}
async function getEmptyContent(props: { descriptor: Readonly<Descriptor> }) {
return new Content(props.descriptor, []);
}
interface TestInstance {
schemaName: string;
className: string;
ids: Array<{ id: Id64String }>;
}
function verifyInstanceKey(instanceKey: [string, Set<string>], instances: TestInstance[]) {
const className = instanceKey[0];
const ids = Array.from(instanceKey[1].values());
for (const instance of instances) {
if (`${instance.schemaName}:${instance.className}` === className) {
for (const idEntry of instance.ids) {
if (!ids.includes(idEntry.id)) {
throw new Error(`Wrong id provided - '${idEntry.id}'`);
}
}
return;
}
}
throw new Error(`Wrong className provided - '${className}'`);
}
function verifyKeyset(keyset: KeySet, testInstances: TestInstance[], verificationSpy: sinon.SinonSpy) {
verificationSpy();
for (const entry of keyset.instanceKeys.entries()) {
verifyInstanceKey(entry, testInstances);
}
}
const createThrowingQueryFunc = (instances: TestInstance[]) => {
return async function* (query: string) {
if (query.includes("SELECT s.Name")) {
for (const row of instances)
yield row;
return;
}
throw new Error("Test error");
};
};
const createQueryFunc = (instances: TestInstance[]) => {
return async function* (query: string) {
if (query.includes("SELECT s.Name")) {
for (const row of instances)
yield row;
return;
}
for (const entry of instances) {
if (query.includes(`"${entry.schemaName}"."${entry.className}"`)) {
for (const id of entry.ids)
yield id;
return;
}
}
};
};
describe("ContentBuilder", () => {
const imodelMock = moq.Mock.ofType<IModelConnection>();
describe("createContent", () => {
const presentationManagerMock = moq.Mock.ofType<PresentationManager>();
const rulesetMock = moq.Mock.ofType<Ruleset>();
const rulesetManagerMock = moq.Mock.ofType<RulesetManager>();
before(() => {
rulesetMock.setup((ruleset) => ruleset.id).returns(() => "1");
});
beforeEach(() => {
rulesetManagerMock.setup(async (x) => x.add(moq.It.isAny())).returns(async (ruleset) => new RegisteredRuleset(ruleset, Guid.createValue(), () => { }));
presentationManagerMock.reset();
presentationManagerMock.setup((manager) => manager.rulesets()).returns(() => rulesetManagerMock.object);
presentationManagerMock.setup(async (manager) => manager.getContent(moq.It.isAny())).returns(getEmptyContent);
presentationManagerMock.setup((x) => x.onIModelContentChanged).returns(() => new BeEvent());
Presentation.setPresentationManager(presentationManagerMock.object);
});
it("returns empty records when there is no content returned from presentation", async () => {
const builder = new ContentBuilder({ imodel: imodelMock.object });
let content = await builder.createContent("1", []);
expect(content).to.be.empty;
presentationManagerMock.verify((manager) => manager.rulesets(), moq.Times.never());
content = await builder.createContent(rulesetMock.object, []);
presentationManagerMock.verify((manager) => manager.rulesets(), moq.Times.once());
expect(content).to.be.empty;
content = await builder.createContent("1", [], DefaultContentDisplayTypes.List);
expect(content).to.be.empty;
});
it("returns empty records when there is no content in the supplied data provider", async () => {
const builder = new ContentBuilder({ imodel: imodelMock.object, dataProvider: new EmptyDataProvider() });
const content = await builder.createContent("1", []);
expect(content).to.be.empty;
});
it("returns correct records when there is content in the supplied data provider", async () => {
const dataProvider = new DataProvider();
const builder = new ContentBuilder({ imodel: imodelMock.object, dataProvider });
const content = await builder.createContent("1", []);
expect(content.length).to.equal(dataProvider.values.length * dataProvider.descriptor.fields.length);
});
it("rounds raw numeric values to supplied decimal precision", async () => {
const testValues = [
{ name: "not-set", value: undefined, type: createDoubleTypeDescription() },
{ name: "int", value: 1, type: createIntTypeDescription() },
{ name: "doubleLowPrecision", value: 1.9, type: createDoubleTypeDescription() },
{ name: "doubleRoundedDown", value: 1.234, type: createDoubleTypeDescription() },
{ name: "doubleRoundedUp", value: 4.567, type: createDoubleTypeDescription() },
{ name: "doublesArray", value: [1.234, 4.567, 7.890], type: createArrayTypeDescription(createDoubleTypeDescription()) },
{ name: "doublesStruct", value: { a: 1.234 }, type: createStructTypeDescription({ a: createDoubleTypeDescription() }) },
{ name: "point2d", value: [1.456, 4.789], type: createPoint2dTypeDescription() },
{ name: "point3d", value: { x: 1.234, y: 4.567, z: 7.890 }, type: createPoint3dTypeDescription() },
];
const category = createCategoryDescription();
const descriptor = new Descriptor({
displayType: "",
selectClasses: [],
categories: [category],
fields: testValues.map((v) => new Field(category, v.name, v.name, v.type, false, 1)),
contentFlags: 1,
});
class TestDataProvider extends EmptyDataProvider {
public readonly descriptor = descriptor;
public readonly values = [testValues.reduce((map, v) => ({ ...map, [v.name]: v.value }), {} as ValuesMap)];
public override getContentSetSize = async () => this.values.length;
public override getContent = async () => getContent(this.values, this.descriptor);
}
const dataProvider = new TestDataProvider();
const builder = new ContentBuilder({ imodel: imodelMock.object, dataProvider, decimalPrecision: 2 });
const content = await builder.createContent("", []);
expect(content.length).to.eq(testValues.length);
expect((content[0].value as PrimitiveValue).value).to.be.undefined;
expect((content[1].value as PrimitiveValue).value).to.eq(1);
expect((content[2].value as PrimitiveValue).value).to.eq(1.9);
expect((content[3].value as PrimitiveValue).value).to.eq(1.23);
expect((content[4].value as PrimitiveValue).value).to.eq(4.57);
expect((content[5].value as ArrayValue).items.map((item) => (item.value as PrimitiveValue).value)).to.deep.eq([1.23, 4.57, 7.89]);
expect(((content[6].value as StructValue).members.a!.value as PrimitiveValue).value).to.deep.eq(1.23);
expect((content[7].value as PrimitiveValue).value).to.deep.eq([1.46, 4.79]);
expect((content[8].value as PrimitiveValue).value).to.deep.eq({ x: 1.23, y: 4.57, z: 7.89 });
});
});
describe("createContentForAllClasses", () => {
const testInstances: TestInstance[] = [
{
className: "Class1",
schemaName: "Schema1",
ids: [{ id: "0x2" }, { id: "0x3" }],
},
{
className: "Class2",
schemaName: "Schema2",
ids: [{ id: "0x5" }, { id: "0x6" }],
},
];
before(() => {
imodelMock.reset();
const f = createQueryFunc(testInstances);
imodelMock.setup((imodel) => imodel.query(moq.It.isAny(), moq.It.isAny(), moq.It.isAny())).returns(f);
});
it("returns all required instances with empty records", async () => {
const verificationSpy = sinon.spy();
const builder = new ContentBuilder({
imodel: imodelMock.object,
dataProvider: new EmptyDataProvider((keyset: KeySet) => verifyKeyset(keyset, testInstances, verificationSpy)),
});
const content = await builder.createContentForAllInstances("1");
expect(content.length).to.equal(2);
expect(content.find((c) => c.className === "Schema1:Class1")).to.not.be.undefined;
expect(content.find((c) => c.className === "Schema2:Class2")).to.not.be.undefined;
expect(content[0].records).to.be.empty;
expect(content[1].records).to.be.empty;
expect(verificationSpy.calledTwice).to.be.true;
});
});
describe("createContentForInstancePerClass", () => {
context("test instances have ids", () => {
const testInstances: TestInstance[] = [
{
className: "Class1",
schemaName: "Schema1",
ids: [{ id: "0x1" }],
},
{
className: "Class2",
schemaName: "Schema2",
ids: [{ id: "0x9" }],
},
];
it("returns all required instances with empty records", async () => {
imodelMock.reset();
imodelMock.setup((imodel) => imodel.query(moq.It.isAny(), moq.It.isAny(), moq.It.isAny())).returns(createQueryFunc(testInstances));
const verificationSpy = sinon.spy();
const builder = new ContentBuilder({
imodel: imodelMock.object,
dataProvider: new EmptyDataProvider((keyset: KeySet) => verifyKeyset(keyset, testInstances, verificationSpy)),
});
const content = await builder.createContentForInstancePerClass("1");
expect(content.length).to.equal(2);
expect(content.find((c) => c.className === "Schema1:Class1")).to.not.be.undefined;
expect(content.find((c) => c.className === "Schema2:Class2")).to.not.be.undefined;
expect(content[0].records).to.be.empty;
expect(content[1].records).to.be.empty;
expect(verificationSpy.calledTwice).to.be.true;
});
it("throws when id query throws an unexpected error", async () => {
imodelMock.reset();
imodelMock.setup((imodel) => imodel.query(moq.It.isAny(), moq.It.isAny(), moq.It.isAny())).returns(createThrowingQueryFunc(testInstances));
const verificationSpy = sinon.spy();
const builder = new ContentBuilder({
imodel: imodelMock.object,
dataProvider: new EmptyDataProvider((keyset: KeySet) => verifyKeyset(keyset, testInstances, verificationSpy)),
});
await expect(builder.createContentForInstancePerClass("1")).to.be.rejectedWith("Test error");
});
});
context("test instances have no ids", () => {
const testInstances: TestInstance[] = [{ className: "Class1", schemaName: "Schema1", ids: [] }];
before(() => {
imodelMock.reset();
imodelMock.setup((imodel) => imodel.query(moq.It.isAny(), moq.It.isAny(), moq.It.isAny())).returns(createQueryFunc(testInstances));
});
it("returns an empty list", async () => {
const verificationSpy = sinon.spy();
const builder = new ContentBuilder({
imodel: imodelMock.object,
dataProvider: new EmptyDataProvider((keyset: KeySet) => verifyKeyset(keyset, testInstances, verificationSpy)),
});
const content = await builder.createContentForInstancePerClass("1");
expect(content).to.be.empty;
expect(verificationSpy.notCalled).to.be.true;
});
});
});
}); | the_stack |
import { compareDates, getItem, isLoggedIn } from "./Util";
import fs = require("fs");
import { CodetimeMetrics } from "../models/CodetimeMetrics";
import { Log } from "../models/Log";
import {
incrementSummaryShare,
updateSummaryJson,
getSummaryTotalHours,
setSummaryCurrentHours,
setSummaryTotalHours,
getCurrentChallengeRound
} from "./SummaryUtil";
import { getFileDataAsJson, getFile } from "../managers/FileManager";
import { isResponseOk, softwareDelete, softwareGet, softwarePost, softwarePut } from "../managers/HttpManager";
import { commands, window } from "vscode";
import { getAllMilestones } from "./MilestonesUtil";
import { NO_TITLE_LABEL } from "./Constants";
const queryString = require("query-string");
const moment = require("moment-timezone");
let currently_deleting_log_date: number = -1;
export function getLogsFilePath(): string {
return getFile("logs.json");
}
export function deleteLogsJson() {
const filepath = getLogsFilePath();
const fileExists = fs.existsSync(filepath);
if (fileExists) {
fs.unlinkSync(filepath);
}
}
export function getAllDescendingOrderLogObjects(): Array<Log> {
const filepath = getLogsFilePath();
let logs = getFileDataAsJson(filepath);
if (logs && logs.length) {
// sort by unix_date in descending order
logs = logs.sort(
(a: Log, b: Log) => b.unix_date - a.unix_date
);
}
return logs || [];
}
export function getLogByUnixDate(unix_date: number): Log {
const logs: Array<Log> = getAllDescendingOrderLogObjects();
if (logs && logs.length) {
return logs.find(n => n.unix_date === unix_date);
}
return null;
}
export function getDayNumberLog(day_number: number): Log {
const logs: Array<Log> = getAllDescendingOrderLogObjects();
if (logs && logs.length) {
logs.reverse();
return logs.find(n => n.day_number === day_number);
}
return null;
}
export function updateDayNumberLog(log: Log) {
const logs: Array<Log> = getAllDescendingOrderLogObjects();
if (logs && logs.length) {
logs.reverse();
for (let i = 0; i < logs.length; i++) {
let existingLog = logs[i];
if (existingLog.day_number === log.day_number) {
logs[i] = log;
writeToLogsJson(logs);
break;
}
}
}
}
export function writeToLogsJson(logs: Array<Log> = []) {
const filepath = getLogsFilePath();
try {
fs.writeFileSync(filepath, JSON.stringify(logs, null, 2));
} catch (err) {
console.log(err);
}
}
export function getLogsSummary(): any {
const logs: Array<Log> = getAllDescendingOrderLogObjects();
let totalHours = 0;
let totalLinesAdded = 0;
let totalKeystrokes = 0;
let totalDays = 0;
let longest_streak = 0;
let current_streak = 0;
let currentHours = 0;
let currentKeystrokes = 0;
let currentLines = 0;
let currentDate = 0;
if (logs.length > 0) {
const hours24 = 86400000;
let previousDate = logs[0].date - hours24;
for (let i = 0; i < logs.length - 1; i++) {
totalHours += logs[i].codetime_metrics.hours;
totalLinesAdded += logs[i].codetime_metrics.lines_added;
totalKeystrokes += logs[i].codetime_metrics.keystrokes;
totalDays++;
if (compareDates(new Date(previousDate + hours24), new Date(logs[i].date))) {
current_streak++;
if (current_streak > longest_streak) {
longest_streak = current_streak;
}
} else {
current_streak = 0;
}
previousDate = logs[i].date;
}
const lastLog = logs[logs.length - 1];
// checks if last log is today
if (compareDates(new Date(lastLog.date), new Date())) {
currentHours = lastLog.codetime_metrics.hours;
currentKeystrokes = lastLog.codetime_metrics.keystrokes;
currentLines = lastLog.codetime_metrics.lines_added;
totalDays++;
} else {
totalHours += lastLog.codetime_metrics.hours;
totalLinesAdded += lastLog.codetime_metrics.lines_added;
totalKeystrokes += lastLog.codetime_metrics.keystrokes;
totalDays++;
}
if (compareDates(new Date(previousDate + hours24), new Date(lastLog.date))) {
current_streak++;
if (current_streak > longest_streak) {
longest_streak = current_streak;
}
} else {
current_streak = 0;
}
currentDate = lastLog.date;
}
return {
totalHours,
totalLinesAdded,
totalKeystrokes,
totalDays,
longest_streak,
current_streak,
currentHours,
currentKeystrokes,
currentLines,
currentDate
};
}
export function getDayNumberFromDate(dateUnix: number): number {
const logs = getAllDescendingOrderLogObjects();
let date = new Date(dateUnix);
for (let log of logs) {
if (compareDates(new Date(log.date), date)) {
return log.day_number;
}
}
return -1;
}
export function setDailyMilestonesByDayNumber(dayNumber: number, newMilestones: Array<number>) {
let log = getDayNumberLog(dayNumber);
newMilestones = newMilestones.concat(log.milestones);
newMilestones = Array.from(new Set(newMilestones));
log.milestones = newMilestones;
updateDayNumberLog(log);
}
export async function addLogToJson(
title: string,
description: string,
hours: string,
keystrokes: string,
lines: string,
links: Array<string>
) {
const numLogs = getLatestLogEntryNumber();
if (numLogs === 0) {
console.log("Logs json could not be read");
return false;
}
let codetimeMetrics = new CodetimeMetrics();
codetimeMetrics.hours = parseFloat(hours);
codetimeMetrics.lines_added = parseInt(lines);
codetimeMetrics.keystrokes = parseInt(keystrokes);
let log = new Log();
if (title) {
log.title = title;
}
log.description = description;
log.links = links;
log.codetime_metrics = codetimeMetrics;
log.day_number = getDayNumberForNewLog();
log.challenge_round = getCurrentChallengeRound();
await createLog(log);
updateSummaryJson();
}
// Get the last log's day_number. If the date is the
// same use the same day_number. If not, increment it.
export function getDayNumberForNewLog() {
const lastLog = getMostRecentLogObject();
const currentDay = moment().format("YYYY-MM-DD");
const lastLogDay = moment(lastLog.date).format("YYYY-MM-DD");
if (currentDay == lastLogDay) {
return lastLog.day_number;
}
return lastLog.day_number + 1;
}
export function getLatestLogEntryNumber(): number {
let logs = getAllDescendingOrderLogObjects();
return logs ? logs.length : 0;
}
export function getMostRecentLogObject(): Log | any {
const logs = getAllDescendingOrderLogObjects();
if (logs && logs.length > 0) {
// get the most recent one
return logs[0];
}
const log:Log = new Log();
log.day_number = 1;
log.challenge_round = getCurrentChallengeRound();
return log;
}
export function getLogDateRange(): Array<number> {
const logs = getAllDescendingOrderLogObjects();
let dates = [];
if (logs.length) {
dates.push(logs[0].date);
dates.push(logs[logs.length - 1].date);
}
return dates;
}
export function getAllCodetimeHours(): Array<number> {
const logs = getAllDescendingOrderLogObjects();
let sendHours: Array<number> = [];
for (let i = 0; i < logs.length; i++) {
if (logs[i].day_number) {
sendHours.push(logs[i].codetime_metrics.hours);
}
}
return sendHours;
}
export function getLastSevenLoggedDays(): Array<Log> {
const logs = getAllDescendingOrderLogObjects();
let sendLogs: Array<Log> = [];
if (logs.length === 0) {
return sendLogs;
}
if (logs[logs.length - 1].title !== NO_TITLE_LABEL) {
sendLogs.push(logs[logs.length - 1]);
}
for (let i = logs.length - 2; i >= 0; i--) {
if (logs[i].day_number) {
sendLogs.push(logs[i]);
if (sendLogs.length === 7) {
return sendLogs;
}
}
}
return sendLogs;
}
export function checkIfOnStreak(): boolean {
const logs = getAllDescendingOrderLogObjects();
// one day streak
if (logs.length < 2) {
return true;
}
const currDate = new Date(logs[logs.length - 1].date);
const prevDatePlusDay = new Date(logs[logs.length - 2].date + 86400000);
return compareDates(currDate, prevDatePlusDay);
}
export function updateLogShare(day: number) {
const log = getDayNumberLog(day);
if (log && !log.shared) {
log.shared = true;
incrementSummaryShare();
updateDayNumberLog(log);
}
}
export async function editLogEntry(
dayNumber: number,
unix_date: number,
title: string,
description: string,
links: Array<string>,
editedHours: number
) {
let log = getLogByUnixDate(unix_date);
log.title = title;
log.description = description;
log.links = links;
log.unix_date = unix_date;
const currentLoggedHours = log.codetime_metrics.hours;
if (editedHours >= 0 && editedHours <= 12) {
log.codetime_metrics.hours = editedHours;
} else if (editedHours < 0) {
log.codetime_metrics.hours = 0;
} else {
log.codetime_metrics.hours = 12;
}
let summaryTotalHours = getSummaryTotalHours();
if (dayNumber === getAllDescendingOrderLogObjects().length) {
setSummaryCurrentHours(log.codetime_metrics.hours);
} else {
summaryTotalHours -= currentLoggedHours;
summaryTotalHours += log.codetime_metrics.hours;
setSummaryTotalHours(summaryTotalHours);
}
await updateLog(log);
}
// updates a log locally and on the server
async function updateLog(log: Log) {
// get all log objects
const logs = await getLocalLogsFromFile();
const index = logs.findIndex(n => n.unix_date === log.unix_date);
// replace
logs[index] = log;
// write back to local
saveLogsToFile(logs);
// push changes to server
const preparedLog = await prepareLogForServerUpdate(log);
await updateExistingLogOnServer(preparedLog);
}
// creates a new log locally and on the server
export async function createLog(log: Log) {
// get all log objects
const logs = await getLocalLogsFromFile();
// push the new log to the server
const preparedLog:Log = await prepareLogForServerUpdate(log);
// add the new log
const updatedLogs = [...logs, preparedLog];
// write back to the local file
saveLogsToFile(updatedLogs);
await pushNewLogToServer(preparedLog);
}
export async function deleteLogDay(unix_date: number) {
if (currently_deleting_log_date !== -1) {
window.showInformationMessage("Currently waiting to delete the requested log, please wait.");
return;
}
currently_deleting_log_date = unix_date;
const resp = await softwareDelete("/100doc/logs", { unix_dates: [unix_date] }, getItem("jwt"));
if (isResponseOk(resp)) {
window.showInformationMessage("Your log has been successfully deleted.");
// delete the log
let logs: Array<Log> = await getLocalLogsFromFile();
// delete the log based on the dayNum
logs = logs.filter((n: Log) => n.unix_date !== unix_date);
saveLogsToFile(logs);
await syncLogs();
commands.executeCommand("DoC.viewLogs");
}
currently_deleting_log_date = -1;
}
// pulls logs from the server and saves them locally. This will be run periodically.
// logs have a format like [ { day_number: 1, date: ... }, ... ]
export async function syncLogs() {
let serverLogs: Array<Log> = getLocalLogsFromFile();
const qryStr = queryString.stringify({
challenge_round: getCurrentChallengeRound()
});
const resp = await softwareGet(`/100doc/logs?${qryStr}`, getItem("jwt"));
if (isResponseOk(resp)) {
serverLogs = resp.data;
}
let createLogForToday = true;
const currentDay = moment().format("YYYY-MM-DD");
if (serverLogs && serverLogs.length) {
// these come back sorted in ascending order
const formattedLogs = formatLogs(serverLogs);
// check if we have one for today
const lastLoggedDay = moment(formattedLogs[0].date).format("YYYY-MM-DD");
// if we don't have a log for today, we'll create an empty one
if (currentDay === lastLoggedDay) {
createLogForToday = false;
}
await addMilestonesToLogs(formattedLogs);
saveLogsToFile(formattedLogs);
}
if (createLogForToday && isLoggedIn()) {
// create a log for today and add it to the local logs
// await addDailyLog();
const log:Log = new Log();
log.day_number = getDayNumberForNewLog();
log.challenge_round = getCurrentChallengeRound();
await createLog(log);
}
}
// converts local log to format that server will accept
function prepareLogForServerUpdate(log: Log) {
const offset_seconds = new Date().getTimezoneOffset() * 60;
let preparedLog = {
...log,
minutes: log.codetime_metrics.hours * 60,
keystrokes: log.codetime_metrics.keystrokes,
lines_added: log.codetime_metrics.lines_added,
lines_removed: 0,
unix_date: moment(log.date).unix(),
local_date: moment(log.date).unix() - offset_seconds,
offset_minutes: offset_seconds / 60,
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
challenge_round: log.challenge_round || getCurrentChallengeRound()
};
return preparedLog;
}
function saveLogsToFile(logs: Array<Log> = []) {
const filePath = getLogFilePath();
try {
fs.writeFileSync(filePath, JSON.stringify(logs, null, 2));
} catch (err) {
console.log(err);
}
}
function getLocalLogsFromFile(): Array<Log> {
const filePath = getLogFilePath();
let logs: Array<Log> = [];
const exists = checkIfLocalFileExists(filePath);
if (exists) {
logs = getFileDataAsJson(filePath);
}
return logs || [];
}
export function getLogFilePath(): string {
return getFile("logs.json");
}
function checkIfLocalFileExists(filepath: string): boolean {
if (fs.existsSync(filepath)) {
return true;
} else {
return false;
}
}
// push new local logs to the server
async function pushNewLogToServer(log: {}) {
await softwarePost("/100doc/logs", [log], getItem("jwt"));
}
// push new local logs to the server
async function updateExistingLogOnServer(log: {}) {
await softwarePut("/100doc/logs", [log], getItem("jwt"));
}
// formats logs from the server into the local log model format before saving locally
// logs have a format like [ { day_number: 1, date: ... }, ... ]
function formatLogs(logs: Array<Log>) {
const formattedLogs: Array<Log> = [];
logs.forEach((log: any) => {
if (!log.codetime_metrics) {
log.codetime_metrics = new CodetimeMetrics();
}
if (!log.date) {
log.date = log.unix_date * 1000;
}
log.codetime_metrics.hours = log.minutes ? parseFloat((log.minutes / 60).toFixed(2)) : 0;
log.codetime_metrics.keystrokes = log.keystrokes;
log.codetime_metrics.lines_added = log.lines_added;
log.links = log.ref_links || [];
if (!log.challenge_round) {
log.challenge_round = getCurrentChallengeRound();
}
formattedLogs.push(log);
});
// sorts logs in descending order
formattedLogs.sort((a: Log, b: Log) => {
return b.day_number - a.day_number;
});
return formattedLogs;
}
// joins milestones to each log
async function addMilestonesToLogs(logs: Array<Log>) {
// fetch all the milestones at once and then add them to each log iteratively below
const milestoneData = getAllMilestones();
if (logs && milestoneData) {
const milestones = milestoneData.milestones;
for (let log of logs) {
const logMilestones = milestones.filter(n => n.day_number && n.day_number === log.day_number);
if (logMilestones) {
// extract the milestone ids
const milestoneIds = logMilestones.map(n => n.id);
log.milestones = Array.from(new Set(milestoneIds));
}
}
}
writeToLogsJson(logs);
} | the_stack |
import ServiceElectron from '../service.electron';
import Logger from '../../tools/env.logger';
import ServiceStreams from "../service.streams";
import MergeDiscover from '../../controllers/features/merge/merge.discover';
import MergeFormat from '../../controllers/features/merge/merge.format';
import TimestampExtract from '../../controllers/features/timestamp/timestamp.extract';
import ServiceTimestampFormatRecent from './service.timestamp.recent';
import { IPCMessages } from '../service.electron';
import { Subscription } from '../../tools/index';
import { IService } from '../../interfaces/interface.service';
import { dialog, SaveDialogReturnValue } from 'electron';
import * as fs from 'fs';
/**
* @class ServiceTimestamp
* @description Providers access to merge files functionality from render
*/
class ServiceTimestamp implements IService {
private _logger: Logger = new Logger('ServiceTimestamp');
private _subscriptions: { [key: string]: Subscription } = {};
private _tasks: Map<string, Map<string, MergeDiscover>> = new Map<string, Map<string, MergeDiscover>>();
/**
* Initialization function
* @returns Promise<void>
*/
public init(): Promise<void> {
return new Promise((resolve, reject) => {
Promise.all([
ServiceElectron.IPC.subscribe(IPCMessages.TimestampDiscoverRequest, this._onTimestampDiscoverRequest.bind(this)).then((subscription: Subscription) => {
this._subscriptions.TimestampDiscoverRequest = subscription;
}),
ServiceElectron.IPC.subscribe(IPCMessages.TimestampTestRequest, this._onTimestampTestRequest.bind(this)).then((subscription: Subscription) => {
this._subscriptions.TimestampTestRequest = subscription;
}),
ServiceElectron.IPC.subscribe(IPCMessages.TimestampExtractRequest, this._onTimestampExtractRequest.bind(this)).then((subscription: Subscription) => {
this._subscriptions.TimestampExtractRequest = subscription;
}),
ServiceElectron.IPC.subscribe(IPCMessages.TimestampExportCSVRequest, this._onTimestampExportCSVRequest.bind(this)).then((subscription: Subscription) => {
this._subscriptions.TimestampExportCSVRequest = subscription;
}),
]).then(() => {
this._subscriptions.onSessionClosed = ServiceStreams.getSubjects().onSessionClosed.subscribe(this._onSessionClosed.bind(this));
resolve();
}).catch((error: Error) => {
this._logger.error(`Fail to init module due error: ${error.message}`);
reject(error);
});
});
}
public destroy(): Promise<void> {
return new Promise((resolve) => {
Object.keys(this._subscriptions).forEach((key: string) => {
this._subscriptions[key].destroy();
});
resolve();
});
}
public getName(): string {
return 'ServiceTimestamp';
}
private _onTimestampDiscoverRequest(request: IPCMessages.TMessage, response: (instance: IPCMessages.TMessage) => any) {
const req: IPCMessages.TimestampDiscoverRequest = request as IPCMessages.TimestampDiscoverRequest;
const filedata: { streamId: string, file: string } | Error = ServiceStreams.getStreamFile(req.session);
if (filedata instanceof Error) {
return response(new IPCMessages.TimestampDiscoverResponse({
id: req.id,
error: filedata.message,
}));
}
fs.stat(filedata.file, (err: NodeJS.ErrnoException | null, stats: fs.Stats) => {
if (err) {
return response(new IPCMessages.TimestampDiscoverResponse({
id: req.id,
error: `Fail to get access to session file due error: ${err.message}`,
}));
}
if (stats.size === 0) {
return response(new IPCMessages.TimestampDiscoverResponse({
id: req.id,
error: `Session is empty`,
}));
}
const controller: MergeDiscover = new MergeDiscover([{ file: filedata.file }]);
controller.discover(undefined, true).then((processed: IPCMessages.IMergeFilesDiscoverResult[]) => {
if (processed[0].format === undefined || typeof processed[0].minTime !== 'number' || typeof processed[0].maxTime !== 'number') {
return response(new IPCMessages.TimestampDiscoverResponse({
id: req.id,
error: typeof processed[0].error !== 'string' ? `Fail to detect datetime format` : processed[0].error,
}));
}
response(new IPCMessages.TimestampDiscoverResponse({
id: req.id,
format: processed[0].format,
error: processed[0].error,
minTime: processed[0].minTime,
maxTime: processed[0].maxTime,
}));
}).catch((error: Error) => {
response(new IPCMessages.TimestampDiscoverResponse({
id: req.id,
error: error.message,
}));
}).finally(() => {
this._removeTask(req.signature, req.id);
});
// Store task
this._addTask(req.signature, req.id, controller);
});
}
private _onTimestampTestRequest(request: IPCMessages.TMessage, response: (instance: IPCMessages.TMessage) => any) {
const req: IPCMessages.TimestampTestRequest = request as IPCMessages.TimestampTestRequest;
const controller: MergeFormat = new MergeFormat(req.format);
controller.validate(req.flags).then((regexp: string) => {
if (regexp === undefined) {
response(new IPCMessages.TimestampTestResponse({
id: req.id,
error: `Fail to generate regexp based on "${req.format}" format string.`,
}));
} else {
response(new IPCMessages.TimestampTestResponse({
id: req.id,
format: {
regex: regexp,
flags: [],
format: req.format,
},
}));
}
}).catch((error: Error) => {
response(new IPCMessages.TimestampTestResponse({
id: req.id,
error: error.message,
}));
});
}
private _onTimestampExtractRequest(request: IPCMessages.TMessage, response: (instance: IPCMessages.TMessage) => any) {
const req: IPCMessages.TimestampExtractRequest = request as IPCMessages.TimestampExtractRequest;
const controller: TimestampExtract = new TimestampExtract(req.str, req.format);
controller.extract(req.replacements).then((timestamp: number) => {
if (timestamp === undefined) {
response(new IPCMessages.TimestampExtractResponse({
id: req.id,
error: `Fail to extract timestamp based on "${req.format}" format string.`,
}));
} else {
response(new IPCMessages.TimestampExtractResponse({
id: req.id,
timestamp: timestamp,
}));
}
}).catch((error: Error) => {
response(new IPCMessages.TimestampExtractResponse({
id: req.id,
error: error.message,
}));
});
}
private _onTimestampExportCSVRequest(request: IPCMessages.TMessage, response: (instance: IPCMessages.TMessage) => any) {
const req: IPCMessages.TimestampExportCSVRequest = request as IPCMessages.TimestampExportCSVRequest;
dialog.showSaveDialog({
title: 'Saving filters',
filters: [{ name: 'CSV Files', extensions: ['csv']}],
}).then((results: SaveDialogReturnValue) => {
if (typeof results.filePath !== 'string' || results.filePath.trim() === '') {
return response(new IPCMessages.TimestampExportCSVResponse({
id: req.id,
}));
}
fs.writeFile(results.filePath, req.csv, (error: NodeJS.ErrnoException | null) => {
if (error) {
response(new IPCMessages.TimestampExportCSVResponse({
id: req.id,
error: error.message,
}));
} else {
response(new IPCMessages.TimestampExportCSVResponse({
id: req.id,
}));
}
});
});
}
private _addTask(session: string, taskId: string, controller: MergeDiscover) {
const storage: Map<string, MergeDiscover> | undefined = this._tasks.get(session);
if (storage === undefined) {
this._tasks.set(session, new Map([[taskId, controller]]));
} else {
storage.set(taskId, controller);
this._tasks.set(session, storage);
}
}
private _removeTask(session: string, taskId: string) {
const storage: Map<string, MergeDiscover> | undefined = this._tasks.get(session);
if (storage !== undefined) {
storage.delete(taskId);
this._tasks.set(session, storage);
}
}
private _onSessionClosed(guid: string) {
const storage: Map<string, MergeDiscover> | undefined = this._tasks.get(guid);
if (storage !== undefined) {
storage.forEach((controller: MergeDiscover, id: string) => {
controller.abort().then(() => {
this._logger.debug(`Task "${id}" is aborted`);
});
});
this._tasks.delete(guid);
}
}
}
export default (new ServiceTimestamp()); | the_stack |
import * as repl from 'repl';
import * as vm from 'vm';
import * as path from 'path';
import { sendMessage } from './comms';
import { logErrorMessage, logMessage } from './logger';
import { CodeObject, Configuration, DisplayData, RunCellRequest, RunCellResponse } from './types';
import { VariableListingMagicCommandHandler } from './magics/variables';
import { formatImage, formatValue } from './extensions/format';
import { DanfoJsFormatter } from './extensions/danfoFormatter';
import { TensorflowJsVisualizer } from './extensions/tfjsVisProxy';
import { Plotly } from './extensions/plotly';
import { init as injectTslib } from '../../../resources/scripts/tslib';
import { register as registerTsNode } from './tsnode';
import { noop } from '../coreUtils';
import { createConsoleOutputCompletedMarker } from '../const';
import { DanfoNodePlotter } from './extensions/danforPlotter';
import { ArqueroFormatter } from './extensions/arqueroFormatter';
import { ReadLineProxy } from './extensions/readLineProxy';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const Module = require('module');
let replServer: repl.REPLServer;
let configuration: Configuration | undefined;
class Utils {
private static _instance: Utils;
public static get instance() {
if (Utils._instance) {
return Utils._instance;
}
return (Utils._instance = new Utils());
}
public static get requestId() {
return Utils._requestId;
}
public static set requestId(value: string) {
if (value !== Utils._requestId) {
// Start a new chain of promises.
Utils.pendingDisplayUpdates = Promise.resolve();
}
Utils._requestId = value;
}
private static _requestId = '';
public static get updatesSent() {
return Utils.pendingDisplayUpdates.catch(() => noop()).then(() => noop());
}
private static pendingDisplayUpdates = Promise.resolve();
public readonly Plotly = Plotly;
public readonly display = {
html: this.displayHtml.bind(this),
json: this.displayJson.bind(this),
image: this.displayImage.bind(this),
appendImage: this.displayImage.bind(this),
gif: this.displayImage.bind(this),
jpeg: this.displayImage.bind(this),
png: this.displayImage.bind(this),
svg: this.displayImage.bind(this),
javascript: (script: string) =>
this.notifyDisplay({
type: 'html',
value: `<script type='text/javascript'>${script}</script>`,
requestId: Utils.requestId
}),
latex: noop,
markdown: (value: string) => this.notifyDisplay({ type: 'markdown', value, requestId: Utils.requestId }),
text: (value: string | Uint8Array) =>
this.notifyDisplay({ type: 'text', value: value.toString(), requestId: Utils.requestId })
};
public displayHtml(html: string) {
this.notifyDisplay({ type: 'html', value: html, requestId: Utils.requestId });
}
public displayImage(image: string | Buffer | Uint8Array) {
const promise = formatImage(image, Utils.requestId).then((data) => (data ? this.notifyDisplay(data) : noop()));
Utils.pendingDisplayUpdates = Utils.pendingDisplayUpdates.finally(() => promise);
}
// eslint-disable-next-line @typescript-eslint/ban-types
public displayJson(json: string | Object) {
this.notifyDisplay({
type: 'json',
value: typeof json === 'string' ? JSON.parse(json) : json,
requestId: Utils.requestId
});
}
private notifyDisplay(data: DisplayData) {
sendMessage({
type: 'output',
requestId: data.requestId || Utils.requestId,
data
});
}
}
let initialized = false;
export function initialize(config?: Configuration) {
if (initialized) {
return;
}
initialized = true;
configuration = config;
startRepl();
}
function startRepl() {
replServer = repl.start({
prompt: '',
eval: replEvalCode,
ignoreUndefined: true,
terminal: true,
useColors: true,
useGlobal: true
});
// replServer.context.$$ = Utils.instance;
injectTslib(replServer.context);
if (configuration?.registerTsNode === true) {
logMessage('tsNode registered');
registerTsNode(replServer.context);
}
// This way we have `__dirname`.
replServer.context.__dirname = process.cwd();
return replServer;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function runCode(
code: string | CodeObject,
mode: 'userCode' | 'silent' = 'userCode'
): Promise<{ start: number; result: any; end: number }> {
const source = typeof code === 'string' ? code : code.code;
logMessage(mode === 'userCode' ? `Executing ${source}` : `Executing Silently ${source}`);
// First check if we have valid JS code.
try {
new vm.Script(source);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (ex: any) {
logErrorMessage('Unrecoverable error', ex);
const newError = new Error(ex.message || '<Unknown error in creating ScriptObject>');
newError.name = 'InvalidCode_CodeExecution';
throw newError;
}
try {
const start = Date.now();
const fileName = typeof code === 'object' ? code.sourceFilename : undefined;
replServer.context.__filename = path.join(process.cwd(), `__exec.js`);
const result = await vm.runInNewContext(source, replServer.context, {
displayErrors: true,
filename: fileName
});
const end = Date.now();
// Found that sometimes if the code runs very quickly `runInNewContext` completes even before we get output.
// Not much we can do about that, but adding this comment so we're aware of that.
return { start, end, result };
} catch (ex) {
logErrorMessage('Unrecoverable error', ex);
throw ex;
}
}
async function replEvalCode(code, _context, _filename, _callback) {
return runCode(code);
}
const magics = [new VariableListingMagicCommandHandler()];
export async function execCode(request: RunCellRequest): Promise<void> {
Utils.requestId = request.requestId;
Plotly.requestId = request.requestId;
DanfoJsFormatter.requestId = request.requestId;
TensorflowJsVisualizer.requestId = request.requestId;
DanfoNodePlotter.requestId = request.requestId;
for (const magicHandler of magics) {
if (magicHandler.isMagicCommand(request)) {
try {
await magicHandler.handleCommand(request, replServer);
} finally {
console.log(createConsoleOutputCompletedMarker(request.requestId));
}
return;
}
}
const start = Date.now();
try {
const { start, end, result } = await runCode(request.code);
// Wait till we send all UI updates to extension before returning from here..
await Utils.updatesSent;
// Now its possible as part of the execution, some data was written to the console.
// Sometimes those messages written to the console get dispayed in the output after
// the last result (the value `result` below).
// E.g. assuem we have a cell as follows:
//
// var a = 1234;
// console.log('Hello World')
// a
//
// Since the variable `a` is the last line, just like in a repl, the value will be printed out.
// However, when we monitor output of the process, its possible that comes a little later (depends on when the buffer is flushed).
// Hence its possible we'd see `1234\nHello World`, i.e. things in reverse order.
// As a solution, we'll send a console.log<Special GUID><ExecutionCount>, if we see that, then we know we're ready to display messages
// received from kernel (i.e. displaying the value of the last line).
console.log(createConsoleOutputCompletedMarker(request.requestId));
// Or another solution is to send the value of the last line (last expression)
// as an output on console.log
// But the problem with that is, this console.log could end up in the output of the next cell.
const execResult: RunCellResponse = {
requestId: request.requestId,
success: true,
result: await formatValue(result, request.requestId),
type: 'cellExec',
start,
end
};
sendMessage(execResult);
} catch (ex) {
console.log(createConsoleOutputCompletedMarker(request.requestId));
const err = ex as Partial<Error> | undefined;
const execResult: RunCellResponse = {
requestId: request.requestId,
success: false,
ex: { name: err?.name || 'unknown', message: err?.message || 'unknown', stack: err?.stack },
type: 'cellExec',
start,
end: Date.now()
};
sendMessage(execResult);
}
}
// let injectedCustomTFLogger = false;
// /**
// * We are only interested in printing the current progress,
// * We don't care about the previous epochs (they take space).
// * User can use the GUID as a place holder to determine where the progress really started
// */
// function customTfjsProgressLogger(message: string) {
// console.log(message);
// // console.log(`49ed1433-2c77-4180-bdfc-922704829871${message}`);
// }
// function injectCustomProgress() {
// if (injectedCustomTFLogger) {
// return;
// }
// try {
// const { progressBarHelper } = vm.runInNewContext(
// "require('@tensorflow/tfjs-node/dist/callbacks')",
// replServer.context,
// {
// displayErrors: false
// }
// );
// if (progressBarHelper.log !== customTfjsProgressLogger) {
// // For some reason, when training in tensforflow, we get empty lines from the process.
// // Some code in tfjs is writing empty lines into console window. no idea where.
// // Even if logging is disabled, we get them.
// // This results in ugly long empty oututs.
// // Solution, swallow this new lines.
// try {
// const tf = vm.runInNewContext("require('@tensorflow/tfjs')", replServer.context, {
// displayErrors: false
// }) as typeof import('@tensorflow/tfjs');
// class CustomLogger extends tf.CustomCallback {
// constructor() {
// super({
// onTrainBegin: (_) => console.log('d1786f7c-d2ed-4a27-bd8a-ce19f704d4d0'),
// onTrainEnd: () => console.log('1f3dd592-7812-4461-b82c-3573643840ed')
// });
// }
// }
// tf.registerCallbackConstructor(1, CustomLogger);
// } catch (ex) {
// console.error('Failed to inject custom tensorflow logger to swallow empty lines', ex);
// }
// progressBarHelper.log = customTfjsProgressLogger;
// }
// } catch (ex) {
// injectedCustomTFLogger = true;
// console.error('Failed to inject custom tensorflow progress bar', ex);
// }
// }
const originalLoad = Module._load;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Module._load = function (request: any, parent: any) {
if (
parent &&
request === '@tensorflow/tfjs-core' &&
parent.filename &&
parent.filename.includes('@tensorflow/tfjs-vis') &&
!parent.filename.includes('@tensorflow/tfjs-vis/dist/util/math')
) {
return {};
}
if (request === 'node-kernel') {
return Utils.instance;
}
if (request === '@tensorflow/tfjs-vis') {
const tfMath = vm.runInNewContext("require('@tensorflow/tfjs-vis/dist/util/math');", replServer.context, {
displayErrors: false
});
const tfCore = vm.runInNewContext("require('@tensorflow/tfjs-core');", replServer.context, {
displayErrors: false
});
return TensorflowJsVisualizer.initialize(tfCore, tfMath);
}
// eslint-disable-next-line prefer-rest-params
const result = originalLoad.apply(this, arguments);
if (request === 'readline') {
ReadLineProxy.initialize(result);
}
if (request === 'danfojs-node') {
DanfoJsFormatter.initialize(result);
}
if (request === 'arquero') {
ArqueroFormatter.initialize(result);
}
return result;
}; | the_stack |
declare namespace smarthome {
namespace IntentFlow {
interface ScanData {
/** Contains data if this result came from a BLE scan. */
bleScanData?: BleScanData;
/** Contains data if this result came from an mDNS scan. */
mdnsScanData?: MdnsScanData;
/** Contains data if this result came from a UDP scan. */
udpScanData?: UdpScanData;
/** Contains data if this result came from a UPnP scan. */
upnpScanData?: UpnpScanData;
}
/**
* Results provided from a device scan on the local network.
*/
interface DeviceScanData {
/** List of radio interfaces used during the scan. */
radioTypes: Constants.RadioType[];
/** Contains data if this result came from a BLE scan. */
bleData?: BleScanData;
/** Contains data if this result came from an mDNS scan. */
mdnsScanData?: MdnsScanData;
/** Contains data if this result came from a UDP scan. */
udpScanData?: UdpScanData;
/** Contains data if this result came from a UPnP scan. */
upnpScanData?: UpnpScanData;
}
}
namespace DataFlow {
/**
* Generic command request object that can be used in function signatures
* that work with command objects in a generic way.
*/
type CommandRequest =
BleRequestData|HttpRequestData|TcpRequestData|UdpRequestData;
/**
* Generic command response object that can be used in function signatures
* that work with command objects in a generic way.
*/
type CommandResponse =
BleResponseData|HttpResponseData|TcpResponseData|UdpResponseData;
}
/** Generic Intent request. Used in API signatures that accept any intent. */
type IntentRequest =
IntentFlow.EventRequest|IntentFlow.ExecuteRequest|
IntentFlow.IdentifyRequest|IntentFlow.IndicateRequest|
IntentFlow.ParseNotificationRequest|IntentFlow.ProvisionRequest|
IntentFlow.ProxySelectedRequest|IntentFlow.QueryRequest|
IntentFlow.ReachableDevicesRequest|IntentFlow.RegisterRequest|
IntentFlow.UnprovisionRequest|IntentFlow.UpdateRequest;
/** Generic Intent response. Used in API signatures that accept any intent. */
type IntentResponse =
IntentFlow.EventResponse|IntentFlow.ExecuteResponse|
IntentFlow.IdentifyResponse|IntentFlow.IndicateResponse|
IntentFlow.ParseNotificationResponse|
IntentFlow.ProvisionResponse|IntentFlow.ProxySelectedResponse|
IntentFlow.QueryResponse|IntentFlow.ReachableDevicesResponse|
IntentFlow.RegisterResponse|IntentFlow.UnprovisionResponse|
IntentFlow.UpdateResponse;
type FilterFunc = (commandResponse: DataFlow.CommandSuccess) => boolean;
type TransformFunc = (commandResponse: DataFlow.CommandSuccess) => unknown;
/**
* Notification options. Either timeout or n must be specified.
* n: Number of notifications needed by the app to complete a specific op.
* timeout: Timeout in ms, after which the SDK will stop collecting
* notifications.
* filterFunc: Interested in notifications that match this filter.
* transformFunc: Transform each notification packet and return transformed
* object. If transformFunc is not used, the promise is resolved with
* DataFlow.CommandSuccess.
*/
interface NotificationOptions {
n?: number;
timeout?: number;
filterFunc?: FilterFunc;
transformFunc?: TransformFunc;
}
/**
* This class provides access to the devices managed by the local home
* platform. Applications can use this interface to send and receive commands
* with a locally identified device using the [[send]] method.
*
* ```typescript
* localHomeApp.getDeviceManager()
* .send(deviceCommand)
* .then((result) => {
* // Handle command success
* })
* .catch((err: IntentFlow.HandlerError) => {
* // Handle command error
* });
* ```
*
*/
interface DeviceManager {
/**
* `send` is called by app when it needs to communicate with a device.
* Depending upon the protocol used by the device, the app constructs a
* [[DataFlow.CommandRequest]] object and passes it as an argument.
* Returns a promise that resolves to [[DataFlow.CommandSuccess]]. Response
* may return data, if it was a read request.
*
* See also [[BleRequestData]], [[HttpRequestData]], [[TcpRequestData]],
* [[UdpRequestData]]
*
* @param command Command to communicate with the device.
* @param sendOptions Options for `send` API. See [[SendOptions]].
* @return Promise that resolves to [[DataFlow.CommandSuccess]]
*/
send(command: DataFlow.CommandRequest, sendOptions?: SendOptions):
Promise<DataFlow.CommandSuccess>;
/**
* `sendAndWait` allows the app to wait for notification in the same
* promise chain. But if the app uses a transformFunc, the resolved result
* could be anything. If transformFunc is not specified, the promise will be
* resolved with DataFlow.CommandSuccess type.
*
* @param command Command to communicate with the device.
* @param options Options for `sendAndWait` API. See
* [[NotificationOptions]].
* @return Promise that resolves to anything. It resolves to
* [[DataFlow.CommandSuccess]] if transformFunc is not specified in
* options.
*/
sendAndWait(command: DataFlow.CommandRequest, options: NotificationOptions):
Promise<unknown|DataFlow.CommandSuccess>;
/**
* `markPending` is called by the app when app is done handling an intent,
* but the actual operation (usually EXECUTE command) is still not done.
* This enables Google Home to respond back to the user in a timely fashion.
* This may be useful for somewhat long running operations. Returns a
* promise.
* @param request Original intent request that should be marked pending.
* @param response Pending response to the intent request.
*/
markPending(request: IntentRequest, response?: IntentResponse):
Promise<void>;
/**
* `getProxyInfo` is called by app to get information about the hub / bridge
* controlling this end-device.
* @param id Device ID of end device that is being controlled by the hub.
*/
getProxyInfo(id: string): ProxyInfo;
/**
* Returns the list of registered devices.
*/
getRegisteredDevices(): IntentFlow.RegisteredDevice[];
/**
* `reportState` is called by app to report the changed state for the
* device. In the case of BLE Seamless Setup, it should be called whenever
* the app receives a BLE notification in [[ParseNotificationHandler]].
* @param state the latest state of the device
*/
reportState(state: ReportState.Response.Payload): undefined;
}
/**
* This class is the main entry point for your app in the local home platform.
* Use the [[App]] class to register callback handlers for [[Intents]] and
* to listen for new events.
*
* ```typescript
* import App = smarthome.App;
*
* const localHomeApp: App = new App("1.0.0");
* localHomeApp
* .onIdentify(identifyHandler)
* .onExecute(executeHandler)
* .listen()
* .then(() => console.log("Ready"));
* ```
*
*/
class App {
constructor(version: string);
/**
* `getDeviceManager` is called by app to get the reference to the singleton
* DeviceManager object.
* @return [[DeviceManager]]
*/
getDeviceManager(): DeviceManager;
/**
* `listen` is called by app when the app is ready to handle the intents.
*/
listen(): Promise<void>;
/**
* `on` is called by app to attach the handler for generic events specified
* in [[Constants.EventType]]
* @param eventType The generic event type the hanlers
* @param handler The handler that handles the intent.
*/
on(eventType: Constants.EventType, handler: IntentFlow.EventHandler): this;
/**
* `onExecute` is called by app to attach the handler for EXECUTE intent.
* @param handler The handler that handles EXECUTE intent.
*/
onExecute(handler: IntentFlow.ExecuteHandler): this;
/**
* `onIdentify` is called by app to attach the handler for IDENTIFY intent.
* @param handler The handler that handles IDENTIFY intent.
*/
onIdentify(handler: IntentFlow.IdentifyHandler): this;
/**
* `onIndicate` is called by app to attach the handler for INDICATE intent.
* @param handler The handler that handles INDICATE intent.
*/
onIndicate(handler: IntentFlow.IndicateHandler): this;
/**
* `onParseNotification` is called by app to attach the handler for
* PARSE_NOTIFICATION intent.
* @param handler The handler that handles PARSE_NOTIFICATION intent.
*/
onParseNotification(handler: IntentFlow.ParseNotificationHandler): this;
/**
* `onProvision` is called by app to attach the handler for PROVISION
* intent.
* @param handler The handler that handles PROVISION intent.
*/
onProvision(handler: IntentFlow.ProvisionHandler): this;
/**
* `onProxySelected` is called by app to attach the handler for
* PROXY_SELECTED intent.
* @param handler The handler that handles PROXY_SELECTED intent.
*/
onProxySelected(handler: IntentFlow.ProxySelectedHandler): this;
/**
* `onQuery` is called by app to attach the handler for QUERY intent.
* @param handler The handler that handles QUERY intent.
*/
onQuery(handler: IntentFlow.QueryHandler): this;
/**
* `onReachableDevices` is called by app to attach the handler for
* REACHABLE_DEVICES intent.
* @param handler The handler that handles REACHABLE_DEVICES intent.
*/
onReachableDevices(handler: IntentFlow.ReachableDevicesHandler): this;
/**
* `onRegister` is called by app to attach the handler for REGISTER intent.
* @param handler The handler that handles REGISTER intent.
*/
onRegister(handler: IntentFlow.RegisterHandler): this;
/**
* `onUnprovision` is called by app to attach the handler for UNPROVISION
* intent.
* @param handler The handler that handles UNPROVISION intent.
*/
onUnprovision(handler: IntentFlow.UnprovisionHandler): this;
/**
* `onUpdate` is called by app to attach the handler for UPDATE intent.
* @param handler The handler that handles UPDATE intent.
*
* @hidden since currently OTA is not available for developers yet
*/
onUpdate(handler: IntentFlow.UpdateHandler): this;
}
} | the_stack |
import {
Field,
FieldType,
ListModel,
Model,
Node,
NodeType, normalizeModel,
ObjectMapModel,
Path,
StringMapModel,
TreeModel
} from './model';
import {
Format, RootSchemaElement, SchemaElement, SchemaPatternProperty, SchemaProperties, schemaVersion,
Type
} from "./schema";
export const getNodeType = (node: Node<Model>): NodeType => {
return node.model.type;
};
export const getFieldAt = (node: Node<Model>, fieldIndex: number): Field => {
return node.model.getFieldAt(fieldIndex);
};
export const getFieldNamed = (node: Node<Model>, name: string): Field => {
return node.model.getFieldNamed(name);
};
export const getFieldIndex = (node: Node<Model>, field: Field) => {
field = getField(field);
const fields = getFields(node);
for (let i = 0; i < fields.length; i++) {
const f = fields[i];
if (field.name === f.name) {
return i;
}
}
throw new Error(`Cannot find fieldIndex for field ${field.name} in node ${node.model.name}`);
};
export const getField = (f: any): Field => {
return typeof f === 'string' ? {name: f} : f;
};
export const getFields = (node: Node<Model>): Field[] => {
return node.model.fields;
};
export const isMapType = (node: Node<Model>): boolean => {
return node.model.isMap();
};
export const isKeyField = (field: Field): boolean => {
return field.key;
};
export const getKeyField = (model : ObjectMapModel | StringMapModel) : Field => {
return model.fields.find(f => f.key)!;
};
export const getValueField = (model : StringMapModel) : Field => {
return model.fields.find(f => !f.key)!;
};
export const findNode = (node: Node<Model>, path: any) => {
if (path === '') {
return node;
}
if (typeof path === 'string') {
path = path.split('/');
}
return _findNode(node, path);
};
export const getChildren = (node: Node<TreeModel>): Node<Model>[] => {
return node.model.children.map(modelChild => {
let childPath = (node.path ? (node.path + '/') : '') + slugify(modelChild.name);
return {
model: modelChild,
schema: node.schema.properties![slugify(modelChild.name)],
data: node.data[slugify(modelChild.name)],
parent: node,
path: childPath,
treePath: childPath,
fieldIndex: -1,
dataIndex: -1
};
});
};
export const deleteNode = (node: Node<Model>): void => {
const parentNode = node.parent!;
const modelChildren = (<TreeModel> parentNode.model).children!;
for (let i = 0; i < modelChildren.length; i++) {
const modelChild = modelChildren[i];
if (modelChild.name === node.model.name) {
modelChildren.splice(i, 1);
delete parentNode.schema.properties![slugify(node.model.name)];
delete parentNode.data[slugify(node.model.name)];
return;
}
}
throw new Error(`Could not delete node '${node.model.name}'`);
};
/**
* Removes the last path fragment if it is a number
* /foo/bar/5 => /foo/bar
*
* @param tree
* @param path
* @returns {*}
*/
export const treePathAndIndex = (tree: Node<Model>, path: string): Path => {
return _treePathAndIndex(tree, path === '' ? [] : path.split('/'), {
fullPath: path,
treePath: '',
dataIndex: -1
});
};
const _treePathAndIndex = (node: Node<Model>, path: string[], result: Path): Path => {
if (path.length > 0) {
const p = path[0];
const nodeType = getNodeType(node);
switch (nodeType) {
case NodeType.TYPE_TREE:
result.treePath = result.treePath === '' ? p : (result.treePath + '/' + p);
_treePathAndIndex(_findChild(<Node<TreeModel>> node, p), path.slice(1), result);
break;
case NodeType.TYPE_LIST_OBJECT:
result.dataIndex = parseInt(p);
break;
case NodeType.TYPE_MAP_OBJECT:
case NodeType.TYPE_MAP_STRING:
result.dataIndex = p;
break;
}
}
return result;
};
const _findChild = (node: Node<TreeModel>, slug: string): Node<Model> => {
if (getNodeType(node) === NodeType.TYPE_TREE) {
for (let i = 0; i < node.model.children.length; i++) {
if (slugify(node.model.children[i].name) === slug) {
let childPath = node.path + '/' + slug;
return {
model: node.model.children[i],
schema: node.schema.properties![slug],
data: node.data[slug],
parent: node,
path: childPath,
treePath: childPath,
fieldIndex: -1,
dataIndex: -1
};
}
}
}
throw new Error(`Could not find child with slug ${slug} in node ${node.model.name}`);
};
export const getDataItems = (node: Node<Model>): any[] => {
switch (getNodeType(node)) {
case NodeType.TYPE_LIST_OBJECT:
return node.data;
case NodeType.TYPE_TREE:
return [ node.data ];
case NodeType.TYPE_MAP_OBJECT:
case NodeType.TYPE_MAP_STRING:
return Object.values(node.data);
default:
throw new Error("Cannot list items for type: " + node.model.type);
}
};
const _findNewListItemName = (node: Node<Model>, newName: string, idx: number): string => {
const fullName = (idx === 1) ? newName : (newName + " (" + idx + ")");
const fieldName = defaultFieldName(node.model);
const items = getDataItems(node);
for (let i = 0; i < items.length; i++) {
let item = items[i];
let name = item[fieldName];
if (name === fullName) {
return _findNewListItemName(node, newName, idx + 1);
}
}
return fullName;
};
const _findNewMapKey = (node: Node<Model>, newName: string, idx: number) => {
const fullName = (idx === 1) ? newName : (newName + " (" + idx + ")");
if (typeof node.data[fullName] !== 'undefined') {
return _findNewMapKey(node, newName, idx + 1);
}
return fullName;
};
const _findNewNodeName = (node: Node<TreeModel>, newName: string, idx: number): string => {
const fullName = (idx === 1) ? newName : (newName + " (" + idx + ")");
const children = node.model.children;
if (children) {
for (let i = 0; i < children.length; i++) {
let child = children[i];
let name = child["name"];
if (name === fullName) {
return _findNewNodeName(node, newName, idx + 1);
}
}
}
return fullName;
};
export const addItem = (node: Node<Model>, requestedName: string) => {
const nodeType = getNodeType(node);
let item;
let dataIndex;
switch (nodeType) {
case NodeType.TYPE_MAP_OBJECT:
item = {};
dataIndex = _findNewMapKey(node, requestedName, 1);
node.data[dataIndex] = item;
break;
case NodeType.TYPE_MAP_STRING:
item = "New value";
dataIndex = _findNewMapKey(node, requestedName, 1);
node.data[dataIndex] = item;
break;
case NodeType.TYPE_LIST_OBJECT:
item = {
[defaultFieldName(node.model)]: _findNewListItemName(node, requestedName, 1)
};
node.data.push(item);
dataIndex = node.data.length - 1;
break;
default:
throw new Error(`Cannot add item to node of type ${nodeType}`);
}
return {dataIndex, item};
};
export const addNode = (node: Node<TreeModel>, requestedName: string, nodeType: NodeType): Node<Model> => {
const newName = _findNewNodeName(node, requestedName, 1);
let newData;
let newModel;
switch (nodeType) {
case NodeType.TYPE_TREE:
newModel = new TreeModel(newName, [], []);
newData = {};
break;
case NodeType.TYPE_MAP_OBJECT:
newModel = new ObjectMapModel(newName, [ new Field("Key", FieldType.String, true) ]);
newData = {};
break;
case NodeType.TYPE_MAP_STRING:
newModel = new StringMapModel(newName, [
new Field("Key", FieldType.String, true),
new Field("Value", FieldType.String)
]);
newData = {};
break;
case NodeType.TYPE_LIST_OBJECT:
newModel = new ListModel(newName, [ new Field("Name", FieldType.String) ]);
newData = [];
break;
}
node.model.children.push(newModel);
node.schema.properties![slugify(newModel.name)] = _modelToSchema(newModel);
node.data[slugify(newModel.name)] = newData;
let path = node.path + '/' + slugify(newModel.name);
return Object.assign(
{},
node,
{
model: newModel,
data: newData,
path: path,
treePath: path,
parent: node,
dataIndex: -1
}
);
};
/**
* Get the node holding the 'struct' data: either this node, or its parent, if the data held
* is an 'item' (from a map or an array)
*/
const _getStructNode = (node : Node<Model>) : Node<Model> => {
if (node.dataIndex !== -1) {
return node.parent!;
}
return node;
};
export const renameNode = function (node: Node<Model>, name: string) : void {
const previousName = node.model.name;
node.model.name = name;
node.schema.title = name;
if (node.parent) {
node.parent.data[slugify(name)] = node.parent.data[slugify(previousName)];
const schema = node.parent.schema.properties![slugify(previousName)];
delete node.parent.schema.properties![slugify(previousName)];
node.parent.schema.properties![slugify(name)] = schema;
node.path = node.parent.path ? (node.parent.path + '/' + slugify(name)) : slugify(name);
node.treePath = node.path;
delete node.parent.data[slugify(previousName)];
}
};
const _checkDeleteFieldAt = (node : Node<Model>, fieldIndex: number) : Field => {
const field = getFieldAt(node, fieldIndex);
if (field.key) {
throw new Error(`Cannot delete: field ${field.name} is a key field for node '${node.model.name}'`);
}
const nodeType = getNodeType(node);
if (nodeType === NodeType.TYPE_MAP_STRING) {
throw new Error(`Cannot delete: field ${field.name} is the value field for node '${node.model.name}', which is a map(string)`);
}
return field;
};
export const canDeleteFieldAt = (node : Node<Model>, fieldIndex : number) : boolean => {
try {
_checkDeleteFieldAt(node, fieldIndex);
} catch (err) {
return false;
}
return true;
};
export const deleteFieldAt = (node : Node<Model>, fieldIndex : number) : void => {
const field = _checkDeleteFieldAt(node, fieldIndex);
const structNode = _getStructNode(node);
if (isItem(structNode)) {
getDataItems(structNode).forEach(item => delete item[slugify(field.name)]);
} else {
delete node.data[slugify(field.name)];
}
node.model.fields.splice(fieldIndex, 1);
delete getFieldHolder(node).properties![slugify(field.name)];
};
const getFieldHolder = (node: Node<Model>) : SchemaElement => {
let nodeType = getNodeType(node);
switch (nodeType) {
case NodeType.TYPE_LIST_OBJECT:
return node.schema.items!;
case NodeType.TYPE_MAP_OBJECT:
case NodeType.TYPE_MAP_STRING:
return node.schema.patternProperties!['.+']!;
case NodeType.TYPE_TREE:
return node.schema;
}
};
export const setValue = (node: Node<Model>, field : Field, value : any) : void => {
node.data[slugify(field.name)] = value;
};
export const updateFieldAt = (node : Node<Model>, fieldIndex : number, field : Field) => {
let fieldHolder = getFieldHolder(node);
if (typeof fieldIndex === 'undefined' || fieldIndex === -1) {
// The field does not exist, just compute the new model index
fieldIndex = node.model.fields.length;
fieldHolder.properties![slugify(field.name)] = fieldToProperty(field);
} else {
// Field exists already, we need to perform a data refactoring
const newField = getField(field);
const prevField = getField(node.model.fields[fieldIndex]);
const structNode = _getStructNode(node);
const nodeType = getNodeType(structNode);
if (newField.name !== prevField.name
&& [NodeType.TYPE_LIST_OBJECT, NodeType.TYPE_MAP_OBJECT, NodeType.TYPE_TREE].includes(nodeType)
&& !newField.key) {
getDataItems(structNode).forEach(item => {
item[slugify(newField.name)] = item[slugify(prevField.name)];
delete item[slugify(prevField.name)];
});
}
if (newField.type !== prevField.type) {
getDataItems(structNode).forEach(item => {
item[slugify(newField.name)] = _convert(item[slugify(newField.name)], prevField.type, newField.type);
});
}
if (newField.key) {
(fieldHolder as SchemaPatternProperty).keyTitle = newField.name;
} else if (nodeType === NodeType.TYPE_MAP_STRING) {
(fieldHolder as SchemaPatternProperty).valueTitle = newField.name;
} else {
delete fieldHolder.properties![slugify(prevField.name)];
fieldHolder.properties![slugify(newField.name)] = fieldToProperty(newField);
}
}
// Update the model
node.model.fields[fieldIndex] = field;
};
const _convert = (value : any, prevFieldType : FieldType, newFieldType : FieldType) : any => {
switch (newFieldType) {
case FieldType.String:
case FieldType.Markdown:
case FieldType.TextArea:
case FieldType.Html:
return value ? "" + value : "";
case FieldType.Boolean:
return !!value;
case FieldType.Number:
return parseInt(value);
case FieldType.Array:
return [value];
default:
throw new Error(`Unknown type: ${newFieldType}`);
}
};
export const findDeepest = (data : any, path : string) => _findDeepest(data, ensureArray(path), 0);
const _findDeepest = (data : any, path : string, depth : number) => {
const found = data[path[0]];
if (found) {
return _findDeepest(found, path.slice(1), depth + 1);
} else {
return {node: data, depth: depth};
}
};
const _findNode = (node : Node<Model>, path : string[]) : Node<Model> => {
const nodeType = getNodeType(node);
if (path.length === 0) {
return node;
}
const next = path[0];
if (nodeType === NodeType.TYPE_TREE) {
const parentModel : TreeModel = <TreeModel> node.model;
for (let c = 0; c < parentModel.children.length; c++) {
const childModel = parentModel.children[c];
if (slugify(childModel.name) === next) {
let treePath = (node.path ? (node.path + '/') : '') + next;
return _findNode({
model: childModel,
schema: node.schema.properties![next],
data: node.data[next] || (childModel.type === NodeType.TYPE_LIST_OBJECT ? [] : {}),
parent: <Node<TreeModel>> node,
path: treePath,
treePath: treePath,
fieldIndex: -1,
dataIndex: -1
}, path.slice(1));
}
}
throw new Error(`Could not find child named ${next} in node ${node.model.name}`);
} else if (nodeType === NodeType.TYPE_LIST_OBJECT) {
const dataIndex = parseInt(next);
return {
model: node.model,
schema: node.schema,
data: node.data[dataIndex] || {},
parent: <Node<TreeModel>> node,
path: (node.path ? (node.path + '/') : '') + next,
treePath: node.path,
dataIndex: dataIndex,
fieldIndex: -1
};
} else {
// Map
return {
model: node.model,
schema: node.schema,
data: node.data[next] || (nodeType === NodeType.TYPE_MAP_OBJECT ? {} : ""),
parent: <Node<TreeModel>> node,
path: (node.path ? (node.path + '/') : '') + next,
treePath: node.path,
dataIndex: next,
fieldIndex: -1
};
}
};
export const defaultFieldName = (model : Model) => {
return slugify(model.fields[0].name);
};
export const fieldName = (field : Field) : string => slugify(field.name);
export const fieldDisplayName = (field : Field) : string => field.name;
export const slugify = (str : string) : string => str.replace(/\s/g, '_').replace(/\//g, '-').toLowerCase();
export const isItem = (node) => {
return node.model.isItem();
};
const ensureArray = path => typeof path === 'string' ? path.split('/') : path;
export const modelToSchema = (model): RootSchemaElement => {
const root = _modelToSchema(normalizeModel(model));
return Object.assign({} as RootSchemaElement, { $schema: schemaVersion }, root);
};
export const _modelToSchema = (model: Model): SchemaElement => {
const element: SchemaElement = {type: Type.TObject, properties: {} };
element.title = model.name;
if (model.type === NodeType.TYPE_TREE) {
const treeModel: TreeModel = model as TreeModel;
treeModel.children.forEach(child => {
const property = slugify(child.name);
if (!element.properties) {
element.properties = {};
}
element.properties[property] = _modelToSchema(child);
});
}
if (model.fields.length > 0) {
const properties : { [s: string]: SchemaElement; } = {};
model.fields.forEach(field => {
if (!isKeyField(field) && model.type !== NodeType.TYPE_MAP_STRING) {
const property = slugify(field.name);
properties[property] = fieldToProperty(field);
}
});
switch (model.type) {
case NodeType.TYPE_TREE:
element.properties = element.properties ? Object.assign(element.properties, properties) : properties;
break;
case NodeType.TYPE_LIST_OBJECT:
element.type = Type.TArray;
element.items = {
type: Type.TObject,
properties: properties
};
break;
case NodeType.TYPE_MAP_OBJECT:
element.patternProperties = {
".+": {
type: Type.TObject,
properties: properties,
keyTitle: getKeyField(model).name
}
};
break;
case NodeType.TYPE_MAP_STRING:
element.patternProperties = {
".+": {
type: Type.TString,
keyTitle: getKeyField(model).name,
valueTitle: getValueField(model).name
}
};
break;
}
}
return element;
};
const fieldToProperty = (field: Field) : SchemaElement => {
const property : SchemaElement = {
type: fieldTypeToSchemaType(field.type),
title: field.name
};
switch (field.type) {
case FieldType.Html:
property.format = Format.Html;
break;
case FieldType.Markdown:
property.format = Format.Markdown;
break;
case FieldType.TextArea:
property.format = Format.TextArea;
break;
default:
break;
}
if (field.className) {
property.className = field.className;
}
if (field.description) {
property.description = field.description;
}
if (field.type === FieldType.Array) {
property.items = {
type: Type.TString
}
}
return property;
};
const fieldTypeToSchemaType = (fieldType: FieldType) : Type => {
switch (fieldType) {
case FieldType.Html:
case FieldType.Markdown:
case FieldType.TextArea:
return Type.TString;
case FieldType.Array:
return Type.TArray;
case FieldType.String:
return Type.TString;
case FieldType.Boolean:
return Type.TBoolean;
case FieldType.Number:
return Type.TNumber;
}
};
export const migrateSchema = (object) : RootSchemaElement => {
// Is this a schema or a old model?
if (object.$schema) {
return object as RootSchemaElement;
} else {
// This is an 'model', which is the old representation
return modelToSchema(normalizeModel(object));
}
};
export const schemaToModel = (schema: RootSchemaElement) : Model => {
return _schemaToModel(schema as SchemaElement);
};
const _schemaToModel = (schema: SchemaElement) : Model => {
let model : Model;
switch (schema.type) {
case Type.TObject:
if (schema.patternProperties) {
const patterns = schema.patternProperties['.+'] as SchemaPatternProperty;
if (patterns.type === Type.TObject) {
model = new ObjectMapModel(schema.title!, []);
model.fields.push(new Field(patterns.keyTitle!, FieldType.String, true, patterns.description));
_propertiesToFields(patterns.properties!, model);
} else {
model = new StringMapModel(schema.title!, []);
model.fields.push(new Field(patterns.keyTitle!, FieldType.String, true, patterns.description));
model.fields.push(new Field(patterns.valueTitle!, FieldType.String));
}
} else {
model = new TreeModel(schema.title!, [], []);
}
break;
case Type.TArray:
model = new ListModel(schema.title!, []);
_propertiesToFields(schema.items!.properties!, model);
break;
default:
throw new Error(`Don't know what to do with element named ${schema.title} and type ${schema.type}`);
}
if (schema.properties) {
_propertiesToFields(schema.properties, model);
}
return model;
};
const _propertiesToFields = (properties : { [s: string]: SchemaElement; }, model : Model) => {
for (let key in properties) {
const element = properties[key];
switch (element.type) {
case Type.TString:
let fieldType = FieldType.String;
if (element.format === Format.Markdown) {
fieldType = FieldType.Markdown;
} else if (element.format === Format.Html) {
fieldType = FieldType.Html;
} else if (element.format === Format.TextArea) {
fieldType = FieldType.TextArea;
}
model.fields.push(new Field(element.title!, fieldType, false, element.description, element.className));
break;
case Type.TBoolean:
model.fields.push(new Field(element.title!, FieldType.Boolean, false, element.description, element.className));
break;
case Type.TNumber:
model.fields.push(new Field(element.title!, FieldType.Number, false, element.description, element.className));
break;
case Type.TArray:
if (element.items!.type === Type.TString) {
model.fields.push(new Field(element.title!, FieldType.Array, false, element.description, element.className));
} else {
(model as TreeModel).children.push(_schemaToModel(element));
}
break;
default:
(model as TreeModel).children.push(_schemaToModel(element));
break;
// throw new Error(`Unknown field type: ${element.type} for element named ${element.title}`);
}
}
}; | the_stack |
export type SimpleTypeKind =
// Primitives types
| "STRING_LITERAL"
| "NUMBER_LITERAL"
| "BOOLEAN_LITERAL"
| "BIG_INT_LITERAL"
| "ES_SYMBOL_UNIQUE"
| "STRING"
| "NUMBER"
| "BOOLEAN"
| "BIG_INT"
| "ES_SYMBOL"
| "NULL"
| "UNDEFINED"
| "VOID"
// TS-specific types
| "NEVER"
| "ANY"
| "UNKNOWN"
| "ENUM"
| "ENUM_MEMBER"
| "NON_PRIMITIVE"
// Structured types
| "UNION"
| "INTERSECTION"
// Object types types
| "INTERFACE"
| "OBJECT"
| "CLASS"
// Callable
| "FUNCTION"
| "METHOD"
// Generics
| "GENERIC_ARGUMENTS"
| "GENERIC_PARAMETER"
| "ALIAS"
// Lists
| "TUPLE"
| "ARRAY"
// Special types
| "DATE"
| "PROMISE";
export type SimpleTypeModifierKind = "EXPORT" | "AMBIENT" | "PUBLIC" | "PRIVATE" | "PROTECTED" | "STATIC" | "READONLY" | "ABSTRACT" | "ASYNC" | "DEFAULT";
// ##############################
// Base
// ##############################
export interface SimpleTypeBase {
readonly kind: SimpleTypeKind;
readonly name?: string;
}
// ##############################
// Primitive Types
// ##############################
export interface SimpleTypeBigIntLiteral extends SimpleTypeBase {
readonly kind: "BIG_INT_LITERAL";
readonly value: bigint;
}
export interface SimpleTypeStringLiteral extends SimpleTypeBase {
readonly kind: "STRING_LITERAL";
readonly value: string;
}
export interface SimpleTypeNumberLiteral extends SimpleTypeBase {
readonly kind: "NUMBER_LITERAL";
readonly value: number;
}
export interface SimpleTypeBooleanLiteral extends SimpleTypeBase {
readonly kind: "BOOLEAN_LITERAL";
readonly value: boolean;
}
export interface SimpleTypeString extends SimpleTypeBase {
readonly kind: "STRING";
}
export interface SimpleTypeNumber extends SimpleTypeBase {
readonly kind: "NUMBER";
}
export interface SimpleTypeBoolean extends SimpleTypeBase {
readonly kind: "BOOLEAN";
}
export interface SimpleTypeBigInt extends SimpleTypeBase {
readonly kind: "BIG_INT";
}
export interface SimpleTypeESSymbol extends SimpleTypeBase {
readonly kind: "ES_SYMBOL";
}
export interface SimpleTypeESSymbolUnique extends SimpleTypeBase {
readonly kind: "ES_SYMBOL_UNIQUE";
readonly value: string;
}
// ##############################
// TS-specific types
// ##############################
export interface SimpleTypeNull extends SimpleTypeBase {
readonly kind: "NULL";
}
export interface SimpleTypeNever extends SimpleTypeBase {
readonly kind: "NEVER";
}
export interface SimpleTypeUndefined extends SimpleTypeBase {
readonly kind: "UNDEFINED";
}
export interface SimpleTypeAny extends SimpleTypeBase {
readonly kind: "ANY";
}
export interface SimpleTypeUnknown extends SimpleTypeBase {
readonly kind: "UNKNOWN";
}
export interface SimpleTypeVoid extends SimpleTypeBase {
readonly kind: "VOID";
}
export interface SimpleTypeNonPrimitive extends SimpleTypeBase {
readonly kind: "NON_PRIMITIVE";
}
export interface SimpleTypeEnumMember extends SimpleTypeBase {
readonly kind: "ENUM_MEMBER";
readonly fullName: string;
readonly name: string;
readonly type: SimpleTypePrimitive;
}
export interface SimpleTypeEnum extends SimpleTypeBase {
readonly name: string;
readonly kind: "ENUM";
readonly types: SimpleTypeEnumMember[];
}
// ##############################
// Structure Types
// ##############################
export interface SimpleTypeUnion extends SimpleTypeBase {
readonly kind: "UNION";
readonly types: SimpleType[];
}
export interface SimpleTypeIntersection extends SimpleTypeBase {
readonly kind: "INTERSECTION";
readonly types: SimpleType[];
}
// ##############################
// Object Types
// ##############################
export interface SimpleTypeMember {
readonly optional: boolean;
readonly type: SimpleType;
readonly modifiers?: SimpleTypeModifierKind[];
}
export interface SimpleTypeMemberNamed extends SimpleTypeMember {
readonly name: string;
}
export interface SimpleTypeObjectTypeBase extends SimpleTypeBase {
readonly members?: SimpleTypeMemberNamed[];
readonly ctor?: SimpleTypeFunction;
readonly call?: SimpleTypeFunction;
readonly typeParameters?: SimpleTypeGenericParameter[];
readonly indexType?: {
["STRING"]?: SimpleType;
["NUMBER"]?: SimpleType;
};
}
export interface SimpleTypeInterface extends SimpleTypeObjectTypeBase {
readonly kind: "INTERFACE";
}
export interface SimpleTypeClass extends SimpleTypeObjectTypeBase {
readonly kind: "CLASS";
}
export interface SimpleTypeObject extends SimpleTypeObjectTypeBase {
readonly kind: "OBJECT";
}
// ##############################
// Callable
// ##############################
export interface SimpleTypeFunctionParameter {
readonly name: string;
readonly type: SimpleType;
readonly optional: boolean;
readonly rest: boolean;
readonly initializer: boolean;
}
export interface SimpleTypeFunction extends SimpleTypeBase {
readonly kind: "FUNCTION";
readonly parameters?: SimpleTypeFunctionParameter[];
readonly typeParameters?: SimpleTypeGenericParameter[];
readonly returnType?: SimpleType;
}
export interface SimpleTypeMethod extends SimpleTypeBase {
readonly kind: "METHOD";
readonly parameters: SimpleTypeFunctionParameter[];
readonly typeParameters?: SimpleTypeGenericParameter[];
readonly returnType: SimpleType;
}
// ##############################
// Generics
// ##############################
export interface SimpleTypeGenericArguments extends SimpleTypeBase {
readonly kind: "GENERIC_ARGUMENTS";
readonly name?: undefined;
readonly target: SimpleType;
readonly typeArguments: SimpleType[];
}
export interface SimpleTypeGenericParameter extends SimpleTypeBase {
readonly name: string;
readonly kind: "GENERIC_PARAMETER";
readonly default?: SimpleType;
}
export interface SimpleTypeAlias extends SimpleTypeBase {
readonly kind: "ALIAS";
readonly name: string;
readonly target: SimpleType;
readonly typeParameters?: SimpleTypeGenericParameter[];
}
// ##############################
// Lists
// ##############################
export interface SimpleTypeTuple extends SimpleTypeBase {
readonly kind: "TUPLE";
readonly members: SimpleTypeMember[];
readonly rest?: boolean;
}
export interface SimpleTypeArray extends SimpleTypeBase {
readonly kind: "ARRAY";
readonly type: SimpleType;
}
// ##############################
// Special Types
// ##############################
export interface SimpleTypeDate extends SimpleTypeBase {
readonly kind: "DATE";
}
export interface SimpleTypePromise extends SimpleTypeBase {
readonly kind: "PROMISE";
readonly type: SimpleType;
}
export type SimpleType =
| SimpleTypeBigIntLiteral
| SimpleTypeEnumMember
| SimpleTypeEnum
| SimpleTypeClass
| SimpleTypeFunction
| SimpleTypeObject
| SimpleTypeInterface
| SimpleTypeTuple
| SimpleTypeArray
| SimpleTypeUnion
| SimpleTypeIntersection
| SimpleTypeStringLiteral
| SimpleTypeNumberLiteral
| SimpleTypeBooleanLiteral
| SimpleTypeESSymbolUnique
| SimpleTypeString
| SimpleTypeNumber
| SimpleTypeBoolean
| SimpleTypeBigInt
| SimpleTypeESSymbol
| SimpleTypeNull
| SimpleTypeUndefined
| SimpleTypeNever
| SimpleTypeAny
| SimpleTypeMethod
| SimpleTypeVoid
| SimpleTypeNonPrimitive
| SimpleTypePromise
| SimpleTypeUnknown
| SimpleTypeAlias
| SimpleTypeDate
| SimpleTypeGenericArguments
| SimpleTypeGenericParameter;
// Collect all values on place. This is a map so Typescript will complain if we forget any kind.
const SIMPLE_TYPE_MAP: Record<SimpleTypeKind, "primitive" | "primitive_literal" | undefined> = {
NUMBER_LITERAL: "primitive_literal",
STRING_LITERAL: "primitive_literal",
BIG_INT_LITERAL: "primitive_literal",
BOOLEAN_LITERAL: "primitive_literal",
ES_SYMBOL_UNIQUE: "primitive_literal",
BIG_INT: "primitive",
BOOLEAN: "primitive",
NULL: "primitive",
UNDEFINED: "primitive",
VOID: "primitive",
ES_SYMBOL: "primitive",
NUMBER: "primitive",
STRING: "primitive",
NON_PRIMITIVE: undefined,
ENUM_MEMBER: undefined,
ALIAS: undefined,
ANY: undefined,
ARRAY: undefined,
CLASS: undefined,
DATE: undefined,
ENUM: undefined,
FUNCTION: undefined,
GENERIC_ARGUMENTS: undefined,
GENERIC_PARAMETER: undefined,
INTERFACE: undefined,
INTERSECTION: undefined,
METHOD: undefined,
NEVER: undefined,
OBJECT: undefined,
PROMISE: undefined,
TUPLE: undefined,
UNION: undefined,
UNKNOWN: undefined
};
// Primitive, literal
export type SimpleTypeLiteral = SimpleTypeBigIntLiteral | SimpleTypeBooleanLiteral | SimpleTypeStringLiteral | SimpleTypeNumberLiteral | SimpleTypeESSymbolUnique;
export const LITERAL_TYPE_KINDS: SimpleTypeKind[] = (Object.keys(SIMPLE_TYPE_MAP) as SimpleTypeKind[]).filter(kind => SIMPLE_TYPE_MAP[kind] === "primitive_literal");
export function isSimpleTypeLiteral(type: SimpleType): type is SimpleTypeLiteral {
return LITERAL_TYPE_KINDS.includes(type.kind);
}
// Primitive
export type SimpleTypePrimitive = SimpleTypeLiteral | SimpleTypeString | SimpleTypeNumber | SimpleTypeBoolean | SimpleTypeBigInt | SimpleTypeNull | SimpleTypeUndefined | SimpleTypeESSymbol;
export const PRIMITIVE_TYPE_KINDS: SimpleTypeKind[] = [...LITERAL_TYPE_KINDS, ...(Object.keys(SIMPLE_TYPE_MAP) as SimpleTypeKind[]).filter(kind => SIMPLE_TYPE_MAP[kind] === "primitive")];
export function isSimpleTypePrimitive(type: SimpleType): type is SimpleTypePrimitive {
return PRIMITIVE_TYPE_KINDS.includes(type.kind);
}
// All kinds
export const SIMPLE_TYPE_KINDS = Object.keys(SIMPLE_TYPE_MAP) as SimpleTypeKind[];
export function isSimpleType(type: unknown): type is SimpleType {
return typeof type === "object" && type != null && "kind" in type && Object.values(SIMPLE_TYPE_KINDS).find((key: SimpleTypeKind) => key === (type as { kind: SimpleTypeKind }).kind) != null;
}
export type SimpleTypeKindMap = {
STRING_LITERAL: SimpleTypeStringLiteral;
NUMBER_LITERAL: SimpleTypeNumberLiteral;
BOOLEAN_LITERAL: SimpleTypeBooleanLiteral;
BIG_INT_LITERAL: SimpleTypeBigIntLiteral;
ES_SYMBOL_UNIQUE: SimpleTypeESSymbolUnique;
STRING: SimpleTypeString;
NUMBER: SimpleTypeNumber;
BOOLEAN: SimpleTypeBoolean;
BIG_INT: SimpleTypeBigInt;
ES_SYMBOL: SimpleTypeESSymbol;
NULL: SimpleTypeNull;
UNDEFINED: SimpleTypeUndefined;
VOID: SimpleTypeVoid;
NEVER: SimpleTypeNever;
ANY: SimpleTypeAny;
UNKNOWN: SimpleTypeUnknown;
ENUM: SimpleTypeEnum;
ENUM_MEMBER: SimpleTypeEnumMember;
NON_PRIMITIVE: SimpleTypeNonPrimitive;
UNION: SimpleTypeUnion;
INTERSECTION: SimpleTypeIntersection;
INTERFACE: SimpleTypeInterface;
OBJECT: SimpleTypeObject;
CLASS: SimpleTypeClass;
FUNCTION: SimpleTypeFunction;
METHOD: SimpleTypeMethod;
GENERIC_ARGUMENTS: SimpleTypeGenericArguments;
GENERIC_PARAMETER: SimpleTypeGenericParameter;
ALIAS: SimpleTypeAlias;
TUPLE: SimpleTypeTuple;
ARRAY: SimpleTypeArray;
DATE: SimpleTypeDate;
PROMISE: SimpleTypePromise;
}; | the_stack |
import { camelize } from '@ridi/object-case-converter';
import { Icon } from '@ridi/rsg';
import { AxiosError, AxiosResponse } from 'axios';
import classNames from 'classnames';
import isString from 'lodash-es/isString';
import take from 'lodash-es/take';
import * as qs from 'qs';
import React from 'react';
import { connect } from 'react-redux';
import { Subject, Subscription } from 'rxjs';
import { debounceTime, distinctUntilChanged, filter, map, tap, throttleTime } from 'rxjs/operators';
import history from 'app/config/history';
import { AppStatus } from 'app/services/app';
import { InstantSearch } from 'app/components/InstantSearch';
import { SearchHistory } from 'app/components/SearchHistory';
import request from 'app/config/axios';
import { FetchStatusFlag } from 'app/constants';
import { GNBColorLevel, GNBSearchActiveType } from 'app/services/commonUI';
import { getSolidBackgroundColorRGBString } from 'app/services/commonUI/selectors';
import { getIsIosInApp, selectIsInApp } from 'app/services/environment/selectors';
import { RidiSelectState } from 'app/store';
import { localStorageManager } from 'app/utils/search';
import toast from 'app/utils/toast';
import { setDisableScroll } from 'app/utils/utils';
import env from 'app/config/env';
import { articleContentToPath } from 'app/utils/toPath';
import Colors from 'app/styles/colors';
export enum SearchHelperFlag {
NONE,
HISTORY,
INSTANT,
}
export interface InstantSearchHighlight {
webTitleTitle?: string;
author?: string;
publisher?: string;
}
export interface InstantSearchArticleHighlight {
title?: string;
authorNames?: string;
articleChannel?: { displayName: string };
}
export interface AuthorInfo {
name: string;
id: number;
isDeleted: boolean;
}
export interface InstantSearchResultBook {
bId: string;
title: string;
author: string;
publisher: string;
highlight: InstantSearchHighlight;
}
export interface InstantSearchResultArticle {
id: number;
articleChannel: { displayName: string; id: number; name: string };
authorsInfo: AuthorInfo[];
contentId: number;
title: string;
highlight: InstantSearchArticleHighlight;
}
interface SearchStoreProps {
gnbColorLevel: GNBColorLevel;
solidBackgroundColorRGBString: string;
gnbSearchActiveType: GNBSearchActiveType;
searchQuery: string;
isInApp: boolean;
isIosInApp: boolean;
appStatus: AppStatus;
}
interface SearchCascadedProps {
isMobile: boolean;
}
type SearchProps = SearchStoreProps & SearchCascadedProps;
interface HistoryState {
enabled: boolean;
bookKeywordList: string[];
articleKeywordList: string[];
}
interface QueryString {
q?: string;
}
interface SearchState {
searchQuery: string;
fetchStatus: FetchStatusFlag;
keyword: string;
isActive: boolean;
isClearButtonVisible: boolean;
highlightIndex: number;
currentHelperType: SearchHelperFlag;
history: HistoryState;
instantSearchResultsByKeyword: {
Books: {
[instantSearchKeyword: string]: InstantSearchResultBook[];
};
Articles: {
[instantSearchKeyword: string]: InstantSearchResultArticle[];
};
Common: {
[instantSearchKeyword: string]: InstantSearchResultBook[];
};
};
}
enum KeyboardCode {
ArrowUp = 38,
ArrowDown = 40,
Enter = 13,
}
export const SearchIcon = (props: { className: string }) => (
<svg width="18" height="18" viewBox="0 0 18 18" fill="none" className={props.className}>
// tslint:disable-next-line:max-line-length
<path
fillRule="evenodd"
clipRule="evenodd"
d="M6.68954 11.3208C4.12693 11.3208 2.05832 9.25214 2.05832 6.68954C2.05832 4.12693 4.12693 2.05832 6.68954 2.05832C9.25214 2.05832 11.3208 4.12693 11.3208 6.68954C11.3208 9.25214 9.25214 11.3208 6.68954 11.3208ZM12.8645 11.3208H12.0515L11.7633 11.0429C12.7719 9.86964 13.3791 8.34648 13.3791 6.68954C13.3791 2.99485 10.3842 0 6.68954 0C2.99485 0 0 2.99485 0 6.68954C0 10.3842 2.99485 13.3791 6.68954 13.3791C8.34648 13.3791 9.86964 12.7719 11.0429 11.7633L11.3208 12.0515V12.8645L16.4666 18L18 16.4666L12.8645 11.3208Z"
/>
</svg>
);
export class Search extends React.Component<SearchProps, SearchState> {
public static getDerivedStateFromProps(nextProps: SearchProps, prevState: SearchState) {
if (nextProps.searchQuery !== prevState.searchQuery) {
const queryString: QueryString = qs.parse(nextProps.searchQuery, { ignoreQueryPrefix: true });
const keywordText: string =
queryString && queryString.q && isString(queryString.q) ? queryString.q : '';
if (keywordText.length <= 0) {
return null;
}
return {
searchQuery: nextProps.searchQuery,
keyword: keywordText,
};
}
return null;
}
// set member variables type
private onSearchChange$ = new Subject();
private onSearchKeydown$ = new Subject();
private searchComponentWrapper: HTMLElement | null;
private searchInput: HTMLInputElement | null;
private keydownSubscription: Subscription;
private inputSubscription: Subscription;
public state: SearchState = this.getInitialState();
private closeFunctionOnWindow = (event: MouseEvent): void => this.handleOutsideClick(event);
// set initial private state
private getInitialState(): SearchState {
const {
enabled = true,
bookKeywordList = [],
articleKeywordList = [],
} = localStorageManager.load().history;
return {
searchQuery: '',
fetchStatus: FetchStatusFlag.IDLE,
keyword: '',
isActive: false,
isClearButtonVisible: false,
highlightIndex: -1,
currentHelperType: SearchHelperFlag.NONE,
history: { enabled, bookKeywordList, articleKeywordList },
instantSearchResultsByKeyword: { Books: {}, Articles: {}, Common: {} },
};
}
private setStateClean(keyword = ''): void {
this.setState(
{
isActive: false,
keyword,
highlightIndex: -1,
currentHelperType: SearchHelperFlag.NONE,
isClearButtonVisible: false,
},
() => {
if (this.searchInput) {
this.searchInput.blur();
}
},
);
}
// private methods
private setHistoryStateAndLocalStorage(historyObj: HistoryState): void {
this.setState(
{
history: historyObj,
},
() => {
localStorageManager.save({
history: {
...this.state.history,
},
});
},
);
}
private toggleSavingHistory(): void {
const updatedHistoryState = {
enabled: !this.state.history.enabled,
bookKeywordList: this.state.history.bookKeywordList,
articleKeywordList: this.state.history.articleKeywordList,
};
this.setHistoryStateAndLocalStorage(updatedHistoryState);
}
private pushHistoryKeyword(keyword: string): void {
if (!this.state.history.enabled || keyword.length <= 0) {
return;
}
const { appStatus } = this.props;
const filteredKeywordList: string[] =
appStatus === AppStatus.Books
? this.state.history.bookKeywordList
: this.state.history.articleKeywordList
.filter((listItem: string) => listItem !== keyword)
.filter((listItem: string) => listItem.length > 0);
const updatedHistoryState: HistoryState = {
enabled: this.state.history.enabled,
bookKeywordList:
appStatus === AppStatus.Books
? [keyword, ...take(filteredKeywordList, 4)]
: this.state.history.bookKeywordList,
articleKeywordList:
appStatus === AppStatus.Articles
? [keyword, ...take(filteredKeywordList, 4)]
: this.state.history.articleKeywordList,
};
this.setHistoryStateAndLocalStorage(updatedHistoryState);
}
private clearHistory(): void {
const updatedHistoryState = {
enabled: this.state.history.enabled,
bookKeywordList: [],
articleKeywordList: [],
};
this.setHistoryStateAndLocalStorage(updatedHistoryState);
}
private removeHistoryKeyword(keyword: string): void {
const { appStatus } = this.props;
const filteredKeywordList: string[] =
appStatus === AppStatus.Books
? this.state.history.bookKeywordList.filter((listItem: string) => listItem !== keyword)
: this.state.history.articleKeywordList.filter((listItem: string) => listItem !== keyword);
const updatedHistoryState = {
enabled: this.state.history.enabled,
bookKeywordList:
appStatus === AppStatus.Books ? filteredKeywordList : this.state.history.bookKeywordList,
articleKeywordList:
appStatus === AppStatus.Articles
? filteredKeywordList
: this.state.history.articleKeywordList,
};
this.setHistoryStateAndLocalStorage(updatedHistoryState);
}
private manageScrollDisable(isDisable: boolean): void {
const { isMobile, isInApp } = this.props;
if (isMobile || isInApp) {
setDisableScroll(isDisable);
}
}
private getInstantSearchedList(value: string) {
const { instantSearchResultsByKeyword } = this.state;
const { appStatus } = this.props;
const requestParams = {
site: 'ridi-select',
where: appStatus === AppStatus.Books ? 'book' : 'article',
what: 'instant',
keyword: value,
};
if (
instantSearchResultsByKeyword[appStatus][value] &&
instantSearchResultsByKeyword[appStatus][value].length > 0
) {
this.setState(
{
isActive: true,
fetchStatus: FetchStatusFlag.IDLE,
currentHelperType: SearchHelperFlag.INSTANT,
},
() => this.manageScrollDisable(false),
);
return;
}
this.setState(
{
isActive: true,
fetchStatus: FetchStatusFlag.FETCHING,
currentHelperType: SearchHelperFlag.INSTANT,
},
() => {
request({
baseURL: env.SEARCH_API,
method: 'get',
url: '/search',
withCredentials: false,
params: requestParams,
})
.then((axResponse: AxiosResponse) =>
this.setState(
{
fetchStatus: FetchStatusFlag.IDLE,
instantSearchResultsByKeyword: {
...instantSearchResultsByKeyword,
[appStatus]: {
...instantSearchResultsByKeyword[appStatus],
[value]: camelize(axResponse.data[appStatus.toLowerCase()], {
recursive: true,
}),
},
},
},
() => this.manageScrollDisable(false),
),
)
.catch((axError: AxiosError) =>
this.setState(
{
fetchStatus: FetchStatusFlag.FETCH_ERROR,
currentHelperType: SearchHelperFlag.NONE,
},
() => this.manageScrollDisable(false),
),
);
},
);
}
private toggleActivation(isTargetActive: boolean): void {
const { isActive } = this.state;
if (isActive === isTargetActive) {
return;
}
window.removeEventListener('click', this.closeFunctionOnWindow, true);
this.manageScrollDisable(isTargetActive);
if (!isTargetActive) {
this.setStateClean();
return;
}
window.addEventListener('click', this.closeFunctionOnWindow, true);
const { keyword } = this.state;
const targetState = {
isActive: isTargetActive,
keyword,
highlightIndex: -1,
currentHelperType: SearchHelperFlag.HISTORY,
isClearButtonVisible: true,
};
if (this.props.gnbSearchActiveType !== GNBSearchActiveType.block) {
targetState.keyword = '';
targetState.isClearButtonVisible = false;
} else if (keyword.length > 0) {
this.getInstantSearchedList(keyword);
targetState.currentHelperType = SearchHelperFlag.INSTANT;
}
this.setState(targetState, () => {
if (this.searchInput) {
this.searchInput.focus();
}
});
}
private clearSearchInput(): void {
this.setState(
{
keyword: '',
isClearButtonVisible: false,
currentHelperType: SearchHelperFlag.HISTORY,
},
() => this.searchInput && this.searchInput.focus(),
);
}
private updateHighlightIndex(idx: number): void {
this.setState({
highlightIndex: idx,
});
}
private linkToBookDetail(book: InstantSearchResultBook): void {
if (!book) {
toast.failureMessage();
return;
}
let targetKeyword = '';
if (book.highlight.webTitleTitle) {
targetKeyword = book.title;
} else if (book.highlight.author) {
targetKeyword = book.author;
} else if (book.highlight.publisher) {
targetKeyword = book.publisher;
}
this.manageScrollDisable(false);
this.setStateClean();
this.pushHistoryKeyword(targetKeyword);
history.push(`/book/${book.bId}?q=${encodeURIComponent(targetKeyword)}&s=instant`);
}
private linkToArticleDetail(article: InstantSearchResultArticle): void {
if (!article) {
toast.failureMessage();
return;
}
let targetKeyword = '';
if (article.highlight.title) {
targetKeyword = article.title;
} else if (article.highlight.articleChannel) {
targetKeyword = article.articleChannel.displayName;
}
this.manageScrollDisable(false);
this.setStateClean();
this.pushHistoryKeyword(targetKeyword);
history.push(
`${articleContentToPath({
channelName: article.articleChannel.name,
contentIndex: article.contentId,
})}?q=${encodeURIComponent(targetKeyword)}&s=instant`,
);
}
private fullSearchWithKeyword(keyword: string): void {
if (keyword.length <= 0) {
return;
}
const { appStatus } = this.props;
this.manageScrollDisable(false);
history.push(`/search?q=${encodeURIComponent(keyword)}&type=${appStatus}`);
this.pushHistoryKeyword(keyword);
setTimeout(() => this.setStateClean(keyword), 0);
}
private doSearchAction(value: string): void {
const { keyword, highlightIndex, currentHelperType } = this.state;
const { appStatus } = this.props;
const { bookKeywordList, articleKeywordList } = this.state.history;
if (highlightIndex < 0) {
this.fullSearchWithKeyword(value);
return;
}
if (currentHelperType === SearchHelperFlag.INSTANT) {
const instantSearchResults = this.state.instantSearchResultsByKeyword;
if (appStatus === AppStatus.Books) {
this.linkToBookDetail(instantSearchResults.Books[keyword][highlightIndex]);
} else {
this.linkToArticleDetail(instantSearchResults.Articles[keyword][highlightIndex]);
}
return;
}
if (currentHelperType === SearchHelperFlag.HISTORY) {
if (appStatus === AppStatus.Books) {
this.fullSearchWithKeyword(bookKeywordList[highlightIndex]);
} else {
this.fullSearchWithKeyword(articleKeywordList[highlightIndex]);
}
}
}
private getMovedHighlightIndex(
keyType: number,
currentIndex: number,
currentList: string[] | InstantSearchResultBook[] | InstantSearchResultArticle[],
): number {
switch (keyType) {
case KeyboardCode.ArrowDown:
return currentIndex + 1 >= currentList.length ? currentIndex : currentIndex + 1;
case KeyboardCode.ArrowUp:
return currentIndex - 1 < 0 ? 0 : currentIndex - 1;
default:
return currentIndex;
}
}
private subscribeKeyboardEvent(): void {
if (!this.searchInput) {
return;
}
// functional key event observable
this.keydownSubscription = this.onSearchKeydown$
.pipe(
filter((e: any) => e.keyCode === 13 || e.keyCode === 38 || e.keyCode === 40),
map((e: any) => {
e.preventDefault();
const { appStatus } = this.props;
return {
keyType: e.keyCode,
value: e.target.value,
currentHelperList:
this.state.currentHelperType === SearchHelperFlag.HISTORY
? appStatus === AppStatus.Books
? this.state.history.bookKeywordList
: this.state.history.articleKeywordList
: this.state.instantSearchResultsByKeyword[appStatus][this.state.keyword],
};
}),
throttleTime(100),
)
.subscribe(
(obj: {
keyType: KeyboardCode;
value: string;
currentHelperList: string[] | InstantSearchResultBook[] | InstantSearchResultArticle[];
}): void => {
const {
keyword,
currentHelperType,
instantSearchResultsByKeyword,
fetchStatus,
highlightIndex,
} = this.state;
if (obj.keyType === KeyboardCode.Enter) {
this.doSearchAction(obj.value);
return;
}
if (currentHelperType === SearchHelperFlag.HISTORY && !this.state.history.enabled) {
this.setState({ highlightIndex: -1 });
return;
}
if (currentHelperType !== SearchHelperFlag.NONE) {
this.setState({
highlightIndex:
fetchStatus === FetchStatusFlag.FETCHING
? -1
: this.getMovedHighlightIndex(obj.keyType, highlightIndex, obj.currentHelperList),
});
} else if (
keyword.length > 0 &&
instantSearchResultsByKeyword[this.props.appStatus][keyword].length > 0
) {
this.setState({
highlightIndex: fetchStatus === FetchStatusFlag.FETCHING ? -1 : 0,
currentHelperType:
fetchStatus === FetchStatusFlag.FETCHING
? SearchHelperFlag.NONE
: SearchHelperFlag.INSTANT,
});
} else if (keyword.length === 0) {
this.setState({
highlightIndex: 0,
currentHelperType: SearchHelperFlag.HISTORY,
});
}
},
);
// input value change event observable
this.inputSubscription = this.onSearchChange$
.pipe(
tap((value: string): void =>
this.setState({
keyword: value,
highlightIndex: -1,
isClearButtonVisible: true,
currentHelperType:
value.length > 0 ? this.state.currentHelperType : SearchHelperFlag.HISTORY,
}),
),
distinctUntilChanged(),
debounceTime(150),
)
.subscribe((value: string): void => {
if (value.length === 0) {
this.setState({
isActive: true,
isClearButtonVisible: false,
currentHelperType: SearchHelperFlag.HISTORY,
});
return;
}
if (this.state.isActive) {
this.getInstantSearchedList(value);
}
});
}
private onSearchChange(e: any): void {
const searchKeyword = e.target.value;
this.onSearchChange$.next(searchKeyword);
}
private onSearchKeydown(e: any): void {
this.onSearchKeydown$.next(e);
}
private handleOutsideClick(e: any): void {
if (this.searchComponentWrapper && this.searchComponentWrapper.contains(e.target)) {
return;
}
const targetKeyword =
this.props.gnbSearchActiveType === GNBSearchActiveType.block ? this.state.keyword : '';
this.toggleActivation(false);
this.setStateClean(targetKeyword);
}
private renderSearchButtonIcon() {
const { isActive } = this.state;
const { isIosInApp, gnbSearchActiveType } = this.props;
if (isActive || gnbSearchActiveType === GNBSearchActiveType.block) {
return <Icon name="arrow_13_left" className="GNBSearchButtonIcon" />;
}
if (isIosInApp) {
return (
<svg
className="GNBSearchButtonIcon_IosInApp"
width="24px"
height="24px"
viewBox="0 0 24 24"
>
<g stroke="none" strokeWidth="1" fill="none" fillRule="evenodd">
<g transform="translate(2.500000, 2.500000)" fill={Colors.bluegray_70}>
{/* tslint:disable-next-line:max-line-length */}
<path
d="M8,1.5 C4.41014913,1.5 1.5,4.41014913 1.5,8 C1.5,11.5898509 4.41014913,14.5 8,14.5 C11.5898509,14.5 14.5,11.5898509 14.5,8 C14.5,4.41014913 11.5898509,1.5 8,1.5 Z M8,0 C12.418278,-7.77156117e-16 16,3.581722 16,8 C16,12.418278 12.418278,16 8,16 C3.581722,16 4.4408921e-16,12.418278 0,8 C-5.55111512e-16,3.581722 3.581722,8.8817842e-16 8,0 Z"
id="Rectangle"
fillRule="nonzero"
/>
{/* tslint:disable-next-line:max-line-length */}
<polygon
transform="translate(15.778175, 15.674621) rotate(-45.000000) translate(-15.778175, -15.674621)"
points="15.0281746 11.4246212 16.5281746 11.4246212 16.5281746 19.9246212 15.0281746 19.9246212"
/>
</g>
</g>
</svg>
);
}
return <SearchIcon className="GNBSearchButtonIcon" />;
}
// component life cycle handler
public componentDidMount(): void {
this.subscribeKeyboardEvent();
}
public componentWillUnmount(): void {
this.keydownSubscription.unsubscribe();
this.inputSubscription.unsubscribe();
}
// render
public render() {
const {
keyword,
fetchStatus,
isActive,
isClearButtonVisible,
highlightIndex,
currentHelperType,
} = this.state;
const {
isMobile,
gnbColorLevel,
solidBackgroundColorRGBString,
gnbSearchActiveType,
appStatus,
} = this.props;
const instantSearchResult = this.state.instantSearchResultsByKeyword[appStatus][keyword];
const { enabled, bookKeywordList, articleKeywordList } = this.state.history;
const inputEvents = {
onChange: (e: any) => this.onSearchChange(e),
onKeyDown: (e: any) => this.onSearchKeydown(e),
};
Object.assign(
inputEvents,
isMobile
? {
onTouchStart: () => this.toggleActivation(true),
}
: {
onClick: () => this.toggleActivation(true),
},
);
return (
<div
className={classNames({
GNBSearchWrapper: true,
active: isActive,
'GNBSearchWrapper-colored': gnbColorLevel !== GNBColorLevel.DEFAULT,
'GNBSearchWrapper-typeBlock': gnbSearchActiveType === GNBSearchActiveType.block,
})}
style={{ background: solidBackgroundColorRGBString }}
ref={ref => {
this.searchComponentWrapper = ref;
}}
>
<button
type="button"
className="GNBSearchButton"
onClick={() => {
if (gnbSearchActiveType === GNBSearchActiveType.block) {
history.goBack();
this.toggleActivation(false);
return;
}
this.toggleActivation(!isActive);
}}
>
{this.renderSearchButtonIcon()}
<h2 className="a11y">검색</h2>
</button>
<div
className={classNames('GNBSearchInputWrapper', {
'GNBSearchInputWrapper-empty': isClearButtonVisible,
})}
>
<SearchIcon className="GNBSearchIcon" />
<input
className="GNBSearchInput"
type="search"
role="search"
autoCorrect="off"
autoComplete="off"
autoCapitalize="off"
placeholder={appStatus === AppStatus.Books ? '도서 검색' : '아티클 검색'}
value={keyword}
ref={ref => {
this.searchInput = ref;
}}
{...inputEvents}
maxLength={150}
/>
{isClearButtonVisible && keyword.length > 0 ? (
<button
className="GNBSearchResetButton"
type="button"
onClick={() => this.clearSearchInput()}
>
<Icon name="close_2" className="GNBSearchResetButtonIcon" />
<span className="a11y">검색어 비우기</span>
</button>
) : null}
</div>
<InstantSearch
keyword={keyword}
isActive={isActive && currentHelperType === SearchHelperFlag.INSTANT}
fetchStatus={fetchStatus}
searchType={appStatus}
instantSearchList={instantSearchResult}
highlightIndex={highlightIndex}
updateHighlight={(idx: number) => this.updateHighlightIndex(idx)}
onSearchItemClick={(item: InstantSearchResultBook | InstantSearchResultArticle) => {
if (appStatus === AppStatus.Books) {
const book = item as InstantSearchResultBook;
this.linkToBookDetail(book);
} else {
const article = item as InstantSearchResultArticle;
this.linkToArticleDetail(article);
}
}}
/>
<SearchHistory
isActive={isActive && currentHelperType === SearchHelperFlag.HISTORY}
highlightIndex={highlightIndex}
updateHighlight={(idx: number) => this.updateHighlightIndex(idx)}
savingHistoryEnabled={enabled}
keywordList={appStatus === AppStatus.Books ? bookKeywordList : articleKeywordList}
toggleSavingHistory={() => this.toggleSavingHistory()}
clearHistory={() => this.clearHistory()}
removeKeyword={(targetKeyword: string) => this.removeHistoryKeyword(targetKeyword)}
resetSearchState={() => {
this.manageScrollDisable(false);
this.toggleActivation(false);
}}
appStatus={appStatus}
/>
{isMobile ? (
<span
className="dim"
onClick={() => {
this.manageScrollDisable(false);
this.setState({ isActive: false, isClearButtonVisible: false });
}}
/>
) : null}
</div>
);
}
}
const mapStateToProps = (state: RidiSelectState): SearchStoreProps => ({
gnbColorLevel: state.commonUI.gnbColorLevel,
solidBackgroundColorRGBString: getSolidBackgroundColorRGBString(state),
gnbSearchActiveType: state.commonUI.gnbSearchActiveType,
searchQuery: state.router.location.search,
isIosInApp: getIsIosInApp(state),
isInApp: selectIsInApp(state),
appStatus: state.app.appStatus,
});
export const ConnectedSearch = connect(mapStateToProps)(Search); | the_stack |
import Dimensions = Utils.Measurements.Dimensions;
import DisplayObject = etch.drawing.DisplayObject;
import Size = minerva.Size;
import {IApp} from '../IApp';
import {MainScene} from './../MainScene';
declare var App: IApp;
export class MessagePanel extends DisplayObject {
private _Roll:boolean[];
public Hover:boolean;
private _Defaults:any;
private _Value: any;
private _Alpha: number;
public Open: boolean;
private _Timeout: any;
private _CloseX: number;
private _Lines: number;
private _ButtonWidth: number;
Init(drawTo: IDisplayContext):void {
super.Init(drawTo);
this._Roll = [];
this.Hover = false;
this.Open = false;
this._CloseX = 0;
this._Lines = 0;
// DEFAULT MESSAGING ARGUMENTS //
this._Defaults = {
string: "Message Text Missing...",
seconds: 3,
confirmation: false,
buttonText: "",
buttonEvent: this.DefaultFunction
};
this._Value = {
string: this._Defaults.string,
seconds: this._Defaults.seconds,
confirmation: this._Defaults.confirmation,
buttonText: this._Defaults.buttonText,
buttonEvent: this._Defaults.buttonEvent
};
}
//-------------------------------------------------------------------------------------------
// DRAWING
//-------------------------------------------------------------------------------------------
Draw() {
var units = App.Unit;
var ctx = this.Ctx;
var midType = App.Metrics.TxtMid;
var y = (<MainScene>this.DrawTo).Height*0.75;
var cx = (<MainScene>this.DrawTo).Width*0.5;
var w = (<MainScene>this.DrawTo).Width;
if (this._Alpha>0) {
ctx.textAlign = "center";
ctx.font = midType;
var clx = this._CloseX;
// DRAW PANEL //
App.FillColor(ctx,App.Palette[2]);
ctx.globalAlpha = this._Alpha * 0.16;
ctx.fillRect(0, y - (25*units), w, (60*units) + (this._Lines * (16*units)));
ctx.globalAlpha = this._Alpha * 0.9;
ctx.fillRect(0, y - (30*units), w, (60*units) + (this._Lines * (16*units)));
// MESSAGE TEXT //
ctx.globalAlpha = this._Alpha;
App.FillColor(ctx,App.Palette[App.ThemeManager.Txt]);
App.StrokeColor(ctx,App.Palette[App.ThemeManager.Txt]);
//ctx.fillText(this._Value.string.toUpperCase(), cx, y + (5 * units));
this.WordWrap(ctx,this._Value.string.toUpperCase(), cx, y + (5 * units), 16*units, w - (30*units));
// CLOSE //
if (this._Value.confirmation) {
App.FillColor(ctx,App.Palette[2]);
ctx.globalAlpha = this._Alpha * 0.9;
ctx.beginPath();
ctx.moveTo(clx - (20 * units), y - (30 * units));
ctx.lineTo(clx + (20 * units), y - (30 * units));
ctx.lineTo(clx, y - (50 * units));
ctx.closePath();
ctx.fill();
// CLOSE X //
ctx.globalAlpha = this._Alpha;
App.StrokeColor(ctx,App.Palette[App.ThemeManager.Txt]);
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(clx - (4 * units), y - (34 * units));
ctx.lineTo(clx + (4 * units), y - (26 * units));
ctx.moveTo(clx - (4 * units), y - (26 * units));
ctx.lineTo(clx + (4 * units), y - (34 * units));
ctx.stroke();
ctx.lineWidth = 1;
}
// BUTTON //
if (this._Value.buttonText!=="") {
App.FillColor(ctx,App.Palette[4]);
ctx.fillRect(clx,y - (15*units),this._ButtonWidth,30*units);
if (this._Roll[1]) {
ctx.beginPath();
ctx.moveTo(clx + (this._ButtonWidth*0.5) - (10 * units), y + (15 * units) - 1);
ctx.lineTo(clx + (this._ButtonWidth*0.5) + (10 * units), y + (15 * units) - 1);
ctx.lineTo(clx + (this._ButtonWidth*0.5), y + (25 * units) - 1);
ctx.closePath();
ctx.fill();
}
ctx.textAlign = "left";
App.FillColor(ctx,App.Palette[App.ThemeManager.Txt]);
ctx.fillText(this._Value.buttonText.toUpperCase(), clx + (10*units), y + (5 * units));
}
}
}
//-------------------------------------------------------------------------------------------
// STRING FUNCTIONS
//-------------------------------------------------------------------------------------------
WordWrap( context , text, x, y, lineHeight, fitWidth) {
fitWidth = fitWidth || 0;
if (fitWidth <= 0) {
context.fillText( text, x, y );
return;
}
var words = text.split(' ');
var currentLine = 0;
var idx = 1;
while (words.length > 0 && idx <= words.length) {
var str = words.slice(0,idx).join(' ');
var w = context.measureText(str).width;
if ( w > fitWidth ) {
if (idx==1)
{
idx=2;
}
context.fillText( words.slice(0,idx-1).join(' '), x, y + (lineHeight*currentLine) );
currentLine++;
words = words.splice(idx-1);
idx = 1;
}
else
{idx++;}
}
if (idx > 0)
context.fillText( words.join(' '), x, y + (lineHeight*currentLine) );
}
LineCount( context , text, fitWidth) {
fitWidth = fitWidth || 0;
this._Lines = 0;
if (fitWidth <= 0) {
return;
}
var words = text.split(' ');
var currentLine = 0;
var idx = 1;
while (words.length > 0 && idx <= words.length) {
var str = words.slice(0,idx).join(' ');
var w = context.measureText(str).width;
if ( w > fitWidth ) {
if (idx==1)
{
idx=2;
}
this._Lines += 1;
currentLine++;
words = words.splice(idx-1);
idx = 1;
}
else
{idx++;}
}
}
//-------------------------------------------------------------------------------------------
// MESSAGING
//-------------------------------------------------------------------------------------------
NewMessage(string?: string, options?: any) {
options = options || {};
this._Value.string = string || this._Defaults.string;
this._Value.seconds = options.seconds || this._Defaults.seconds;
this._Value.confirmation = options.confirmation || this._Defaults.confirmation;
this._Value.buttonText = options.buttonText || this._Defaults.buttonText;
this._Value.buttonEvent = options.buttonEvent || this._Defaults.buttonEvent;
// IF BUTTON, FORCE CONFIRMATION //
if (this._Value.buttonText!=="") {
this._Value.confirmation = true;
}
// LINE COUNT //
var units = App.Unit;
var ctx = this.Ctx;
ctx.font = App.Metrics.TxtMid;
this.LineCount(ctx,this._Value.string.toUpperCase(), App.Width - (30*units));
// CLOSE POSITION //
if (this._Value.confirmation) {
var cx = (<MainScene>this.DrawTo).Width*0.5;
this._CloseX = cx + (20*units) + (ctx.measureText(this._Value.string.toUpperCase()).width * 0.5);
this._ButtonWidth = (20*units) + ctx.measureText(this._Value.buttonText.toUpperCase()).width;
}
// START OPEN TWEEN //
if (!this.Open) {
this.Tween(this,"_Alpha",1,0,400);
this.Open = true;
}
// CLOSE TIMER//
clearTimeout(this._Timeout);
var message = this;
this._Timeout = setTimeout(function(){
if (!message._Value.confirmation) {
message.Close();
}
},this._Value.seconds*1000);
}
Close() {
this.Tween(this,"_Alpha",0,0,1000);
this.Hover = false;
this.Open = false;
}
DefaultFunction() {
// console.log("default function");
}
//-------------------------------------------------------------------------------------------
// TWEEN
//-------------------------------------------------------------------------------------------
Tween(panel,value,destination,delay,time) {
var pTween = new window.TWEEN.Tween({x:panel[""+value]});
pTween.to({ x: destination }, time);
pTween.onUpdate(function() {
panel[""+value] = this.x;
});
pTween.delay(delay);
pTween.start(this.LastVisualTick);
pTween.easing( window.TWEEN.Easing.Quintic.InOut );
}
//-------------------------------------------------------------------------------------------
// INTERACTION
//-------------------------------------------------------------------------------------------
MouseDown(point) {
this.RolloverCheck(point);
if (this.Open && this._Roll[0]) {
this.Close();
}
if (this.Open && this._Roll[1]) {
this._Value.buttonEvent();
this.Close();
}
}
MouseMove(point) {
this.RolloverCheck(point);
}
RolloverCheck(point) {
this.Hover = false;
var units = App.Unit;
if (this._Value.confirmation) {
this._Roll[0] = Dimensions.hitRect(this._CloseX - (20*units), ((<MainScene>this.DrawTo).Height*0.75) - (50*units), (40*units), (40*units), point.x, point.y);
} else {
this._Roll[0] = false;
}
if (this._Value.buttonText!=="") {
this._Roll[1] = Dimensions.hitRect(this._CloseX, ((<MainScene>this.DrawTo).Height*0.75) - (15*units), this._ButtonWidth, (30*units), point.x, point.y);
} else {
this._Roll[1] = false;
}
if (this._Roll[0] || this._Roll[1]) {
this.Hover = true;
}
}
} | the_stack |
import * as coreClient from "@azure/core-client";
export type SourceNodeBaseUnion =
| SourceNodeBase
| RtspSource
| IotHubMessageSource;
export type ProcessorNodeBaseUnion =
| ProcessorNodeBase
| MotionDetectionProcessor
| ObjectTrackingProcessor
| LineCrossingProcessor
| ExtensionProcessorBaseUnion
| SignalGateProcessor
| CognitiveServicesVisionProcessor;
export type SinkNodeBaseUnion =
| SinkNodeBase
| IotHubMessageSink
| FileSink
| VideoSink;
export type EndpointBaseUnion = EndpointBase | UnsecuredEndpoint | TlsEndpoint;
export type CredentialsBaseUnion =
| CredentialsBase
| UsernamePasswordCredentials
| HttpHeaderCredentials
| SymmetricKeyCredentials;
export type CertificateSourceUnion = CertificateSource | PemCertificateList;
export type NamedLineBaseUnion = NamedLineBase | NamedLineString;
export type ImageFormatPropertiesUnion =
| ImageFormatProperties
| ImageFormatRaw
| ImageFormatJpeg
| ImageFormatBmp
| ImageFormatPng;
export type NamedPolygonBaseUnion = NamedPolygonBase | NamedPolygonString;
export type SpatialAnalysisOperationBaseUnion =
| SpatialAnalysisOperationBase
| SpatialAnalysisCustomOperation
| SpatialAnalysisTypedOperationBaseUnion;
export type ExtensionProcessorBaseUnion =
| ExtensionProcessorBase
| GrpcExtension
| HttpExtension;
export type SpatialAnalysisTypedOperationBaseUnion =
| SpatialAnalysisTypedOperationBase
| SpatialAnalysisPersonCountOperation
| SpatialAnalysisPersonZoneCrossingOperation
| SpatialAnalysisPersonDistanceOperation
| SpatialAnalysisPersonLineCrossingOperation;
/** Live Pipeline represents an unique instance of a pipeline topology which is used for real-time content ingestion and analysis. */
export interface LivePipeline {
/** Live pipeline unique identifier. */
name: string;
/** Read-only system metadata associated with this object. */
systemData?: SystemData;
/** Live pipeline properties. */
properties?: LivePipelineProperties;
}
/** Read-only system metadata associated with a resource. */
export interface SystemData {
/** Date and time when this resource was first created. Value is represented in UTC according to the ISO8601 date format. */
createdAt?: Date;
/** Date and time when this resource was last modified. Value is represented in UTC according to the ISO8601 date format. */
lastModifiedAt?: Date;
}
/** Live pipeline properties. */
export interface LivePipelineProperties {
/** An optional description of the live pipeline. */
description?: string;
/** The reference to an existing pipeline topology defined for real-time content processing. When activated, this live pipeline will process content according to the pipeline topology definition. */
topologyName?: string;
/** List of the instance level parameter values for the user-defined topology parameters. A pipeline can only define or override parameters values for parameters which have been declared in the referenced topology. Topology parameters without a default value must be defined. Topology parameters with a default value can be optionally be overridden. */
parameters?: ParameterDefinition[];
/** Current pipeline state (read-only). */
state?: LivePipelineState;
}
/** Defines the parameter value of an specific pipeline topology parameter. See pipeline topology parameters for more information. */
export interface ParameterDefinition {
/** Name of the parameter declared in the pipeline topology. */
name: string;
/** Parameter value to be applied on this specific live pipeline. */
value?: string;
}
/** A collection of live pipelines. */
export interface LivePipelineCollection {
/** List of live pipelines. */
value?: LivePipeline[];
/** A continuation token to be used in subsequent calls when enumerating through the collection. This is returned when the collection results won't fit in a single response. */
continuationToken?: string;
}
/** A collection of pipeline topologies. */
export interface PipelineTopologyCollection {
/** List of pipeline topologies. */
value?: PipelineTopology[];
/** A continuation token to be used in subsequent calls when enumerating through the collection. This is returned when the collection results won't fit in a single response. */
continuationToken?: string;
}
/**
* Pipeline topology describes the processing steps to be applied when processing media for a particular outcome. The topology should be defined according to the scenario to be achieved and can be reused across many pipeline instances which share the same processing characteristics. For instance, a pipeline topology which acquires data from a RTSP camera, process it with an specific AI model and stored the data on the cloud can be reused across many different cameras, as long as the same processing should be applied across all the cameras. Individual instance properties can be defined through the use of user-defined parameters, which allow for a topology to be parameterized, thus allowing individual pipelines to refer to different values, such as individual cameras RTSP endpoints and credentials. Overall a topology is composed of the following:
*
* - Parameters: list of user defined parameters that can be references across the topology nodes.
* - Sources: list of one or more data sources nodes such as an RTSP source which allows for media to be ingested from cameras.
* - Processors: list of nodes which perform data analysis or transformations.
* -Sinks: list of one or more data sinks which allow for data to be stored or exported to other destinations.
*/
export interface PipelineTopology {
/** Pipeline topology unique identifier. */
name: string;
/** Read-only system metadata associated with this object. */
systemData?: SystemData;
/** Pipeline topology properties. */
properties?: PipelineTopologyProperties;
}
/** Pipeline topology properties. */
export interface PipelineTopologyProperties {
/** An optional description of the pipeline topology. It is recommended that the expected use of the topology to be described here. */
description?: string;
/** List of the topology parameter declarations. Parameters declared here can be referenced throughout the topology nodes through the use of "${PARAMETER_NAME}" string pattern. Parameters can have optional default values and can later be defined in individual instances of the pipeline. */
parameters?: ParameterDeclaration[];
/** List of the topology source nodes. Source nodes enable external data to be ingested by the pipeline. */
sources?: SourceNodeBaseUnion[];
/** List of the topology processor nodes. Processor nodes enable pipeline data to be analyzed, processed or transformed. */
processors?: ProcessorNodeBaseUnion[];
/** List of the topology sink nodes. Sink nodes allow pipeline data to be stored or exported. */
sinks?: SinkNodeBaseUnion[];
}
/** Single topology parameter declaration. Declared parameters can and must be referenced throughout the topology and can optionally have default values to be used when they are not defined in the pipeline instances. */
export interface ParameterDeclaration {
/** Name of the parameter. */
name: string;
/** Type of the parameter. */
type: ParameterType;
/** Description of the parameter. */
description?: string;
/** The default value for the parameter to be used if the live pipeline does not specify a value. */
default?: string;
}
/** Base class for topology source nodes. */
export interface SourceNodeBase {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type":
| "#Microsoft.VideoAnalyzer.RtspSource"
| "#Microsoft.VideoAnalyzer.IotHubMessageSource";
/** Node name. Must be unique within the topology. */
name: string;
}
/** Base class for topology processor nodes. */
export interface ProcessorNodeBase {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type":
| "#Microsoft.VideoAnalyzer.MotionDetectionProcessor"
| "#Microsoft.VideoAnalyzer.ObjectTrackingProcessor"
| "#Microsoft.VideoAnalyzer.LineCrossingProcessor"
| "#Microsoft.VideoAnalyzer.ExtensionProcessorBase"
| "#Microsoft.VideoAnalyzer.GrpcExtension"
| "#Microsoft.VideoAnalyzer.HttpExtension"
| "#Microsoft.VideoAnalyzer.SignalGateProcessor"
| "#Microsoft.VideoAnalyzer.CognitiveServicesVisionProcessor";
/** Node name. Must be unique within the topology. */
name: string;
/** An array of upstream node references within the topology to be used as inputs for this node. */
inputs: NodeInput[];
}
/** Describes an input signal to be used on a pipeline node. */
export interface NodeInput {
/** The name of the upstream node in the pipeline which output is used as input of the current node. */
nodeName: string;
/** Allows for the selection of specific data streams (eg. video only) from another node. */
outputSelectors?: OutputSelector[];
}
/** Allows for the selection of particular streams from another node. */
export interface OutputSelector {
/** The property of the data stream to be used as the selection criteria. */
property?: OutputSelectorProperty;
/** The operator to compare properties by. */
operator?: OutputSelectorOperator;
/** Value to compare against. */
value?: string;
}
/** Base class for topology sink nodes. */
export interface SinkNodeBase {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type":
| "#Microsoft.VideoAnalyzer.IotHubMessageSink"
| "#Microsoft.VideoAnalyzer.FileSink"
| "#Microsoft.VideoAnalyzer.VideoSink";
/** Node name. Must be unique within the topology. */
name: string;
/** An array of upstream node references within the topology to be used as inputs for this node. */
inputs: NodeInput[];
}
/** Base class for endpoints. */
export interface EndpointBase {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type":
| "#Microsoft.VideoAnalyzer.UnsecuredEndpoint"
| "#Microsoft.VideoAnalyzer.TlsEndpoint";
/** Credentials to be presented to the endpoint. */
credentials?: CredentialsBaseUnion;
/** The endpoint URL for Video Analyzer to connect to. */
url: string;
}
/** Base class for credential objects. */
export interface CredentialsBase {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type":
| "#Microsoft.VideoAnalyzer.UsernamePasswordCredentials"
| "#Microsoft.VideoAnalyzer.HttpHeaderCredentials"
| "#Microsoft.VideoAnalyzer.SymmetricKeyCredentials";
}
/** Base class for certificate sources. */
export interface CertificateSource {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.PemCertificateList";
}
/** Options for controlling the validation of TLS endpoints. */
export interface TlsValidationOptions {
/** When set to 'true' causes the certificate subject name validation to be skipped. Default is 'false'. */
ignoreHostname?: string;
/** When set to 'true' causes the certificate chain trust validation to be skipped. Default is 'false'. */
ignoreSignature?: string;
}
/** Options for changing video publishing behavior on the video sink and output video. */
export interface VideoPublishingOptions {
/** When set to 'true' the video will publish preview images. Default is 'false'. */
enableVideoPreviewImage?: string;
}
/** Optional video properties to be used in case a new video resource needs to be created on the service. These will not take effect if the video already exists. */
export interface VideoCreationProperties {
/** Optional video title provided by the user. Value can be up to 256 characters long. */
title?: string;
/** Optional video description provided by the user. Value can be up to 2048 characters long. */
description?: string;
/** Video segment length indicates the length of individual video files (segments) which are persisted to storage. Smaller segments provide lower archive playback latency but generate larger volume of storage transactions. Larger segments reduce the amount of storage transactions while increasing the archive playback latency. Value must be specified in ISO8601 duration format (i.e. "PT30S" equals 30 seconds) and can vary between 30 seconds to 5 minutes, in 30 seconds increments. Changing this value after the video is initially created can lead to errors when uploading media to the archive. Default value is 30 seconds. */
segmentLength?: string;
/** Video retention period indicates how long the video is kept in storage, and must be a multiple of 1 day. For example, if this is set to 30 days, then content older than 30 days will be deleted. */
retentionPeriod?: string;
}
/** Base class for named lines. */
export interface NamedLineBase {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.NamedLineString";
/** Line name. Must be unique within the node. */
name: string;
}
/** Image transformations and formatting options to be applied to the video frame(s). */
export interface ImageProperties {
/** Image scaling mode. */
scale?: ImageScale;
/** Base class for image formatting properties. */
format?: ImageFormatPropertiesUnion;
}
/** Image scaling mode. */
export interface ImageScale {
/** Describes the image scaling mode to be applied. Default mode is 'pad'. */
mode?: ImageScaleMode;
/** The desired output image width. */
width?: string;
/** The desired output image height. */
height?: string;
}
/** Base class for image formatting properties. */
export interface ImageFormatProperties {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type":
| "#Microsoft.VideoAnalyzer.ImageFormatRaw"
| "#Microsoft.VideoAnalyzer.ImageFormatJpeg"
| "#Microsoft.VideoAnalyzer.ImageFormatBmp"
| "#Microsoft.VideoAnalyzer.ImageFormatPng";
}
/** Defines how often media is submitted to the extension plugin. */
export interface SamplingOptions {
/** When set to 'true', prevents frames without upstream inference data to be sent to the extension plugin. This is useful to limit the frames sent to the extension to pre-analyzed frames only. For example, when used downstream from a motion detector, this can enable for only frames in which motion has been detected to be further analyzed. */
skipSamplesWithoutAnnotation?: string;
/** Maximum rate of samples submitted to the extension. This prevents an extension plugin to be overloaded with data. */
maximumSamplesPerSecond?: string;
}
/** Describes how media is transferred to the extension plugin. */
export interface GrpcExtensionDataTransfer {
/** The share memory buffer for sample transfers, in mebibytes. It can only be used with the 'SharedMemory' transfer mode. */
sharedMemorySizeMiB?: string;
/** Data transfer mode: embedded or sharedMemory. */
mode: GrpcExtensionDataTransferMode;
}
/** Describes the named polygon. */
export interface NamedPolygonBase {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.NamedPolygonString";
/** Polygon name. Must be unique within the node. */
name: string;
}
/** Base class for Azure Cognitive Services Spatial Analysis operations. */
export interface SpatialAnalysisOperationBase {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type":
| "#Microsoft.VideoAnalyzer.SpatialAnalysisCustomOperation"
| "SpatialAnalysisTypedOperationBase"
| "#Microsoft.VideoAnalyzer.SpatialAnalysisPersonCountOperation"
| "#Microsoft.VideoAnalyzer.SpatialAnalysisPersonZoneCrossingOperation"
| "#Microsoft.VideoAnalyzer.SpatialAnalysisPersonDistanceOperation"
| "#Microsoft.VideoAnalyzer.SpatialAnalysisPersonLineCrossingOperation";
}
/** Defines the Azure Cognitive Services Spatial Analysis operation eventing configuration. */
export interface SpatialAnalysisOperationEventBase {
/** The event threshold. */
threshold?: string;
/** The operation focus type. */
focus?: SpatialAnalysisOperationFocus;
}
export interface SpatialAnalysisPersonCountZoneEvents {
/** The named zone. */
zone: NamedPolygonBaseUnion;
/** The event configuration. */
events?: SpatialAnalysisPersonCountEvent[];
}
export interface SpatialAnalysisPersonZoneCrossingZoneEvents {
/** The named zone. */
zone: NamedPolygonBaseUnion;
/** The event configuration. */
events?: SpatialAnalysisPersonZoneCrossingEvent[];
}
export interface SpatialAnalysisPersonDistanceZoneEvents {
/** The named zone. */
zone: NamedPolygonBaseUnion;
/** The event configuration. */
events?: SpatialAnalysisPersonDistanceEvent[];
}
export interface SpatialAnalysisPersonLineCrossingLineEvents {
/** The named line. */
line: NamedLineBaseUnion;
/** The event configuration. */
events?: SpatialAnalysisPersonLineCrossingEvent[];
}
/** The Video Analyzer edge module can act as a transparent gateway for video, enabling IoT devices to send video to the cloud from behind a firewall. A remote device adapter should be created for each such IoT device. Communication between the cloud and IoT device would then flow via the Video Analyzer edge module. */
export interface RemoteDeviceAdapter {
/** The unique identifier for the remote device adapter. */
name: string;
/** Read-only system metadata associated with this object. */
systemData?: SystemData;
/** Properties of the remote device adapter. */
properties?: RemoteDeviceAdapterProperties;
}
/** Remote device adapter properties. */
export interface RemoteDeviceAdapterProperties {
/** An optional description for the remote device adapter. */
description?: string;
/** The IoT device to which this remote device will connect. */
target: RemoteDeviceAdapterTarget;
/** Information that enables communication between the IoT Hub and the IoT device - allowing this edge module to act as a transparent gateway between the two. */
iotHubDeviceConnection: IotHubDeviceConnection;
}
/** Properties of the remote device adapter target. */
export interface RemoteDeviceAdapterTarget {
/** Hostname or IP address of the remote device. */
host: string;
}
/** Information that enables communication between the IoT Hub and the IoT device - allowing this edge module to act as a transparent gateway between the two. */
export interface IotHubDeviceConnection {
/** The name of the IoT device configured and managed in IoT Hub. (case-sensitive) */
deviceId: string;
/** IoT device connection credentials. Currently IoT device symmetric key credentials are supported. */
credentials?: CredentialsBaseUnion;
}
/** A list of remote device adapters. */
export interface RemoteDeviceAdapterCollection {
/** An array of remote device adapters. */
value?: RemoteDeviceAdapter[];
/** A continuation token to use in subsequent calls to enumerate through the remote device adapter collection. This is used when the collection contains too many results to return in one response. */
continuationToken?: string;
}
/** A list of ONVIF devices that were discovered in the same subnet as the IoT Edge device. */
export interface DiscoveredOnvifDeviceCollection {
/** An array of ONVIF devices that have been discovered in the same subnet as the IoT Edge device. */
value?: DiscoveredOnvifDevice[];
}
/** The discovered properties of the ONVIF device that are returned during the discovery. */
export interface DiscoveredOnvifDevice {
/** The unique identifier of the ONVIF device that was discovered in the same subnet as the IoT Edge device. */
serviceIdentifier?: string;
/** The IP address of the ONVIF device that was discovered in the same subnet as the IoT Edge device. */
remoteIPAddress?: string;
/** An array of hostnames for the ONVIF discovered devices that are in the same subnet as the IoT Edge device. */
scopes?: string[];
/** An array of media profile endpoints that the ONVIF discovered device supports. */
endpoints?: string[];
}
/** The ONVIF device properties. */
export interface OnvifDevice {
/** The hostname of the ONVIF device. */
hostname?: OnvifHostName;
/** The system date and time of the ONVIF device. */
systemDateTime?: OnvifSystemDateTime;
/** The ONVIF device DNS properties. */
dns?: OnvifDns;
/** An array of of ONVIF media profiles supported by the ONVIF device. */
mediaProfiles?: MediaProfile[];
}
/** The ONVIF device DNS properties. */
export interface OnvifHostName {
/** Result value showing if the ONVIF device is configured to use DHCP. */
fromDhcp?: boolean;
/** The hostname of the ONVIF device. */
hostname?: string;
}
/** The ONVIF device DNS properties. */
export interface OnvifSystemDateTime {
/** An enum value determining whether the date time was configured using NTP or manual. */
type?: OnvifSystemDateTimeType;
/** The device datetime returned when calling the request. */
time?: string;
/** The timezone of the ONVIF device datetime. */
timeZone?: string;
}
/** The ONVIF device DNS properties. */
export interface OnvifDns {
/** Result value showing if the ONVIF device is configured to use DHCP. */
fromDhcp?: boolean;
/** An array of IPv4 address for the discovered ONVIF device. */
ipv4Address?: string[];
/** An array of IPv6 address for the discovered ONVIF device. */
ipv6Address?: string[];
}
/** Class representing the ONVIF MediaProfiles. */
export interface MediaProfile {
/** The name of the Media Profile. */
name?: string;
/** Object representing the URI that will be used to request for media streaming. */
mediaUri?: Record<string, unknown>;
/** The Video encoder configuration. */
videoEncoderConfiguration?: VideoEncoderConfiguration;
}
/** Class representing the MPEG4 Configuration. */
export interface VideoEncoderConfiguration {
/** The video codec used by the Media Profile. */
encoding?: VideoEncoding;
/** Relative value representing the quality of the video. */
quality?: number;
/** The Video Resolution. */
resolution?: VideoResolution;
/** The Video's rate control. */
rateControl?: RateControl;
/** The H264 Configuration. */
h264?: H264Configuration;
/** The H264 Configuration. */
mpeg4?: Mpeg4Configuration;
}
/** The Video resolution. */
export interface VideoResolution {
/** The number of columns of the Video image. */
width?: number;
/** The number of lines of the Video image. */
height?: number;
}
/** Class representing the video's rate control. */
export interface RateControl {
/** the maximum output bitrate in kbps. */
bitRateLimit?: number;
/** Interval at which images are encoded and transmitted. */
encodingInterval?: number;
/** Maximum output framerate in fps. */
frameRateLimit?: number;
/** A value of true indicates that frame rate is a fixed value rather than an upper limit, and that the video encoder shall prioritize frame rate over all other adaptable configuration values such as bitrate. */
guaranteedFrameRate?: boolean;
}
/** Class representing the H264 Configuration. */
export interface H264Configuration {
/** Group of Video frames length. */
govLength?: number;
/** The H264 Profile */
profile?: H264Profile;
}
/** Class representing the MPEG4 Configuration. */
export interface Mpeg4Configuration {
/** Group of Video frames length. */
govLength?: number;
/** The MPEG4 Profile */
profile?: Mpeg4Profile;
}
/** Object representing the URI that will be used to request for media streaming. */
export interface MediaUri {
/** URI that can be used for media streaming. */
uri?: string;
}
/** Base class for direct method calls. */
export interface MethodRequest {
/** Polymorphic discriminator, which specifies the different types this object can be */
methodName: "undefined";
/** Video Analyzer API version. */
apiVersion?: "1.1";
}
/** RTSP source allows for media from an RTSP camera or generic RTSP server to be ingested into a live pipeline. */
export type RtspSource = SourceNodeBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.RtspSource";
/** Network transport utilized by the RTSP and RTP exchange: TCP or HTTP. When using TCP, the RTP packets are interleaved on the TCP RTSP connection. When using HTTP, the RTSP messages are exchanged through long lived HTTP connections, and the RTP packages are interleaved in the HTTP connections alongside the RTSP messages. */
transport?: RtspTransport;
/** RTSP endpoint information for Video Analyzer to connect to. This contains the required information for Video Analyzer to connect to RTSP cameras and/or generic RTSP servers. */
endpoint: EndpointBaseUnion;
};
/** IoT Hub Message source allows for the pipeline to consume messages from the IoT Edge Hub. Messages can be routed from other IoT modules via routes declared in the IoT Edge deployment manifest. */
export type IotHubMessageSource = SourceNodeBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.IotHubMessageSource";
/** Name of the IoT Edge Hub input from which messages will be consumed. */
hubInputName?: string;
};
/** Motion detection processor allows for motion detection on the video stream. It generates motion events whenever motion is present on the video. */
export type MotionDetectionProcessor = ProcessorNodeBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.MotionDetectionProcessor";
/** Motion detection sensitivity: low, medium, high. */
sensitivity?: MotionDetectionSensitivity;
/** Indicates whether the processor should detect and output the regions within the video frame where motion was detected. Default is true. */
outputMotionRegion?: boolean;
/** Time window duration on which events are aggregated before being emitted. Value must be specified in ISO8601 duration format (i.e. "PT2S" equals 2 seconds). Use 0 seconds for no aggregation. Default is 1 second. */
eventAggregationWindow?: string;
};
/** Object tracker processor allows for continuous tracking of one of more objects over a finite sequence of video frames. It must be used downstream of an object detector extension node, thus allowing for the extension to be configured to to perform inferences on sparse frames through the use of the 'maximumSamplesPerSecond' sampling property. The object tracker node will then track the detected objects over the frames in which the detector is not invoked resulting on a smother tracking of detected objects across the continuum of video frames. The tracker will stop tracking objects which are not subsequently detected by the upstream detector on the subsequent detections. */
export type ObjectTrackingProcessor = ProcessorNodeBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.ObjectTrackingProcessor";
/** Object tracker accuracy: low, medium, high. Higher accuracy leads to higher CPU consumption in average. */
accuracy?: ObjectTrackingAccuracy;
};
/** Line crossing processor allows for the detection of tracked objects moving across one or more predefined lines. It must be downstream of an object tracker of downstream on an AI extension node that generates sequenceId for objects which are tracked across different frames of the video. Inference events are generated every time objects crosses from one side of the line to another. */
export type LineCrossingProcessor = ProcessorNodeBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.LineCrossingProcessor";
/** An array of lines used to compute line crossing events. */
lines: NamedLineBaseUnion[];
};
/** Base class for pipeline extension processors. Pipeline extensions allow for custom media analysis and processing to be plugged into the Video Analyzer pipeline. */
export type ExtensionProcessorBase = ProcessorNodeBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type":
| "#Microsoft.VideoAnalyzer.ExtensionProcessorBase"
| "#Microsoft.VideoAnalyzer.GrpcExtension"
| "#Microsoft.VideoAnalyzer.HttpExtension";
/** Endpoint details of the pipeline extension plugin. */
endpoint: EndpointBaseUnion;
/** Image transformations and formatting options to be applied to the video frame(s) prior submission to the pipeline extension plugin. */
image: ImageProperties;
/** Media sampling parameters that define how often media is submitted to the extension plugin. */
samplingOptions?: SamplingOptions;
};
/** A signal gate determines when to block (gate) incoming media, and when to allow it through. It gathers input events over the activationEvaluationWindow, and determines whether to open or close the gate. See https://aka.ms/ava-signalgate for more information. */
export type SignalGateProcessor = ProcessorNodeBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.SignalGateProcessor";
/** The period of time over which the gate gathers input events before evaluating them. */
activationEvaluationWindow?: string;
/** Signal offset once the gate is activated (can be negative). It determines the how much farther behind of after the signal will be let through based on the activation time. A negative offset indicates that data prior the activation time must be included on the signal that is let through, once the gate is activated. When used upstream of a file or video sink, this allows for scenarios such as recording buffered media prior an event, such as: record video 5 seconds prior motions is detected. */
activationSignalOffset?: string;
/** The minimum period for which the gate remains open in the absence of subsequent triggers (events). When used upstream of a file or video sink, it determines the minimum length of the recorded video clip. */
minimumActivationTime?: string;
/** The maximum period for which the gate remains open in the presence of subsequent triggers (events). When used upstream of a file or video sink, it determines the maximum length of the recorded video clip. */
maximumActivationTime?: string;
};
/** A processor that allows the pipeline topology to send video frames to a Cognitive Services Vision extension. Inference results are relayed to downstream nodes. */
export type CognitiveServicesVisionProcessor = ProcessorNodeBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.CognitiveServicesVisionProcessor";
/** Endpoint to which this processor should connect. */
endpoint: EndpointBaseUnion;
/** Describes the parameters of the image that is sent as input to the endpoint. */
image?: ImageProperties;
/** Describes the sampling options to be applied when forwarding samples to the extension. */
samplingOptions?: SamplingOptions;
/** Describes the Spatial Analysis operation to be used in the Cognitive Services Vision processor. */
operation: SpatialAnalysisOperationBaseUnion;
};
/** IoT Hub Message sink allows for pipeline messages to published into the IoT Edge Hub. Published messages can then be delivered to the cloud and other modules via routes declared in the IoT Edge deployment manifest. */
export type IotHubMessageSink = SinkNodeBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.IotHubMessageSink";
/** Name of the Iot Edge Hub output to which the messages will be published. */
hubOutputName: string;
};
/** File sink allows for video and audio content to be recorded on the file system on the edge device. */
export type FileSink = SinkNodeBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.FileSink";
/** Absolute directory path where media files will be stored. */
baseDirectoryPath: string;
/** File name pattern for creating new files when performing event based recording. The pattern must include at least one system variable. */
fileNamePattern: string;
/** Maximum amount of disk space that can be used for storing files from this sink. Once this limit is reached, the oldest files from this sink will be automatically deleted. */
maximumSizeMiB: string;
};
/** Video sink allows for video and audio to be recorded to the Video Analyzer service. The recorded video can be played from anywhere and further managed from the cloud. Due to security reasons, a given Video Analyzer edge module instance can only record content to new video entries, or existing video entries previously recorded by the same module. Any attempt to record content to an existing video which has not been created by the same module instance will result in failure to record. */
export type VideoSink = SinkNodeBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.VideoSink";
/** Name of a new or existing Video Analyzer video resource used for the media recording. */
videoName: string;
/** Optional video properties to be used in case a new video resource needs to be created on the service. */
videoCreationProperties?: VideoCreationProperties;
/** Optional video publishing options to be used for changing publishing behavior of the output video. */
videoPublishingOptions?: VideoPublishingOptions;
/** Path to a local file system directory for caching of temporary media files. This will also be used to store content which cannot be immediately uploaded to Azure due to Internet connectivity issues. */
localMediaCachePath: string;
/** Maximum amount of disk space that can be used for caching of temporary media files. Once this limit is reached, the oldest segments of the media archive will be continuously deleted in order to make space for new media, thus leading to gaps in the cloud recorded content. */
localMediaCacheMaximumSizeMiB: string;
};
/** Unsecured endpoint describes an endpoint that the pipeline can connect to over clear transport (no encryption in transit). */
export type UnsecuredEndpoint = EndpointBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.UnsecuredEndpoint";
};
/** TLS endpoint describes an endpoint that the pipeline can connect to over TLS transport (data is encrypted in transit). */
export type TlsEndpoint = EndpointBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.TlsEndpoint";
/** List of trusted certificate authorities when authenticating a TLS connection. A null list designates that Azure Video Analyzer's list of trusted authorities should be used. */
trustedCertificates?: CertificateSourceUnion;
/** Validation options to use when authenticating a TLS connection. By default, strict validation is used. */
validationOptions?: TlsValidationOptions;
};
/** Username and password credentials. */
export type UsernamePasswordCredentials = CredentialsBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.UsernamePasswordCredentials";
/** Username to be presented as part of the credentials. */
username: string;
/** Password to be presented as part of the credentials. It is recommended that this value is parameterized as a secret string in order to prevent this value to be returned as part of the resource on API requests. */
password: string;
};
/** HTTP header credentials. */
export type HttpHeaderCredentials = CredentialsBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.HttpHeaderCredentials";
/** HTTP header name. */
headerName: string;
/** HTTP header value. It is recommended that this value is parameterized as a secret string in order to prevent this value to be returned as part of the resource on API requests. */
headerValue: string;
};
/** Symmetric key credential. */
export type SymmetricKeyCredentials = CredentialsBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.SymmetricKeyCredentials";
/** Symmetric key credential. */
key: string;
};
/** A list of PEM formatted certificates. */
export type PemCertificateList = CertificateSource & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.PemCertificateList";
/** PEM formatted public certificates. One certificate per entry. */
certificates: string[];
};
/** Describes a line configuration. */
export type NamedLineString = NamedLineBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.NamedLineString";
/** Point coordinates for the line start and end, respectively. Example: '[[0.3, 0.2],[0.9, 0.8]]'. Each point is expressed as [LEFT, TOP] coordinate ratios ranging from 0.0 to 1.0, where [0,0] is the upper-left frame corner and [1, 1] is the bottom-right frame corner. */
line: string;
};
/** Raw image formatting. */
export type ImageFormatRaw = ImageFormatProperties & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.ImageFormatRaw";
/** Pixel format to be applied to the raw image. */
pixelFormat: ImageFormatRawPixelFormat;
};
/** JPEG image encoding. */
export type ImageFormatJpeg = ImageFormatProperties & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.ImageFormatJpeg";
/** Image quality value between 0 to 100 (best quality). */
quality?: string;
};
/** BMP image encoding. */
export type ImageFormatBmp = ImageFormatProperties & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.ImageFormatBmp";
};
/** PNG image encoding. */
export type ImageFormatPng = ImageFormatProperties & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.ImageFormatPng";
};
/** Describes a closed polygon configuration. */
export type NamedPolygonString = NamedPolygonBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.NamedPolygonString";
/** Point coordinates for the polygon. Example: '[[0.3, 0.2],[0.9, 0.8],[0.7, 0.6]]'. Each point is expressed as [LEFT, TOP] coordinate ratios ranging from 0.0 to 1.0, where [0,0] is the upper-left frame corner and [1, 1] is the bottom-right frame corner. */
polygon: string;
};
/** Defines a Spatial Analysis custom operation. This requires the Azure Cognitive Services Spatial analysis module to be deployed alongside the Video Analyzer module, please see https://aka.ms/ava-spatial-analysis for more information. */
export type SpatialAnalysisCustomOperation = SpatialAnalysisOperationBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.SpatialAnalysisCustomOperation";
/** Custom configuration to pass to the Azure Cognitive Services Spatial Analysis module. */
extensionConfiguration: string;
};
/** Base class for Azure Cognitive Services Spatial Analysis typed operations. */
export type SpatialAnalysisTypedOperationBase = SpatialAnalysisOperationBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type":
| "SpatialAnalysisTypedOperationBase"
| "#Microsoft.VideoAnalyzer.SpatialAnalysisPersonCountOperation"
| "#Microsoft.VideoAnalyzer.SpatialAnalysisPersonZoneCrossingOperation"
| "#Microsoft.VideoAnalyzer.SpatialAnalysisPersonDistanceOperation"
| "#Microsoft.VideoAnalyzer.SpatialAnalysisPersonLineCrossingOperation";
/** If set to 'true', enables debugging mode for this operation. */
debug?: string;
/** Advanced calibration configuration. */
calibrationConfiguration?: string;
/** Advanced camera configuration. */
cameraConfiguration?: string;
/** Advanced camera calibrator configuration. */
cameraCalibratorNodeConfiguration?: string;
/** Advanced detector node configuration. */
detectorNodeConfiguration?: string;
/** Advanced tracker node configuration. */
trackerNodeConfiguration?: string;
/** If set to 'true', enables face mask detection for this operation. */
enableFaceMaskClassifier?: string;
};
/** Defines a Spatial Analysis person count operation eventing configuration. */
export type SpatialAnalysisPersonCountEvent = SpatialAnalysisOperationEventBase & {
/** The event trigger type. */
trigger?: SpatialAnalysisPersonCountEventTrigger;
/** The event or interval output frequency. */
outputFrequency?: string;
};
/** Defines a Spatial Analysis person crossing zone operation eventing configuration. */
export type SpatialAnalysisPersonZoneCrossingEvent = SpatialAnalysisOperationEventBase & {
/** The event type. */
eventType?: SpatialAnalysisPersonZoneCrossingEventType;
};
/** Defines a Spatial Analysis person distance operation eventing configuration. */
export type SpatialAnalysisPersonDistanceEvent = SpatialAnalysisOperationEventBase & {
/** The event trigger type. */
trigger?: SpatialAnalysisPersonDistanceEventTrigger;
/** The event or interval output frequency. */
outputFrequency?: string;
/** The minimum distance threshold */
minimumDistanceThreshold?: string;
/** The maximum distance threshold */
maximumDistanceThreshold?: string;
};
/** Defines a Spatial Analysis person line crossing operation eventing configuration. */
export type SpatialAnalysisPersonLineCrossingEvent = SpatialAnalysisOperationEventBase & {};
/** GRPC extension processor allows pipeline extension plugins to be connected to the pipeline through over a gRPC channel. Extension plugins must act as an gRPC server. Please see https://aka.ms/ava-extension-grpc for details. */
export type GrpcExtension = ExtensionProcessorBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.GrpcExtension";
/** Specifies how media is transferred to the extension plugin. */
dataTransfer: GrpcExtensionDataTransfer;
/** An optional configuration string that is sent to the extension plugin. The configuration string is specific to each custom extension and it not understood neither validated by Video Analyzer. Please see https://aka.ms/ava-extension-grpc for details. */
extensionConfiguration?: string;
};
/** HTTP extension processor allows pipeline extension plugins to be connected to the pipeline through over the HTTP protocol. Extension plugins must act as an HTTP server. Please see https://aka.ms/ava-extension-http for details. */
export type HttpExtension = ExtensionProcessorBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.HttpExtension";
};
/** Defines a Spatial Analysis person count operation. This requires the Azure Cognitive Services Spatial analysis module to be deployed alongside the Video Analyzer module, please see https://aka.ms/ava-spatial-analysis for more information. */
export type SpatialAnalysisPersonCountOperation = SpatialAnalysisTypedOperationBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.SpatialAnalysisPersonCountOperation";
/** The list of zones and optional events. */
zones: SpatialAnalysisPersonCountZoneEvents[];
};
/** Defines a Spatial Analysis person zone crossing operation. This requires the Azure Cognitive Services Spatial analysis module to be deployed alongside the Video Analyzer module, please see https://aka.ms/ava-spatial-analysis for more information. */
export type SpatialAnalysisPersonZoneCrossingOperation = SpatialAnalysisTypedOperationBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.SpatialAnalysisPersonZoneCrossingOperation";
/** The list of zones with optional events. */
zones: SpatialAnalysisPersonZoneCrossingZoneEvents[];
};
/** Defines a Spatial Analysis person distance operation. This requires the Azure Cognitive Services Spatial analysis module to be deployed alongside the Video Analyzer module, please see https://aka.ms/ava-spatial-analysis for more information. */
export type SpatialAnalysisPersonDistanceOperation = SpatialAnalysisTypedOperationBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.SpatialAnalysisPersonDistanceOperation";
/** The list of zones with optional events. */
zones: SpatialAnalysisPersonDistanceZoneEvents[];
};
/** Defines a Spatial Analysis person line crossing operation. This requires the Azure Cognitive Services Spatial analysis module to be deployed alongside the Video Analyzer module, please see https://aka.ms/ava-spatial-analysis for more information. */
export type SpatialAnalysisPersonLineCrossingOperation = SpatialAnalysisTypedOperationBase & {
/** Polymorphic discriminator, which specifies the different types this object can be */
"@type": "#Microsoft.VideoAnalyzer.SpatialAnalysisPersonLineCrossingOperation";
/** The list of lines with optional events. */
lines: SpatialAnalysisPersonLineCrossingLineEvents[];
};
/** Known values of {@link LivePipelineState} that the service accepts. */
export enum KnownLivePipelineState {
/** The live pipeline is idle and not processing media. */
Inactive = "inactive",
/** The live pipeline is transitioning into the active state. */
Activating = "activating",
/** The live pipeline is active and able to process media. If your data source is not available, for instance, if your RTSP camera is powered off or unreachable, the pipeline will still be active and periodically retrying the connection. Your Azure subscription will be billed for the duration in which the live pipeline is in the active state. */
Active = "active",
/** The live pipeline is transitioning into the inactive state. */
Deactivating = "deactivating"
}
/**
* Defines values for LivePipelineState. \
* {@link KnownLivePipelineState} can be used interchangeably with LivePipelineState,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **inactive**: The live pipeline is idle and not processing media. \
* **activating**: The live pipeline is transitioning into the active state. \
* **active**: The live pipeline is active and able to process media. If your data source is not available, for instance, if your RTSP camera is powered off or unreachable, the pipeline will still be active and periodically retrying the connection. Your Azure subscription will be billed for the duration in which the live pipeline is in the active state. \
* **deactivating**: The live pipeline is transitioning into the inactive state.
*/
export type LivePipelineState = string;
/** Known values of {@link ParameterType} that the service accepts. */
export enum KnownParameterType {
/** The parameter's value is a string. */
String = "string",
/** The parameter's value is a string that holds sensitive information. */
SecretString = "secretString",
/** The parameter's value is a 32-bit signed integer. */
Int = "int",
/** The parameter's value is a 64-bit double-precision floating point. */
Double = "double",
/** The parameter's value is a boolean value that is either true or false. */
Bool = "bool"
}
/**
* Defines values for ParameterType. \
* {@link KnownParameterType} can be used interchangeably with ParameterType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **string**: The parameter's value is a string. \
* **secretString**: The parameter's value is a string that holds sensitive information. \
* **int**: The parameter's value is a 32-bit signed integer. \
* **double**: The parameter's value is a 64-bit double-precision floating point. \
* **bool**: The parameter's value is a boolean value that is either true or false.
*/
export type ParameterType = string;
/** Known values of {@link OutputSelectorProperty} that the service accepts. */
export enum KnownOutputSelectorProperty {
/** The stream's MIME type or subtype: audio, video or application */
MediaType = "mediaType"
}
/**
* Defines values for OutputSelectorProperty. \
* {@link KnownOutputSelectorProperty} can be used interchangeably with OutputSelectorProperty,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **mediaType**: The stream's MIME type or subtype: audio, video or application
*/
export type OutputSelectorProperty = string;
/** Known values of {@link OutputSelectorOperator} that the service accepts. */
export enum KnownOutputSelectorOperator {
/** The property is of the type defined by value. */
Is = "is",
/** The property is not of the type defined by value. */
IsNot = "isNot"
}
/**
* Defines values for OutputSelectorOperator. \
* {@link KnownOutputSelectorOperator} can be used interchangeably with OutputSelectorOperator,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **is**: The property is of the type defined by value. \
* **isNot**: The property is not of the type defined by value.
*/
export type OutputSelectorOperator = string;
/** Known values of {@link RtspTransport} that the service accepts. */
export enum KnownRtspTransport {
/** HTTP transport. RTSP messages are exchanged over long running HTTP requests and RTP packets are interleaved within the HTTP channel. */
Http = "http",
/** TCP transport. RTSP is used directly over TCP and RTP packets are interleaved within the TCP channel. */
Tcp = "tcp"
}
/**
* Defines values for RtspTransport. \
* {@link KnownRtspTransport} can be used interchangeably with RtspTransport,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **http**: HTTP transport. RTSP messages are exchanged over long running HTTP requests and RTP packets are interleaved within the HTTP channel. \
* **tcp**: TCP transport. RTSP is used directly over TCP and RTP packets are interleaved within the TCP channel.
*/
export type RtspTransport = string;
/** Known values of {@link MotionDetectionSensitivity} that the service accepts. */
export enum KnownMotionDetectionSensitivity {
/** Low sensitivity. */
Low = "low",
/** Medium sensitivity. */
Medium = "medium",
/** High sensitivity. */
High = "high"
}
/**
* Defines values for MotionDetectionSensitivity. \
* {@link KnownMotionDetectionSensitivity} can be used interchangeably with MotionDetectionSensitivity,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **low**: Low sensitivity. \
* **medium**: Medium sensitivity. \
* **high**: High sensitivity.
*/
export type MotionDetectionSensitivity = string;
/** Known values of {@link ObjectTrackingAccuracy} that the service accepts. */
export enum KnownObjectTrackingAccuracy {
/** Low accuracy. */
Low = "low",
/** Medium accuracy. */
Medium = "medium",
/** High accuracy. */
High = "high"
}
/**
* Defines values for ObjectTrackingAccuracy. \
* {@link KnownObjectTrackingAccuracy} can be used interchangeably with ObjectTrackingAccuracy,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **low**: Low accuracy. \
* **medium**: Medium accuracy. \
* **high**: High accuracy.
*/
export type ObjectTrackingAccuracy = string;
/** Known values of {@link ImageScaleMode} that the service accepts. */
export enum KnownImageScaleMode {
/** Preserves the same aspect ratio as the input image. If only one image dimension is provided, the second dimension is calculated based on the input image aspect ratio. When 2 dimensions are provided, the image is resized to fit the most constraining dimension, considering the input image size and aspect ratio. */
PreserveAspectRatio = "preserveAspectRatio",
/** Pads the image with black horizontal stripes (letterbox) or black vertical stripes (pillar-box) so the image is resized to the specified dimensions while not altering the content aspect ratio. */
Pad = "pad",
/** Stretches the original image so it resized to the specified dimensions. */
Stretch = "stretch"
}
/**
* Defines values for ImageScaleMode. \
* {@link KnownImageScaleMode} can be used interchangeably with ImageScaleMode,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **preserveAspectRatio**: Preserves the same aspect ratio as the input image. If only one image dimension is provided, the second dimension is calculated based on the input image aspect ratio. When 2 dimensions are provided, the image is resized to fit the most constraining dimension, considering the input image size and aspect ratio. \
* **pad**: Pads the image with black horizontal stripes (letterbox) or black vertical stripes (pillar-box) so the image is resized to the specified dimensions while not altering the content aspect ratio. \
* **stretch**: Stretches the original image so it resized to the specified dimensions.
*/
export type ImageScaleMode = string;
/** Known values of {@link GrpcExtensionDataTransferMode} that the service accepts. */
export enum KnownGrpcExtensionDataTransferMode {
/** Media samples are embedded into the gRPC messages. This mode is less efficient but it requires a simpler implementations and can be used with plugins which are not on the same node as the Video Analyzer module. */
Embedded = "embedded",
/** Media samples are made available through shared memory. This mode enables efficient data transfers but it requires that the extension plugin to be co-located on the same node and sharing the same shared memory space. */
SharedMemory = "sharedMemory"
}
/**
* Defines values for GrpcExtensionDataTransferMode. \
* {@link KnownGrpcExtensionDataTransferMode} can be used interchangeably with GrpcExtensionDataTransferMode,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **embedded**: Media samples are embedded into the gRPC messages. This mode is less efficient but it requires a simpler implementations and can be used with plugins which are not on the same node as the Video Analyzer module. \
* **sharedMemory**: Media samples are made available through shared memory. This mode enables efficient data transfers but it requires that the extension plugin to be co-located on the same node and sharing the same shared memory space.
*/
export type GrpcExtensionDataTransferMode = string;
/** Known values of {@link ImageFormatRawPixelFormat} that the service accepts. */
export enum KnownImageFormatRawPixelFormat {
/** Planar YUV 4:2:0, 12bpp, (1 Cr and Cb sample per 2x2 Y samples). */
Yuv420P = "yuv420p",
/** Packed RGB 5:6:5, 16bpp, (msb) 5R 6G 5B(lsb), big-endian. */
Rgb565Be = "rgb565be",
/** Packed RGB 5:6:5, 16bpp, (msb) 5R 6G 5B(lsb), little-endian. */
Rgb565Le = "rgb565le",
/** Packed RGB 5:5:5, 16bpp, (msb)1X 5R 5G 5B(lsb), big-endian , X=unused/undefined. */
Rgb555Be = "rgb555be",
/** Packed RGB 5:5:5, 16bpp, (msb)1X 5R 5G 5B(lsb), little-endian, X=unused/undefined. */
Rgb555Le = "rgb555le",
/** Packed RGB 8:8:8, 24bpp, RGBRGB. */
Rgb24 = "rgb24",
/** Packed RGB 8:8:8, 24bpp, BGRBGR. */
Bgr24 = "bgr24",
/** Packed ARGB 8:8:8:8, 32bpp, ARGBARGB. */
Argb = "argb",
/** Packed RGBA 8:8:8:8, 32bpp, RGBARGBA. */
Rgba = "rgba",
/** Packed ABGR 8:8:8:8, 32bpp, ABGRABGR. */
Abgr = "abgr",
/** Packed BGRA 8:8:8:8, 32bpp, BGRABGRA. */
Bgra = "bgra"
}
/**
* Defines values for ImageFormatRawPixelFormat. \
* {@link KnownImageFormatRawPixelFormat} can be used interchangeably with ImageFormatRawPixelFormat,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **yuv420p**: Planar YUV 4:2:0, 12bpp, (1 Cr and Cb sample per 2x2 Y samples). \
* **rgb565be**: Packed RGB 5:6:5, 16bpp, (msb) 5R 6G 5B(lsb), big-endian. \
* **rgb565le**: Packed RGB 5:6:5, 16bpp, (msb) 5R 6G 5B(lsb), little-endian. \
* **rgb555be**: Packed RGB 5:5:5, 16bpp, (msb)1X 5R 5G 5B(lsb), big-endian , X=unused\/undefined. \
* **rgb555le**: Packed RGB 5:5:5, 16bpp, (msb)1X 5R 5G 5B(lsb), little-endian, X=unused\/undefined. \
* **rgb24**: Packed RGB 8:8:8, 24bpp, RGBRGB. \
* **bgr24**: Packed RGB 8:8:8, 24bpp, BGRBGR. \
* **argb**: Packed ARGB 8:8:8:8, 32bpp, ARGBARGB. \
* **rgba**: Packed RGBA 8:8:8:8, 32bpp, RGBARGBA. \
* **abgr**: Packed ABGR 8:8:8:8, 32bpp, ABGRABGR. \
* **bgra**: Packed BGRA 8:8:8:8, 32bpp, BGRABGRA.
*/
export type ImageFormatRawPixelFormat = string;
/** Known values of {@link SpatialAnalysisOperationFocus} that the service accepts. */
export enum KnownSpatialAnalysisOperationFocus {
/** The center of the object. */
Center = "center",
/** The bottom center of the object. */
BottomCenter = "bottomCenter",
/** The footprint. */
Footprint = "footprint"
}
/**
* Defines values for SpatialAnalysisOperationFocus. \
* {@link KnownSpatialAnalysisOperationFocus} can be used interchangeably with SpatialAnalysisOperationFocus,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **center**: The center of the object. \
* **bottomCenter**: The bottom center of the object. \
* **footprint**: The footprint.
*/
export type SpatialAnalysisOperationFocus = string;
/** Known values of {@link SpatialAnalysisPersonCountEventTrigger} that the service accepts. */
export enum KnownSpatialAnalysisPersonCountEventTrigger {
/** Event trigger. */
Event = "event",
/** Interval trigger. */
Interval = "interval"
}
/**
* Defines values for SpatialAnalysisPersonCountEventTrigger. \
* {@link KnownSpatialAnalysisPersonCountEventTrigger} can be used interchangeably with SpatialAnalysisPersonCountEventTrigger,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **event**: Event trigger. \
* **interval**: Interval trigger.
*/
export type SpatialAnalysisPersonCountEventTrigger = string;
/** Known values of {@link SpatialAnalysisPersonZoneCrossingEventType} that the service accepts. */
export enum KnownSpatialAnalysisPersonZoneCrossingEventType {
/** Zone crossing event type. */
ZoneCrossing = "zoneCrossing",
/** Zone dwell time event type. */
ZoneDwellTime = "zoneDwellTime"
}
/**
* Defines values for SpatialAnalysisPersonZoneCrossingEventType. \
* {@link KnownSpatialAnalysisPersonZoneCrossingEventType} can be used interchangeably with SpatialAnalysisPersonZoneCrossingEventType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **zoneCrossing**: Zone crossing event type. \
* **zoneDwellTime**: Zone dwell time event type.
*/
export type SpatialAnalysisPersonZoneCrossingEventType = string;
/** Known values of {@link SpatialAnalysisPersonDistanceEventTrigger} that the service accepts. */
export enum KnownSpatialAnalysisPersonDistanceEventTrigger {
/** Event trigger. */
Event = "event",
/** Interval trigger. */
Interval = "interval"
}
/**
* Defines values for SpatialAnalysisPersonDistanceEventTrigger. \
* {@link KnownSpatialAnalysisPersonDistanceEventTrigger} can be used interchangeably with SpatialAnalysisPersonDistanceEventTrigger,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **event**: Event trigger. \
* **interval**: Interval trigger.
*/
export type SpatialAnalysisPersonDistanceEventTrigger = string;
/** Known values of {@link OnvifSystemDateTimeType} that the service accepts. */
export enum KnownOnvifSystemDateTimeType {
Ntp = "Ntp",
Manual = "Manual"
}
/**
* Defines values for OnvifSystemDateTimeType. \
* {@link KnownOnvifSystemDateTimeType} can be used interchangeably with OnvifSystemDateTimeType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Ntp** \
* **Manual**
*/
export type OnvifSystemDateTimeType = string;
/** Known values of {@link VideoEncoding} that the service accepts. */
export enum KnownVideoEncoding {
/** The Media Profile uses JPEG encoding. */
Jpeg = "JPEG",
/** The Media Profile uses H264 encoding. */
H264 = "H264",
/** The Media Profile uses MPEG4 encoding. */
Mpeg4 = "MPEG4"
}
/**
* Defines values for VideoEncoding. \
* {@link KnownVideoEncoding} can be used interchangeably with VideoEncoding,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **JPEG**: The Media Profile uses JPEG encoding. \
* **H264**: The Media Profile uses H264 encoding. \
* **MPEG4**: The Media Profile uses MPEG4 encoding.
*/
export type VideoEncoding = string;
/** Known values of {@link H264Profile} that the service accepts. */
export enum KnownH264Profile {
Baseline = "Baseline",
Main = "Main",
Extended = "Extended",
High = "High"
}
/**
* Defines values for H264Profile. \
* {@link KnownH264Profile} can be used interchangeably with H264Profile,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Baseline** \
* **Main** \
* **Extended** \
* **High**
*/
export type H264Profile = string;
/** Known values of {@link Mpeg4Profile} that the service accepts. */
export enum KnownMpeg4Profile {
/** Simple Profile. */
SP = "SP",
/** Advanced Simple Profile. */
ASP = "ASP"
}
/**
* Defines values for Mpeg4Profile. \
* {@link KnownMpeg4Profile} can be used interchangeably with Mpeg4Profile,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **SP**: Simple Profile. \
* **ASP**: Advanced Simple Profile.
*/
export type Mpeg4Profile = string;
/** Optional parameters. */
export interface GeneratedClientOptionalParams
extends coreClient.ServiceClientOptions {
/** Overrides client endpoint. */
endpoint?: string;
} | the_stack |
module BABYLON {
// logging stuffs
export class C2DLogging {
// Set to true to temporary disable logging.
public static snooze = true;
public static logFrameRender(frameCount: number) {
C2DLogging.snooze = true;
C2DLogging._logFramesCount = frameCount;
}
public static setPostMessage(message: () => string) {
if (C2DLoggingInternals.enableLog) {
C2DLoggingInternals.postMessages[C2DLoggingInternals.callDepth-1] = message();
}
}
public static _startFrameRender() {
if (C2DLogging._logFramesCount === 0) {
return;
}
C2DLogging.snooze = false;
}
public static _endFrameRender() {
if (C2DLogging._logFramesCount === 0) {
return;
}
C2DLogging.snooze = true;
--C2DLogging._logFramesCount;
}
private static _logFramesCount = 0;
}
class C2DLoggingInternals {
//-------------FLAG TO CHANGE TO ENABLE/DISABLE LOGGING ACTIVATION--------------
// This flag can't be changed at runtime you must manually change it in the code
public static enableLog = false;
public static callDepth = 0;
public static depths = [
"|-", "|--", "|---", "|----", "|-----", "|------", "|-------", "|--------", "|---------", "|----------",
"|-----------", "|------------", "|-------------", "|--------------", "|---------------", "|----------------", "|-----------------", "|------------------", "|-------------------", "|--------------------"
];
public static postMessages = [];
public static computeIndent(): string {
// Compute the indent
let indent: string = null;
if (C2DLoggingInternals.callDepth < 20) {
indent = C2DLoggingInternals.depths[C2DLoggingInternals.callDepth];
} else {
indent = "|";
for (let i = 0; i <= C2DLoggingInternals.callDepth; i++) {
indent = indent + "-";
}
}
return indent;
}
public static getFormattedValue(a): string {
if (a instanceof Prim2DBase) {
return a.id;
}
if (a == null) {
return "[null]";
}
return a.toString();
}
}
export function logProp<T>(message: string = "", alsoGet = false, setNoProlog=false, getNoProlog=false): (target: Object, propName: string | symbol, descriptor: TypedPropertyDescriptor<T>) => void {
return (target: Object, propName: string | symbol, descriptor: TypedPropertyDescriptor<T>) => {
if (!C2DLoggingInternals.enableLog) {
return descriptor;
}
let getter = descriptor.get, setter = descriptor.set;
if (getter && alsoGet) {
descriptor.get = function (): T {
if (C2DLogging.snooze) {
return getter.call(this);
} else {
let indent = C2DLoggingInternals.computeIndent();
let id = this.id || "";
if (message !== null && message !== "") {
console.log(message);
}
let isSPP = this instanceof SmartPropertyPrim;
let flags = isSPP ? this._flags : 0;
let depth = C2DLoggingInternals.callDepth;
if (!getNoProlog) {
console.log(`${indent} [${id}] (${depth}) ==> get ${propName} property`);
}
++C2DLoggingInternals.callDepth;
C2DLogging.setPostMessage(() => "[no msg]");
// Call the initial getter
let r = getter.call(this);
--C2DLoggingInternals.callDepth;
let flagsStr = "";
if (isSPP) {
let nflags = this._flags;
let newFlags = this._getFlagsDebug((nflags & flags) ^ nflags);
let removedFlags = this._getFlagsDebug((nflags & flags) ^ flags);
flagsStr = "";
if (newFlags !== "") {
flagsStr = ` +++[${newFlags}]`;
}
if (removedFlags !== "") {
if (flagsStr !== "") {
flagsStr += ",";
}
flagsStr += ` ---[${removedFlags}]`;
}
}
console.log(`${indent} [${id}] (${depth})${getNoProlog ? "" : " <=="} get ${propName} property => ${C2DLoggingInternals.getFormattedValue(r)}${flagsStr}, ${C2DLoggingInternals.postMessages[C2DLoggingInternals.callDepth]}`);
return r;
}
}
}
// Overload the property setter implementation to add our own logic
if (setter) {
descriptor.set = function (val) {
if (C2DLogging.snooze) {
setter.call(this, val);
} else {
let indent = C2DLoggingInternals.computeIndent();
let id = this.id || "";
if (message !== null && message !== "") {
console.log(message);
}
let isSPP = this instanceof SmartPropertyPrim;
let flags = isSPP ? this._flags : 0;
let depth = C2DLoggingInternals.callDepth;
if (!setNoProlog) {
console.log(`${indent} [${id}] (${depth}) ==> set ${propName} property with ${C2DLoggingInternals.getFormattedValue(val)}`);
}
++C2DLoggingInternals.callDepth;
C2DLogging.setPostMessage(() => "[no msg]");
// Change the value
setter.call(this, val);
--C2DLoggingInternals.callDepth;
let flagsStr = "";
if (isSPP) {
let nflags = this._flags;
let newFlags = this._getFlagsDebug((nflags & flags) ^ nflags);
let removedFlags = this._getFlagsDebug((nflags & flags) ^ flags);
flagsStr = "";
if (newFlags !== "") {
flagsStr = ` +++[${newFlags}]`;
}
if (removedFlags !== "") {
if (flagsStr !== "") {
flagsStr += ",";
}
flagsStr += ` ---[${removedFlags}]`;
}
}
console.log(`${indent} [${id}] (${depth})${setNoProlog ? "" : " <=="} set ${propName} property, ${C2DLoggingInternals.postMessages[C2DLoggingInternals.callDepth]}${flagsStr}`);
}
}
}
return descriptor;
}
}
export function logMethod(message: string = "", noProlog = false) {
return (target, key, descriptor) => {
if (!C2DLoggingInternals.enableLog) {
return descriptor;
}
if (descriptor === undefined) {
descriptor = Object.getOwnPropertyDescriptor(target, key);
}
var originalMethod = descriptor.value;
//editing the descriptor/value parameter
descriptor.value = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i - 0] = arguments[_i];
}
if (C2DLogging.snooze) {
return originalMethod.apply(this, args);
} else {
var a = args.map(a => C2DLoggingInternals.getFormattedValue(a) + ", ").join();
a = a.slice(0, a.length - 2);
let indent = C2DLoggingInternals.computeIndent();
let id = this.id || "";
if (message !== null && message !== "") {
console.log(message);
}
let isSPP = this instanceof SmartPropertyPrim;
let flags = isSPP ? this._flags : 0;
let depth = C2DLoggingInternals.callDepth;
if (!noProlog) {
console.log(`${indent} [${id}] (${depth}) ==> call: ${key} (${a})`);
}
++C2DLoggingInternals.callDepth;
C2DLogging.setPostMessage(() => "[no msg]");
// Call the method!
var result = originalMethod.apply(this, args);
--C2DLoggingInternals.callDepth;
let flagsStr = "";
if (isSPP) {
let nflags = this._flags;
let newFlags = this._getFlagsDebug((nflags & flags) ^ nflags);
let removedFlags = this._getFlagsDebug((nflags & flags) ^ flags);
flagsStr = "";
if (newFlags !== "") {
flagsStr = ` +++[${newFlags}]`;
}
if (removedFlags !== "") {
if (flagsStr !== "") {
flagsStr += ",";
}
flagsStr += ` ---[${removedFlags}]`;
}
}
console.log(`${indent} [${id}] (${depth})${noProlog ? "" : " <=="} call: ${key} (${a}) Res: ${C2DLoggingInternals.getFormattedValue(result)}, ${C2DLoggingInternals.postMessages[C2DLoggingInternals.callDepth]}${flagsStr}`);
return result;
}
};
// return edited descriptor as opposed to overwriting the descriptor
return descriptor;
}
}
} | the_stack |
// some types
interface PuzzleSides {
left?:-1|0|1;
top?:-1|0|1;
right?:-1|0|1;
bottom?:-1|0|1;
}
// constants
// these must remain 100 for the puzzle piece path stuff to work out
const piecewidth = 100;
const pieceheight = 100;
// const gridRows = 2;
const gridRows = 1; // Only one interactive row for now -JS
const pipelineRow = 0;
const gridOffset:fabric.Point = new fabric.Point(22,20);
const canvasHeightInteractive = gridRows*pieceheight+gridOffset.y*2;
// we should set canvas width appropriately
let totalCanvasWidth = 1000;
// Value for the 'accept' attribute for schema input (hardwired for now)
const schemaAccept = ".json,.schema,.io,.ddl";
// Value for the 'accept' attribute for non-csv data input (hardwired for now)
const dataAccept = ".json,.input,.io,.data";
// Error message for compile and execute tab when the source and target languages are not specified
const sourceAndTargetRequired = "[ Both source and target languages must specified ]";
// Error message for compile and execute (non-javascript) tab when the source and target languages are specified but the query src is not
const noQuerySrc = "[ Query contents have not been specified ]";
// Placeholder optimization when there are no optimizations chosen in a phase tab
const optPlaceholder = "Add optimizations here";
// global variables
// The web-worker that is actively running a query or null. The kill button should only be visible when this is non-null.
var worker:Worker = null;
// The top-level tab manager (providing access to it from global functions)
var tabManager:TabManager;
// The main canvas (for late (re)-construction of tabs to be replaced in the top-level tab manager
var mainCanvas:fabric.Canvas;
// Functions
// A placeholder to fetch ancillary information not currently in Qcert.LanguageDescription
// TODO integrate this
function getSourceLanguageExtraInfo(source:Qcert.Language) : {accept: string, schemaForCompile: boolean} {
switch (source) {
case "sql":
return {accept: ".sql", schemaForCompile: false};
case "sqlpp":
return {accept: ".sqlpp", schemaForCompile: false};
case "oql":
return {accept: ".oql", schemaForCompile: false};
case "lambda_nra":
return {accept: ".lnra", schemaForCompile: false};
case "tech_rule":
return {accept: ".arl", schemaForCompile: true};
case "designer_rule":
return {accept: ".sem", schemaForCompile: false};
case "camp_rule":
return {accept: ".rule,.camp", schemaForCompile: false};
default:
return undefined;
}
}
// Executes when the kill button is pressed. The kill button should only be visible when an execution is running, whether or not the execution tab is showing
function killButton() {
if (worker != null) {
worker.terminate();
worker = null;
const executing = getExecOutputArea();
if (executing != null)
executing.value = "[ Execution interrupted ]";
document.getElementById("kill-button").style.display = "none";
}
}
// Executes when compile button is pressed. This button shows when the compile tab shows.
function compileButton() {
const langs = getPipelineLangs();
const optimconf = getOptimConfig();
const srcInput = getSrcInput();
const schemaInput = getSchemaInput();
const theTextArea = <HTMLTextAreaElement>document.getElementById("compile-tab-query-output-text");
const path = langs.map(x => x.id);
if (path.length <= 2) {
theTextArea.value = sourceAndTargetRequired;
return;
} else if (srcInput.length == 0) {
theTextArea.value = noQuerySrc;
return;
} else if (schemaInput.length == 0 || schemaInput == "{}") {
if (getSourceLanguageExtraInfo(path[0]).schemaForCompile) {
theTextArea.value = "[ The " + path[0] + " language requires a schema for compilation ]";
return;
}
}
theTextArea.value = "[ Compiling query ]";
const middlePath = path.slice(1,-1);
const handler = function(resultPack: Qcert.Result) {
theTextArea.value = resultPack.result;
}
qcertWhiskDispatch({
source:path[0],
target:path[path.length-1],
path:middlePath,
exactpath:true,
emitall:true,
sourcesexp:false,
ascii:false,
javaimports:undefined,
query:srcInput,
schema: schemaInput,
eval:false,
input:undefined,
optims:JSON.stringify(optimconf) /* XXX Add optimizations here XXX */
}, handler);
}
// Executes when execute button is pressed. This button shows when the execute tab shows.
function executeButton() {
const langs = getPipelineLangs();
const optimconf = getOptimConfig();
const path = langs.map(x => x.id);
const executing = getExecOutputArea();
if (worker != null) {
executing.value = " [ A previous query is still executing and must be killed in order to execute a new one ]";
return;
}
if (path.length <= 2) {
executing.value = sourceAndTargetRequired;
return;
}
const dataInput = getIOInput();
if (dataInput.length == 0) {
executing.value = "[ No input data specified ]";
return;
}
executing.value = "[ Executing query ]";
// expose the kill button
document.getElementById("kill-button").style.display = "block";
// Additional inputs
const target = langs[langs.length-1].id;
const schemaInput = getSchemaInput();
// Setup to handle according to target language
const arg:any = target == "js" ? setupJsEval(dataInput, schemaInput) :
setupQcertEval(path, getSrcInput(), schemaInput, dataInput, optimconf);
if (arg == null) // error already detected and indicated
return;
// Processing is delegated to a web-worker
try {
// Worker variable is global (also executing and executingCanvas), making it (them) accessible to the killButton() function
worker = new Worker("evalWorker.js");
worker.onmessage = function(e) {
workerComplete(e.data);
}
worker.onerror = function(e) {
workerComplete(e.message);
}
console.log("About to post");
console.log(arg);
worker.postMessage(arg);
} catch (err) {
workerComplete(err.message);
}
}
function setupJsEval(inputString:string, schemaText:string) : [string,string,string] {
const compiledQuery = getCompiledQuery();
if (compiledQuery == null) {
const executing = getExecOutputArea();
executing.value = "[ The query has not been compiled ]";
return null;
}
return [inputString, schemaText, compiledQuery ];
}
function workerComplete(text:string) {
const executing = getExecOutputArea();
executing.value = text;
document.getElementById("kill-button").style.display = "none";
worker = null;
}
function setupQcertEval(path:string[], srcInput:string, schemaInput:string, dataInput:string,optimconf:Qcert.OptimConfig[]) : Qcert.CompilerConfig {
if (srcInput.length == 0) {
const executing = getExecOutputArea();
executing.value = noQuerySrc;
return null;
}
const middlePath = path.slice(1,-1);
return {source:path[0],
target:path[path.length-1],
path:middlePath,
exactpath:true,
emitall:true,
sourcesexp:false,
ascii:false,
javaimports:undefined,
query:srcInput,
schema: schemaInput,
eval: true,
input: dataInput,
optims:JSON.stringify(optimconf) /* XXX Add optimizations here XXX */
};
}
// Executes when defaults button is pushed on the optim config tab
function defaultConfig() {
setConfig(Qcert.optimDefaults().optims);
setConfigStatus("Default configuration was loaded.", false);
}
// Executes when clear button is pushed on the optim config tab
function clearConfig() {
setConfig(getClearConfig());
setConfigStatus("Configuration starting from scratch", false);
}
// Executes when save button is pushed on the optim config tab
function saveConfig() {
const config = JSON.stringify(getOptimConfig());
const blob = new Blob([config], {type: 'text/plain'});
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = "optimizations";
link.click();
}
function getClearConfig() {
function clearOptimsInOptimsList(optims:{[key: string]: string[];}) {
for(const k in Object.keys(optims)) {
optims[k] = [optPlaceholder];
}
}
function clearOptimsInPhaseList(array:Qcert.OptimPhase[]) {
array.forEach((elem) =>clearOptimsInOptimsList(elem.optims));
}
function clearOptimsInTopList(array:Qcert.OptimConfig[]) {
array.forEach((elem) => clearOptimsInPhaseList(elem.phases));
return array;
}
return clearOptimsInTopList(Qcert.optimDefaults().optims);
}
function setConfigStatus(text:string, usedFileChooser:boolean) {
const msgarea = document.getElementById('config-message');
msgarea.innerHTML = text;
if (usedFileChooser)
return;
// Buttons that alter the config without going through the file chooser should clear file chooser state, which is no longer valid
const chooser = document.getElementById('load-optims') as HTMLInputElement;
chooser.value = "";
}
function setConfig(optims) {
const newOptimsTab = OptimizationsTabMakeFromConfig(mainCanvas, optims);
tabManager.replaceTab(newOptimsTab, 1);
mainCanvas.renderAll();
}
function getSourceLeft(left:number):number {
return left*(piecewidth + 30) + 20;
}
function getSourceTop(top:number):number {
return canvasHeightInteractive + top*(pieceheight+30) + 20;
}
// The set of languages and their properties
// const srcLanguageGroups:SourceLanguageGroups = {
// frontend:[{langid:'sql', label:'SQL'}, {langid:'oql', label:'OQL'}],
// intermediate:[{langid:'nrae', label:'NRAenv'}, {langid:'nrc', label:'NNRC'}],
// backend:[{langid:'js', label:'javascript'}, {langid:'cloudant', label:'Cloudant'}]};
function toSrcLangDescript(color, sides:PuzzleSides) {
return function(group:Qcert.LanguageDescription) {
return {langid:group.langid, label:group.label, langdescription:group.description, fill:color, sides:sides};
}
}
function getSrcLangDescripts(langGroups:Qcert.SourceLanguageGroups) {
let ret = [];
ret.push(langGroups.frontend.map(toSrcLangDescript('#91D050', {right:-1})));
ret.push(langGroups.core.map(toSrcLangDescript('#7AB0DD', {left: 1, right:-1})))
ret.push(langGroups.distributed.map(toSrcLangDescript('#7AB0DD', {left: 1, right:-1})))
ret.push(langGroups.backend.map(toSrcLangDescript('#ED7D32', {left: 1})));
return ret;
}
// the boundary between the interactive and the selections
let separatorLine = new fabric.Line([ 0, canvasHeightInteractive, totalCanvasWidth, canvasHeightInteractive], { stroke: '#ccc', selectable: false });
function updateCanvasWidth(canvas:fabric.StaticCanvas, newWidth:number) {
totalCanvasWidth = newWidth;
canvas.setWidth(newWidth);
separatorLine.set('x2', newWidth);
}
function ensureCanvasWidth(canvas:fabric.StaticCanvas, newWidth:number) {
if(newWidth > totalCanvasWidth) {
updateCanvasWidth(canvas, newWidth);
}
}
function ensureCanvasInteractivePieceWidth(canvas:fabric.StaticCanvas, lastpiece:number) {
ensureCanvasWidth(canvas, lastpiece*piecewidth);
}
function ensureCanvasSourcePieceWidth(canvas:fabric.StaticCanvas, lastpiece:number) {
ensureCanvasWidth(canvas, getSourceLeft(lastpiece));
}
// Add support for hit testig individual objects in a group
// from http://stackoverflow.com/questions/15196603/using-containspoint-to-select-object-in-group#15210884
fabric.util.object.extend(fabric.Object.prototype, {
getAbsoluteCenterPoint: function() {
var point = this.getCenterPoint();
if (!this.group)
return point;
var groupPoint = this.group.getAbsoluteCenterPoint();
return {
x: point.x + groupPoint.x,
y: point.y + groupPoint.y
};
},
containsInGroupPoint: function(point) {
if (!this.group)
return this.containsPoint(point);
var center = this.getAbsoluteCenterPoint();
var thisPos = {
xStart: center.x - this.width/2,
xEnd: center.x + this.width/2,
yStart: center.y - this.height/2,
yEnd: center.y + this.height/2
}
if (point.x >= thisPos.xStart && point.x <= (thisPos.xEnd)) {
if (point.y >= thisPos.yStart && point.y <= thisPos.yEnd) {
return true;
}
}
return false;
}});
// based on code from https://www.codeproject.com/articles/395453/html-jigsaw-puzzle
function getMask(tileRatio, topTab, rightTab, bottomTab, leftTab) {
var curvyCoords = [ 0, 0, 35, 15, 37, 5, 37, 5, 40, 0, 38, -5, 38, -5,
20, -20, 50, -20, 50, -20, 80, -20, 62, -5, 62, -5, 60, 0, 63,
5, 63, 5, 65, 15, 100, 0 ];
const tileWidth = 100;
const tileHeight = 100;
var mask = "";
var leftx = -4;
var topy = 0;
var rightx = leftx + tileWidth;
var bottomy = topy + tileHeight;
mask += "M" + leftx + "," + topy;
//Top
for (var i = 0; i < curvyCoords.length / 6; i++) {
mask += "C";
mask += leftx + curvyCoords[i * 6 + 0] * tileRatio;
mask += ",";
mask += topy + topTab * curvyCoords[i * 6 + 1] * tileRatio;
mask += ",";
mask += leftx + curvyCoords[i * 6 + 2] * tileRatio;
mask += ",";
mask += topy + topTab * curvyCoords[i * 6 + 3] * tileRatio;
mask += ",";
mask += leftx + curvyCoords[i * 6 + 4] * tileRatio;
mask += ",";
mask += topy + topTab * curvyCoords[i * 6 + 5] * tileRatio;
}
//Right
for (var i = 0; i < curvyCoords.length / 6; i++) {
mask += "C";
mask += rightx - rightTab * curvyCoords[i * 6 + 1] * tileRatio;
mask += ",";
mask += topy + curvyCoords[i * 6 + 0] * tileRatio;
mask += ",";
mask += rightx - rightTab * curvyCoords[i * 6 + 3] * tileRatio;
mask += ",";
mask += topy + curvyCoords[i * 6 + 2] * tileRatio;
mask += ",";
mask += rightx - rightTab * curvyCoords[i * 6 + 5] * tileRatio;
mask += ",";
mask += topy + curvyCoords[i * 6 + 4] * tileRatio;
}
//Bottom
for (var i = 0; i < curvyCoords.length / 6; i++) {
mask += "C";
mask += rightx - curvyCoords[i * 6 + 0] * tileRatio;
mask += ",";
mask += bottomy - bottomTab*curvyCoords[i * 6 + 1] * tileRatio;
mask += ",";
mask += rightx - curvyCoords[i * 6 + 2] * tileRatio;
mask += ",";
mask += bottomy - bottomTab * curvyCoords[i * 6 + 3] * tileRatio;
mask += ",";
mask += rightx - curvyCoords[i * 6 + 4] * tileRatio;
mask += ",";
mask += bottomy - bottomTab * curvyCoords[i * 6 + 5] * tileRatio;
}
//Left
for (var i = 0; i < curvyCoords.length / 6; i++) {
mask += "C";
mask += leftx + leftTab * curvyCoords[i * 6 + 1] * tileRatio;
mask += ",";
mask += bottomy - curvyCoords[i * 6 + 0] * tileRatio;
mask += ",";
mask += leftx + leftTab * curvyCoords[i * 6 + 3] * tileRatio;
mask += ",";
mask += bottomy - curvyCoords[i * 6 + 2] * tileRatio;
mask += ",";
mask += leftx + leftTab * curvyCoords[i * 6 + 5] * tileRatio;
mask += ",";
mask += bottomy - curvyCoords[i * 6 + 4] * tileRatio;
}
return mask;
}
function makeToolTip(
tip:string,
canvas:fabric.StaticCanvas,
srcRect:{left:number, top:number, width:number, height:number},
tooltipOffset:fabric.Point,
textOptions:fabric.ITextOptions,
rectOptions:fabric.IRectOptions):fabric.Object {
const topts = fabric.util.object.clone(textOptions);
topts.left = 0;
topts.top = 0;
topts.editable = false;
const text = new fabric.IText(tip, topts);
// calculate where it should appear.
// if needed, shrink the font so that the text
// is not too large
let boundingBox = text.getBoundingRect();
const maxwidth = canvas.getWidth()*3/4;
while(boundingBox.width > maxwidth) {
text.setFontSize(text.getFontSize()-2);
text.setCoords();
boundingBox = text.getBoundingRect();
}
let piecemid = srcRect.left + Math.round(srcRect.width/2);
let boxleft = piecemid - Math.round(boundingBox.width / 2);
if(boxleft < 0) {
boxleft = 0;
} else {
let tryright = piecemid + Math.round(boundingBox.width / 2);
tryright = Math.min(tryright, canvas.getWidth());
boxleft = tryright - boundingBox.width;
}
let boxtop = srcRect.top - boundingBox.height - tooltipOffset.y;
if(boxtop < 0) {
boxtop = srcRect.top + srcRect.height + tooltipOffset.y;
}
text.originX = 'left';
text.left = boxleft;
text.originY = 'top';
text.top = boxtop;
text.setCoords();
const ropts = fabric.util.object.clone(rectOptions);
fabric.util.object.extend(ropts, text.getBoundingRect());
const box = new fabric.Rect(ropts);
const group = new fabric.Group([box, text]);
return group;
}
// interface IPuzzlePiece extends fabric.Object {
// // this should be in the fabric ts file
// canvas:fabric.StaticCanvas;
// // new stuff
// isSourcePiece?:boolean;
// isImplicit?:boolean;
// movePlace?:{left:number, top:number};
// langid:string;
// label:string;
// langdescription:string;
// tooltipObj?:fabric.Object;
// puzzleOffset:fabric.Point;
// getGridPoint:()=>fabric.Point;
// setGridPoint:(point:fabric.Point)=>void;
// setGridCoords:(x:number, y:number)=>void;
// // these are to help avoid accidentally setting
// // left or top without calling setCoords() after as required
// mySetLeft:(x:number)=>void;
// mySetTop:(y:number)=>void;
// mySetLeftAndTop:(x:number, y:number)=>void;
// readonly left:number;
// readonly top:number;
// }
// The class for a puzzle piece object
interface StringMap<V> {
[K: string]: V;
}
// Either move sourcePieces inside the builder or move its initialization
// out to avoid maintenance/ordering problems
// These are two critical arrays for the buider
// This is the collection of source pieces
var sourcePieces:StringMap<SourcePuzzlePiece> = {};
// This is the matrix of pieces that are in the grid
var placedPieces:BasicPuzzlePiece[][] = [];
let errorPiece:SourcePuzzlePiece;
// things that can be get/set via the grid
interface Griddable {
getGridPoint():fabric.Point;
setGridPoint(point:fabric.Point):void;
setGridCoords(x:number, y:number):void;
isTransient():boolean;
}
interface Displayable {
show();
hide();
}
interface fabricObjectExt extends fabric.Object {
canvas:fabric.Canvas;
}
// function ext(obj:fabric.Object):fabricObjectExt {
// return <fabricObjectExt>obj;
// }
// objects that wrap a fabric object
interface FrontingObject {
backingObject:fabricObjectExt;
associate();
deassociate();
}
function setBackingObject(f:FrontingObject, obj:fabric.Object) {
f.backingObject = <fabricObjectExt>obj;
}
// function assignBackingObject(frontingObject:FrontingObject, backingObject:fabric.Object) {
// // disassociate the backingObject from any previous owner
// if(isBackingObject(backingObject)) {
// const oldObject = backingObject.frontingObject;
// oldObject.deassociate();
// delete oldObject.backingObject;
// }
// (<any>backingObject).frontingObject = frontingObject;
// frontingObject.backingObject = <BackingObject>(backingObject);
// frontingObject.associate();
// }
abstract class GriddablePuzzlePiece implements Griddable {
getGridPoint():fabric.Point {
return new fabric.Point(
Math.round((this.backingObject.left + this.puzzleOffset.x - gridOffset.x) / piecewidth),
Math.round((this.backingObject.top + this.puzzleOffset.y - gridOffset.y) / pieceheight));
};
setGridPoint(point:{x:number, y:number}):void {
this.setGridCoords(point.x, point.y);
};
setGridCoords(x:number, y:number):void {
this.backingObject.left = x * piecewidth - this.puzzleOffset.x + gridOffset.x;
this.backingObject.top = y * pieceheight - this.puzzleOffset.y + gridOffset.y;
this.backingObject.setCoords();
};
static calcPuzzleEdgeOffset(side:number):number {
if(side < 0) {
return 9;
} else if(side > 0) {
return 20;
} else {
return 0;
}
}
abstract isTransient():boolean;
backingObject:fabricObjectExt;
puzzleOffset:fabric.Point;
}
class Grid {
static remove(location:{x:number, y:number}) {
let prow = placedPieces[location.y];
if(prow === undefined) {
return;
}
for(let i=location.x; i < prow.length; i++) {
const p = i+1 < prow.length ? prow[i+1] : undefined;
prow[i] = p;
if(p !== undefined) {
p.setGridCoords(i, location.y);
}
}
}
static removeAndHide(location:{x:number, y:number}) {
let prow = placedPieces[location.y];
if(prow === undefined) {
return;
}
const p = prow[location.x];
Grid.remove(location);
if(p !== undefined) {
p.hide();
}
}
static addAndShow(location:{x:number, y:number}, pieces:BasicPuzzlePiece|BasicPuzzlePiece[]) {
Grid.add(location, pieces);
if(pieces instanceof Array) {
pieces.forEach(function(p:BasicPuzzlePiece) {p.show();});
} else {
pieces.show();
}
}
/**
* @param location The location where the first piece will be inserted
* @param piece The piece(s) to be inserted. The piece
* locations are not set. If this is desired, call {@link fixup locations}
* @returns the number of pieces that were moved out of the way
*/
static add(location:{x:number, y:number}, pieces:BasicPuzzlePiece|BasicPuzzlePiece[]) {
let prow = placedPieces[location.y];
if(! (pieces instanceof Array)) {
pieces = [pieces];
}
const numPieces = pieces.length;
if(prow === undefined) {
prow = [];
placedPieces[location.y] = prow;
} else {
for(let i=prow.length-1; i >= location.x; i--) {
const p = prow[i];
const dest = i+numPieces;
if(p !== undefined) {
p.setGridCoords(dest, location.y);
}
prow[dest] = p;
}
}
for(let i=0; i < numPieces; i++) {
prow[location.x+i] = pieces[i];
}
}
static fixupLocations(location:{x:number, y:number}, pieces:number) {
const prow = placedPieces[location.y];
if(prow === undefined) {
return;
}
for(let i=0; i < pieces; i++) {
const x = location.x+i;
const p = prow[x];
if(p !== undefined) {
p.setGridCoords(x, location.y);
}
}
}
}
class BasicPuzzlePiece extends GriddablePuzzlePiece implements FrontingObject, Displayable {
langid:Qcert.Language;
langdescription:string;
previouslangid:Qcert.Language|null;
previouslabel:string|null;
isTransient() {
return true;
}
readonly canvas:fabric.Canvas;
options:any;
backingObject:fabricObjectExt;
show() {
this.canvas.add(this.backingObject);
}
hide() {
this.canvas.remove(this.backingObject);
}
static make(canvas:fabric.Canvas, previouslangid:Qcert.Language, previouslabel:string, options):BasicPuzzlePiece {
const p = new BasicPuzzlePiece(canvas, previouslangid, previouslabel, {options:options});
p.associate();
return p;
}
protected constructor(canvas:fabric.Canvas, previouslangid:Qcert.Language, previouslabel:string, args:{options:any} | {srcpuzzle:BasicPuzzlePiece}) {
super();
this.canvas = canvas;
if('options' in args) {
let options = (<any>args).options;
this.options = options;
options || (options = { });
options.width = piecewidth;
options.height = pieceheight;
const puzzleSides:PuzzleSides = options.sides || {};
const puzzleLeft = puzzleSides.left || 0;
const puzzleRight = puzzleSides.right || 0;
const puzzleTop = puzzleSides.top || 0;
const puzzleBottom = puzzleSides.bottom || 0;
const puzzleOffsetPoint = new fabric.Point(GriddablePuzzlePiece.calcPuzzleEdgeOffset(puzzleLeft),
GriddablePuzzlePiece.calcPuzzleEdgeOffset(puzzleTop));
options.left = getSourceLeft(options.col || 0) - puzzleOffsetPoint.x;
options.top = getSourceTop(options.row || 0) - puzzleOffsetPoint.y;
options.hasControls = false;
options.hasBorders = false;
const path = new fabric.Path(getMask(1, puzzleTop, puzzleRight, puzzleBottom, puzzleLeft), options);
// fix where the text appears
const text = new fabric.Text(options.label, {
fill: '#333',
fontFamily: 'sans-serif',
fontWeight: 'bold',
fontSize: 15,
left: options.left + 10 + (puzzleLeft > 0 ? 23 : 0),
top: options.top + 10
});
// const bbox = text.getBoundingRect();
const group = new fabric.Group([path, text],
{
hasControls:false,
hasBorders:false
});
setBackingObject(this, group);
this.puzzleOffset = puzzleOffsetPoint;
} else {
// steal from another puzzle
const src = (<any>args).srcpuzzle;
this.options = src.options;
this.backingObject = src.backingObject;
this.puzzleOffset = src.puzzleOffset;
}
}
deassociate() {
};
associate() {
};
// markSelected() {
// console.log('selecting: ' + this.langid);
// }
// group.makeUnselected = function() {
// console.log('deselecting: ' + this.langid);
// }
}
class InteractivePuzzlePiece extends BasicPuzzlePiece {
langid:Qcert.Language;
label:string;
langdescription:string;
previouslangid:Qcert.Language|null;
previouslabel:string|null;
movePlace?:{left:number, top:number};
isTransient() {
return false;
}
static make(canvas:fabric.Canvas, previouslangid:Qcert.Language, previouslabel:string, src:BasicPuzzlePiece):InteractivePuzzlePiece {
const p = new InteractivePuzzlePiece(canvas, previouslangid, previouslabel, {srcpuzzle:src});
p.associate();
return p;
}
public constructor(canvas:fabric.Canvas, previouslangid:Qcert.Language, previouslabel:string, args:{options:any} | {srcpuzzle:BasicPuzzlePiece}) {
super(canvas, previouslangid, previouslabel, args);
if('srcpuzzle' in args) {
const options = (<any>args).srcpuzzle;
this.langid = options.langid;
this.label = options.label;
this.langdescription = options.langdescription;
this.previouslangid = previouslangid;
this.previouslabel = previouslabel;
} else {
const options = (<any>args).options;
this.langid = options.langid;
this.label = options.label;
this.langdescription = options.langdescription;
this.previouslangid = previouslangid;
this.previouslabel = previouslabel;
}
}
associate() {
this.backingObject.selectable = true;
this.backingObject.hoverCursor = 'grab';
this.backingObject.moveCursor = 'grabbing';
this.backingObject.on('mousedown', this.mousedown);
this.backingObject.on('moving', this.moving);
this.backingObject.on('mouseup', this.mouseup);
}
disassociate() {
this.backingObject.off('mousedown', this.mousedown);
this.backingObject.off('moving', this.moving);
this.backingObject.off('mouseup', this.mouseup);
}
protected mousedown = () => {
// Update source browser to point to the IL definition -JS
// Dealing with window focus is annoying, so disabled for now - JS
if (this.previouslangid != null) {
var illoc = makeTransitionURL(this.previouslangid,this.previouslabel,this.langid,this.label);
var win = window.open(illoc, 'codebrowser');
window.focus();
}
const gp = this.getGridPoint();
this.backingObject.set({
opacity:0.5
});
this.movePlace = {left:gp.x, top:gp.y};
}
protected mouseup = () => {
this.backingObject.set({
opacity:1
});
const gridp = this.getGridPoint();
const leftentry = gridp.x;
const topentry = gridp.y;
this.setGridPoint(gridp);
// fix this to use grid coordinates
if(gridp.y < 0 || gridp.y >= gridRows) {
Grid.remove(gridp);
this.hide();
}
delete this.movePlace;
// find the rightmost entry in the row
const prow = placedPieces[topentry];
if(prow !== undefined) {
let maxcol:number;
for(maxcol = prow.length-1; maxcol >= 0; maxcol--) {
if(prow[maxcol] !== undefined) {
break;
}
}
ensureCanvasInteractivePieceWidth(this.canvas, maxcol+1);
}
// // update the placed grid
// if('movePlace' in this) {
// // finalize the moved pieces in their new positions
// const prow = placedPieces[topentry];
// if(! (prow === undefined)) {
// let curleft = leftentry;
// let curleftval = prow[leftentry];
// while(! (curleftval === undefined)) {
// let nextleft = curleft+1;
// let nextleftval = prow[nextleft];
// prow[nextleft] = curleftval;
// curleft = nextleft;
// curleftval = nextleftval;
// }
// ensureCanvasInteractivePieceWidth(this.canvas, curleft+1);
// prow[leftentry] = undefined;
// }
// delete this['movePlace'];
// }
// if(topentry >= placedPieces.length || placedPieces[topentry] === undefined) {
// placedPieces[topentry] = [];
// }
// const topplaces = placedPieces[topentry];
// if(leftentry >= topplaces.length || topplaces[leftentry] === undefined) {
// topplaces[leftentry] = this;
// }
// // finalize any left objects in their new positions
// // remove any transient path objects
// if('pathObjects' in this) {
// for(let i =0; i < this.PathObjects.length; i++) {
// const obj = this.PathObjects[i];
// this.backingObject.canvas.remove(obj.backingObject);
// }
// delete this.PathObjects;
// }
}
protected moving = ():any => {
const oldactualleft = this.backingObject.getLeft();
const oldactualtop = this.backingObject.getTop();
const gridp = this.getGridPoint();
const originalleftentry = gridp.x;
let leftentry = originalleftentry;
const topentry = gridp.y;
if('movePlace' in this) {
if(this.movePlace.left == leftentry && this.movePlace.top == topentry) {
// still over the same grid spot
return;
}
const oldtop = this.movePlace.top;
const oldleft = this.movePlace.left;
const prow = placedPieces[oldtop];
const shifted = InteractivePuzzlePiece.removeadjacentTransients({x:oldleft, y:oldtop});
const newleft = oldleft - shifted;
Grid.remove({x:newleft, y:oldtop});
InteractivePuzzlePiece.addTransientsBefore({x:newleft, y:oldtop});
}
// // destroy any associated objects
// if('pathObjects' in this) {
// for(let i =0; i < this.PathObjects.length; i++) {
// const obj = this.PathObjects[i];
// this.backingObject.canvas.remove(obj.backingObject);
// }
// delete this.PathObjects;
// }
// update, since it may have moved when we removed/added transients
leftentry = this.getGridPoint().x;
this.backingObject.moveCursor = 'grabbing';
const prow = placedPieces[topentry];
let shifted:number = 0;
if(prow !== undefined) {
const existingPiece = prow[leftentry];
if(existingPiece !== undefined) {
if(existingPiece.isTransient()) {
shifted = InteractivePuzzlePiece.removeadjacentTransients({x:leftentry, y:topentry});
leftentry = leftentry - shifted;
// also remove the current (transient) entry
Grid.removeAndHide({x:leftentry, y:topentry});
//leftentry = leftentry+1;
Grid.add({x:leftentry, y:topentry}, this);
} else {
Grid.add({x:leftentry, y:topentry}, this);
shifted = InteractivePuzzlePiece.removeadjacentTransients({x:leftentry, y:topentry});
leftentry = leftentry - shifted;
}
} else {
Grid.add({x:leftentry, y:topentry}, this);
}
} else {
Grid.add({x:leftentry, y:topentry}, this);
}
const movedBack:number = InteractivePuzzlePiece.addTransients({x:leftentry, y:topentry}, this);
leftentry = leftentry + movedBack;
if(leftentry == originalleftentry) {
// if this is where we started, restore the (unsnapped) coordinates
this.backingObject.setLeft(oldactualleft);
this.backingObject.setTop(oldactualtop);
} else {
this.setGridCoords(leftentry, topentry);
}
this.canvas.renderAll();
this.movePlace = {top:topentry, left:leftentry};
}
// TODO: would probably help to have a grid abstraction
// which you add/move stuff with (instead of just setting/getting prow and stuff)
//
/**
* Remove any transients (transient-transitively) next to point
*/
static removeadjacentTransients(point:{x:number, y:number}):number {
const cury = point.y;
const prow = placedPieces[cury];
if(prow === undefined) {
return;
}
let curx = point.x+1;
// delete stuff to the right
while(true) {
const p = prow[curx];
if(p !== undefined && p.isTransient()) {
Grid.removeAndHide({x:curx, y:cury});
} else {
break;
}
}
// delete stuff to the left
curx = point.x-1;
while(curx >= 0) {
const p = prow[curx];
if(p !== undefined && p.isTransient()) {
Grid.removeAndHide({x:curx, y:point.y});
curx--;
} else {
break;
}
}
return point.x-(curx+1);
}
static addTransientsBefore(afterpoint:{x:number, y:number}):number {
const cury = afterpoint.y;
const curx = afterpoint.x;
const prow = placedPieces[cury];
if(prow === undefined) {
return 0;
}
const piece = prow[curx];
if(piece === undefined) {
return 0;
}
if(piece.isTransient()) {
console.log("addTransientsBefore called next to a transient (right). This should not happen.");
return 0;
}
if(curx > 0) {
const leftx = curx-1;
const leftp = prow[leftx];
if(leftp !== undefined) {
if(leftp.isTransient()) {
console.log("addTransientsBefore called next to a transient (left). This should not happen.");
return 0;
}
const leftpieces = InteractivePuzzlePiece.getPathTransients(<InteractivePuzzlePiece>leftp, <InteractivePuzzlePiece>piece);
if(leftpieces.length > 0) {
Grid.addAndShow(afterpoint, leftpieces);
Grid.fixupLocations(afterpoint, leftpieces.length);
}
return leftpieces.length;
} else {
return 0;
}
} else {
return 0;
}
}
// add transients around a piece
static addTransients(curpoint:{x:number, y:number}, piece:InteractivePuzzlePiece):number {
const cury = curpoint.y;
const curx = curpoint.x;
const prow = placedPieces[cury];
if(prow === undefined) {
return 0;
}
const rightx = curx + 1;
const rightp = prow[rightx];
if(rightp !== undefined) {
if(rightp.isTransient()) {
console.log("addTransient called next to a transient (right). This should not happen.");
return 0;
}
const rightpieces = InteractivePuzzlePiece.getPathTransients(piece, <InteractivePuzzlePiece>rightp);
if(rightpieces.length > 0) {
Grid.addAndShow({y:cury, x:rightx}, rightpieces);
// call fixup on them
Grid.fixupLocations({y:cury, x:rightx}, rightpieces.length);
}
}
if(curx > 0) {
const leftx = curx-1;
const leftp = prow[leftx];
if(leftp !== undefined) {
if(leftp.isTransient()) {
console.log("addTransient called next to a transient (left). This should not happen.");
return 0;
}
const leftpieces = InteractivePuzzlePiece.getPathTransients(<InteractivePuzzlePiece>leftp, piece);
if(leftpieces.length > 0) {
Grid.addAndShow(curpoint, leftpieces);
Grid.fixupLocations(curpoint, leftpieces.length);
}
return leftpieces.length;
} else {
return 0;
}
} else {
return 0;
}
}
// I need to figure out this whole interactive v transient thing better
static getPathTransients(piece1:InteractivePuzzlePiece, piece2:InteractivePuzzlePiece):BasicPuzzlePiece[] {
const curPath = Qcert.languagesPath({
source: piece1.langid,
target:piece2.langid
}).path;
const curPathLen = curPath.length;
const transients:BasicPuzzlePiece[] = [];
if(curPath == null
|| curPathLen == 0
|| (curPathLen == 1 && curPath[0] == "error")) {
// (<any>this.backingObject).moveCursor = 'no-drop';
// add an error piece
transients.push(errorPiece.mkTransientDerivative(null,null));
} else {
for(let j = 1; j < curPathLen-1; j++) {
const previouslangid = curPath[j-1];
const langid = curPath[j];
const p = SourcePuzzlePiece.makeTransient(previouslangid,langid);
// p.setGridCoords(leftentry+(j-1), topentry);
// p.backingObject.top = p.backingObject.top + pieceheight/2;
// p.backingObject.setCoords();
transients.push(p);
//this.backingObject.canvas.add(p.backingObject);
}
}
piece2.previouslangid = transients[transients.length-1].langid;
piece2.previouslabel = sourcePieces[transients[transients.length-1].langid].label;
return transients;
}
// let nextentry = prow[leftentry];
// if(nextentry === undefined) {
// nextentry = prow[leftentry+1];
// }
// if(nextentry !== undefined) {
// // ...
// }
}
class SourcePuzzlePiece extends BasicPuzzlePiece {
static makeBasic(langid:Qcert.Language):BasicPuzzlePiece {
return sourcePieces[langid].mkBasicDerivative();
}
static makeTransient(prevlangid:Qcert.Language,langid:Qcert.Language):TransientPuzzlePiece {
var prevlabel = null;
if (prevlangid != null) {
prevlabel = sourcePieces[prevlangid].label;
}
return sourcePieces[langid].mkTransientDerivative(prevlangid,prevlabel);
}
isTransient() {
return true;
}
static make(canvas:fabric.Canvas, options):SourcePuzzlePiece {
const p = new SourcePuzzlePiece(canvas, options);
p.associate();
return p;
}
langid:Qcert.Language;
label:string;
langdescription:string;
protected constructor(canvas:fabric.Canvas, options) {
super(canvas, null, null, {options:options});
this.langid = options.langid;
this.label = options.label;
this.langdescription = options.langdescription;
};
associate() {
this.backingObject.hoverCursor = 'grab';
this.backingObject.moveCursor = 'grabbing';
this.backingObject.on('mousedown', this.mousedown);
this.backingObject.on('mouseover', this.mouseover);
this.backingObject.on('mouseout', this.mouseout);
};
disassociate() {
this.backingObject.off();
// this.backingObject.off('mousedown', this.mousedown);
// this.backingObject.off('mouseover', this.mouseover);
// this.backingObject.off('mouseout', this.mouseout);
}
// TODO: when me move something, shift things to the right back over it (to the left)
// be careful how that interacts with the shift right code!
// TODO: work on getting things to move out of the way
// track what we were over last / are over now
// and use that to track what is going on
// once that is working, change the code to move things over
// to use animations to look smooth
// mkDerivative() {
// // change to keep the same fronting object, with a new backingobject.
// // which actually, can be automatically re-created upon disassociate
// // instead, when dragging, we will create a new (BasicPuzzlePiece for now)
// // and reassociate the backend with it
// // new SourcePuzzlePiece(this.options);
// // (<any>piece).mkDerivative = function () {
// // var copyOfSelf = mkSourcePiece(options);
// // copyOfSelf.isSourcePiece = false;
// // return copyOfSelf;
// }
tooltipObj?:fabric.Object;
protected mousedown = () => {
// Update source browser to point to the IL definition -JS
// Dealing with window focus is annoying, so disabled for now - JS
var illoc = fixLabel(this.label)+".Lang."+fixLabel(this.label);
var langURL = makeLemmaURL(illoc,this.langid);
var win = window.open(langURL, 'codebrowser');
window.focus();
// Rest of logic for moving puzzle pieces
this.backingObject.set({
opacity:.5
});
// clear any tooltip
if('tooltipObj' in this) {
this.backingObject.canvas.remove(this.tooltipObj);
delete this.tooltipObj;
}
this.disassociate();
InteractivePuzzlePiece.make(this.canvas, null, null, this);
// This could be optimized a bit
// in particular, we can factor out the underlying puzzle piece,
// and just create it and give it to the existing source piece
// instead of creating a new source piece
const newSourcePiece = SourcePuzzlePiece.make(this.canvas, this.options);
this.backingObject.canvas.add(newSourcePiece.backingObject);
sourcePieces[this.langid] = newSourcePiece;
this.backingObject.canvas.renderAll();
}
mkBasicDerivative():BasicPuzzlePiece {
return BasicPuzzlePiece.make(this.canvas, null, null, this.options);
}
mkTransientDerivative(previouslangid:Qcert.Language, previouslabel:string):TransientPuzzlePiece {
return TransientPuzzlePiece.make(this.canvas, previouslangid, previouslabel, {options:this.options});
}
protected mouseover = () => {
if(! ('tooltipObj' in this)) {
const tip = makeToolTip(
this.langdescription,
this.backingObject.canvas,
{left:this.backingObject.left, top:this.backingObject.top, width:piecewidth, height:pieceheight},
new fabric.Point(10, 10),
{fill:'black', fontSize:20},
{fill:'#EEEEEE'});
this.tooltipObj = tip;
this.backingObject.canvas.add(tip);
}
};
protected mouseout = () => {
if('tooltipObj' in this) {
this.backingObject.canvas.remove(this.tooltipObj);
delete this.tooltipObj;
}
};
}
class TransientPuzzlePiece extends BasicPuzzlePiece {
langid:Qcert.Language;
label:string;
langdescription:string;
previouslangid:Qcert.Language|null;
previouslabel:string|null;
movePlace?:{left:number, top:number};
movedPieces?:number;
isTransient() {
return true;
}
static make(canvas:fabric.Canvas, previouslangid:Qcert.Language,previouslabel:string,args:{options:any} | {srcpuzzle:BasicPuzzlePiece}):TransientPuzzlePiece {
const p = new TransientPuzzlePiece(canvas, previouslangid, previouslabel, args);
p.associate();
return p;
}
public constructor(canvas:fabric.Canvas, previouslangid:Qcert.Language,previouslabel:string,args:{options:any} | {srcpuzzle:BasicPuzzlePiece}) {
super(canvas, previouslangid, previouslabel, args);
if('srcpuzzle' in args) {
const options = (<any>args).srcpuzzle;
this.langid = options.langid;
this.label = options.label;
this.langdescription = options.langdescription;
this.previouslangid = previouslangid;
this.previouslabel = previouslabel;
} else {
const options = (<any>args).options;
this.langid = options.langid;
this.label = options.label;
this.langdescription = options.langdescription;
this.previouslangid = previouslangid;
this.previouslabel = previouslabel;
}
}
protected mousedown = () => {
// Update source browser to point to the IL definition -JS
// Dealing with window focus is annoying, so disabled for now - JS
if (this.previouslangid != null) {
var illoc = makeTransitionURL(this.previouslangid,this.previouslabel,this.langid,this.label);
var win = window.open(illoc, 'codebrowser');
window.focus();
}
}
protected mouseup = () => {
}
oldoptions?:{selectable:boolean, opacity:number};
associate() {
this.oldoptions = {
selectable:this.backingObject.selectable,
opacity:this.backingObject.getOpacity()
};
this.backingObject.selectable = false;
this.backingObject.setOpacity(0.25);
this.backingObject.hoverCursor = 'pointer';
this.backingObject.moveCursor = 'pointer';
this.backingObject.on('mousedown', this.mousedown);
//this.backingObject.on('moving', this.moving);
this.backingObject.on('mouseup', this.mouseup);
}
disassociate() {
if('oldoptions' in this) {
this.backingObject.set(this.oldoptions);
delete this.oldoptions;
}
this.backingObject.off('mousedown', this.mousedown);
//this.backingObject.off('moving', this.moving);
this.backingObject.off('mouseup', this.mouseup);
}
}
// hm. it would be really nice if we could make shorter pieces...
// a makeCompositePiece which takes in a list of puzzle pieces
// (which it can, of course, display as the hovertip. Ideally it would take color from them too...)
// yay! the new getLRMask can do this!
// TODO: first get the implicit logic to work:
// when we need a new piece, create one piece (with first part of the chain?) and mark it implicit
// make sure all the logic works.
// after implicit pieces work, add support for composite pieces (which may also be implicit)
// TODO: create a makeCompositePiece that takes in a bunch of IPuzzlePieces
// and creates a single composite piece that can show the originals in a tooltip
// depending on which piece part you are actually hovering over, the tooltip will
// show that piece "bright"/selected and the others with a lower opacity
// separately, mark pieces as implicit if they are implicit
// If there is a single piece in a chain, it can be directly added (marked as implicit)
// if more, they are created, and then a composite (and implicit) chain will represent them.
// double clicking (if we can support that) on an implicit (either normal or composite)
// turns it into an explicit chain
// dropping on an implicit is allowed. It does not make the implicit move out of the way,
// although it may generate a (possibly temporary) new implicit
// the logic will be a bit hairy :-)
// Of course, that piece will be marked as "generated"
// which means that
// the sources that are passed in are owned (and manipulated directly) by the resulting composite object
class CompositePuzzlePiece extends GriddablePuzzlePiece implements Displayable, FrontingObject {
static getLRMask(tileRatio, rightTab:number, leftTab:number, width:number) {
var curvyCoords = [ 0, 0, 35, 15, 37, 5, 37, 5, 40, 0, 38, -5, 38, -5,
20, -20, 50, -20, 50, -20, 80, -20, 62, -5, 62, -5, 60, 0, 63,
5, 63, 5, 65, 15, 100, 0 ];
const tileHeight = 100;
var mask = "";
var leftx = -4;
var topy = 0;
var rightx = leftx + width;
var bottomy = topy + tileHeight;
mask += "M" + leftx + "," + topy;
mask += "L" + (leftx + width) + "," + topy;
//Right
for (var i = 0; i < curvyCoords.length / 6; i++) {
mask += "C";
mask += rightx - rightTab * curvyCoords[i * 6 + 1] * tileRatio;
mask += ",";
mask += topy + curvyCoords[i * 6 + 0] * tileRatio;
mask += ",";
mask += rightx - rightTab * curvyCoords[i * 6 + 3] * tileRatio;
mask += ",";
mask += topy + curvyCoords[i * 6 + 2] * tileRatio;
mask += ",";
mask += rightx - rightTab * curvyCoords[i * 6 + 5] * tileRatio;
mask += ",";
mask += topy + curvyCoords[i * 6 + 4] * tileRatio;
}
mask += "L" + leftx + "," + bottomy;
//Left
for (var i = 0; i < curvyCoords.length / 6; i++) {
mask += "C";
mask += leftx + leftTab * curvyCoords[i * 6 + 1] * tileRatio;
mask += ",";
mask += bottomy - curvyCoords[i * 6 + 0] * tileRatio;
mask += ",";
mask += leftx + leftTab * curvyCoords[i * 6 + 3] * tileRatio;
mask += ",";
mask += bottomy - curvyCoords[i * 6 + 2] * tileRatio;
mask += ",";
mask += leftx + leftTab * curvyCoords[i * 6 + 5] * tileRatio;
mask += ",";
mask += bottomy - curvyCoords[i * 6 + 4] * tileRatio;
}
return mask;
}
isTransient():boolean {
return false;
}
static make(canvas:fabric.Canvas, gridx:number, gridy:number, sources:BasicPuzzlePiece[]) {
const piece = new CompositePuzzlePiece(canvas, sources);
piece.associate();
piece.setGridCoords(gridx, gridy);
return piece;
}
show() {
this.canvas.add(this.backingObject);
}
hide() {
this.canvas.remove(this.backingObject);
}
protected constructor(canvas:fabric.Canvas, sources:BasicPuzzlePiece[]) {
super();
this.puzzleOffset = new fabric.Point(GriddablePuzzlePiece.calcPuzzleEdgeOffset(1), 0);
this.canvas = canvas;
this.sources = sources;
const sourceLen = sources.length;
const pwidth = piecewidth / sourceLen;
let parts:fabric.Object[] = [];
let fulls:fabric.Object[] = [];
for(let i=0; i < sourceLen; i++) {
const p:BasicPuzzlePiece = sources[i];
const ofull:fabric.Object = p.backingObject;
const shortPiece = new fabric.Path(CompositePuzzlePiece.getLRMask(1, 1, -1, pwidth), {
fill:p.backingObject.fill,
opacity: 0.5,
left:i*pwidth,
top:0,
});
shortPiece.set({
fill : '#6699ff',
hasControls : false,
selectable : false,
evented : false,
});
ofull.setOpacity(p.backingObject.opacity/2);
p.setGridCoords(i, 0);
(<any>shortPiece).fullPiece = p;
parts.push(shortPiece);
fulls.push(ofull);
}
this.fullGroup = new fabric.Group(fulls);
setBackingObject(this, new fabric.Group(parts));
this.parts = parts;
this.lastSelectedPart = -1;
}
readonly canvas:fabric.Canvas;
readonly fullGroup:fabric.Object;
readonly parts:fabric.Object[];
readonly sources:BasicPuzzlePiece[];
tooltipObj?:fabric.Object;
lastSelectedPart:number;
updateTooltip() {
// abstract the logic from makeToolTip?
// fix where it appears!
const tipbound = this.fullGroup.getBoundingRect();
const compositebound = this.backingObject.getBoundingRect();
this.fullGroup.setLeft(compositebound.left + (compositebound.width - tipbound.width) / 2);
this.fullGroup.setTop(compositebound.top + compositebound.height + 10);
const tip = this.fullGroup;
if(! ('tooltipObj' in this)) {
this.tooltipObj = tip;
this.canvas.add(tip);
}
};
findSubTarget(e:Event, lastIndex:number):number {
const mousePos = this.canvas.getPointer(e);
const mousePoint = new fabric.Point(mousePos.x, mousePos.y);
if(lastIndex >= 0) {
const part:any = this.parts[lastIndex];
if(part.containsInGroupPoint(mousePoint)) {
return lastIndex;
}
}
for(let i=0; i < this.parts.length; i++) {
if(i == lastIndex) {
continue;
}
const part:any = this.parts[i];
if(part.containsInGroupPoint(mousePoint)) {
return i;
}
}
return -1;
}
updateTooltipFocus(e:Event) {
const newSelectedPart = this.findSubTarget(e, this.lastSelectedPart);
if(this.lastSelectedPart == newSelectedPart) {
return;
}
if(this.lastSelectedPart >= 0) {
const lastpartpiece:any = this.parts[this.lastSelectedPart];
//lastpart.makeUnselected();
}
if(newSelectedPart >= 0) {
const newpart:any = this.sources[newSelectedPart];
//newpart.makeSelected();
}
this.lastSelectedPart = newSelectedPart;
this.canvas.renderAll();
}
deleteTooltip() {
if('tooltipObj' in this) {
this.canvas.remove(this.tooltipObj);
delete this.tooltipObj;
}
}
mousemovehandler = (e:fabric.IEvent) => {
if(e.target == this.backingObject) {
if(! ('tooltipObj' in this)) {
this.updateTooltip();
}
this.updateTooltipFocus(e.e);
}
}
mouseover = () => {
this.canvas.on('mouse:move', this.mousemovehandler);
}
mouseout = () => {
this.canvas.off('mouse:move', this.mousemovehandler);
this.deleteTooltip();
}
moving = () => {
this.updateTooltip();
}
associate() {
this.backingObject.on('mouseover', this.mouseover);
this.backingObject.on('mouseout', this.mouseout);
this.backingObject.on('moving', this.moving);
}
deassociate() {
this.backingObject.off('mouseover', this.mouseover);
this.backingObject.off('mouseout', this.mouseout);
this.backingObject.off('moving', this.moving);
}
}
function getLangPiece(langid:string):BasicPuzzlePiece {
return SourcePuzzlePiece.makeBasic(langid);
}
const defaultTabTextOpts:fabric.ITextOptions = {
fontFamily: 'sans-serif',
};
const defaultTabRectOpts:fabric.IRectOptions = {
cornerSize:2,
strokeLineCap:'round'
}
abstract class CanvasTab {
constructor(canvas:fabric.Canvas) {
this.canvas = canvas;
}
abstract getLabel():string;
getRectOptions():fabric.IRectOptions {
return defaultTabRectOpts;
}
getTextOptions():fabric.ITextOptions {
return defaultTabTextOpts;
}
abstract show():void;
hide() {
this.canvas.clear();
}
canvas:fabric.Canvas;
canvasObj?:fabric.Object;
}
abstract class CanvasDynamicTab extends CanvasTab {
constructor(canvas:fabric.Canvas) {
super(canvas);
}
/**
* returns true if the name change is successfull
*/
abstract setLabel(newlabel:string):boolean;
}
type TabManagerOptions = {label:string,
rectOptions?:fabric.IRectOptions,
textOptions?:fabric.IITextOptions,
tabOrigin?:{left?:number, top?:number},
};
class TabManager extends CanvasTab {
static makeTab(tab:CanvasTab, top:number, left:number):fabric.Object {
const ropts = fabric.util.object.clone(defaultTabRectOpts);
fabric.util.object.extend(ropts, tab.getRectOptions() || {});
ropts.left = left;
ropts.top = top;
ropts.editable = false;
ropts.height = ropts.height || 30;
ropts.width = ropts.width || 150;
const box = new fabric.Rect(ropts);
const topts = fabric.util.object.clone(defaultTabTextOpts)
fabric.util.object.extend(topts, tab.getTextOptions() || {});
topts.left = 0;
topts.top = 0;
topts.editable = false;
const text = new fabric.IText(tab.getLabel(), topts);
// calculate where it should appear.
// if needed, shrink the font so that the text
// is not too large
let boundingBox = text.getBoundingRect();
const maxwidth = ropts.width - 4;
while(boundingBox.width > maxwidth) {
text.setFontSize(text.getFontSize()-2);
text.setCoords();
boundingBox = text.getBoundingRect();
}
text.originX = 'left';
text.left = ropts.left + (ropts.width - boundingBox.width) / 2;
text.originY = 'top';
text.top = ropts.top;
text.height = ropts.height;
text.width = ropts.width;
text.setTextAlign('center');
text.setCoords();
const group = new fabric.Group([box, text]);
group.hasControls = false;
group.hasBorders = false;
group.lockMovementX = true;
group.lockMovementY = true;
tab.canvasObj = group;
group.setOpacity(0.3);
return group;
}
static make(canvas:fabric.Canvas,
options:TabManagerOptions,
tabs:CanvasTab[], startTab:number=-1):TabManager {
console.log("Making tab manager with label " + options.label + " and initial tab " + startTab + " and " + tabs.length + " tabs");
const tm = new TabManager(canvas, options, tabs);
tm.setInitTab(tabs, startTab);
return tm;
}
protected setInitTab(tabs:CanvasTab[], startTab:number) {
if(startTab >= 0 && startTab < tabs.length) {
const t = tabs[startTab];
if(t !== undefined && t !== null) {
this.currentTab = t;
if('canvasObj' in t) {
const tabobj = t.canvasObj;
tabobj.setOpacity(1);
}
}
}
}
protected constructor(canvas:fabric.Canvas,
options:TabManagerOptions,
tabs:CanvasTab[]) {
super(canvas);
this.label = options.label;
this.rectOpts = options.rectOptions || defaultTabRectOpts;
this.textOpts = options.textOptions || defaultTabTextOpts;
this.tabObjects = [];
const defaultTabOrigin = {left:10, top:5};
const tabOrigin = options.tabOrigin || defaultTabOrigin;
const tabTop = tabOrigin.top || defaultTabOrigin.top;
let tabLeft = tabOrigin.left || defaultTabOrigin.left;
for(let i=0; i < tabs.length; i++) {
const itab = tabs[i];
const tabgroup = TabManager.makeTab(itab, tabTop, tabLeft);
tabLeft += tabgroup.getBoundingRect().width;
tabgroup.hoverCursor = 'pointer';
tabgroup.on('selected', () => {
this.switchTab(itab);
});
this.tabObjects.push(tabgroup);
}
}
replaceTab(newTab:CanvasTab, position:number) {
const oldGroup = this.tabObjects[position];
const rect = oldGroup.getBoundingRect();
console.log("Old tab:");
console.log(this.currentTab);
const newGroup = TabManager.makeTab(newTab, rect.top, rect.left);
newGroup.hoverCursor = 'pointer';
newGroup.on('selected', () => {
this.switchTab(newTab);
});
this.tabObjects.forEach((obj) => this.canvas.remove(obj));
this.tabObjects[position] = newGroup;
this.tabObjects.forEach((obj) => this.canvas.add(obj));
if (oldGroup === this.currentTab.canvasObj) {
this.switchTab(newTab);
}
console.log("New tab:");
console.log(newTab);
this.canvas.renderAll();
}
readonly label:string;
readonly rectOpts:fabric.IRectOptions;
readonly textOpts:fabric.IITextOptions;
tabObjects:fabric.Object[];
getLabel():string {
return this.label;
}
getRectOptions():fabric.IRectOptions {
return this.rectOpts;
}
getTextOptions():fabric.ITextOptions {
return this.textOpts;
}
show():void {
if(this.currentTab != null) {
this.currentTab.show();
}
this.tabObjects.forEach((obj) => this.canvas.add(obj));
}
hide() {
if(this.currentTab != null) {
this.currentTab.hide();
}
this.tabObjects.forEach((obj) => this.canvas.remove(obj));
}
currentTab:CanvasTab = null;
switchTab(tab:CanvasTab) {
if(this.currentTab != null) {
if('canvasObj' in this.currentTab) {
const tabobj = this.currentTab.canvasObj;
tabobj.setOpacity(0.3);
}
this.currentTab.hide();
}
this.currentTab = tab;
tab.show();
if('canvasObj' in tab) {
const tabobj = tab.canvasObj;
tabobj.setOpacity(1);
}
}
}
class BuilderTab extends CanvasTab {
static make(canvas:fabric.Canvas) {
return new BuilderTab(canvas);
}
startPiece:BasicPuzzlePiece;
totalCanvasHeight:number;
maxCols:number;
constructor(canvas:fabric.Canvas) {
super(canvas);
separatorLine.set('visible', true);
const startPiece = BasicPuzzlePiece.make(canvas, null, null, {
fill : '#bfe49a',
label : 'start',
sides : {right:-1},
hasControls : false,
selectable : false,
evented : false
});
startPiece.setGridCoords(0, pipelineRow);
startPiece.backingObject.set({
hasControls : false,
selectable: false
});
startPiece.backingObject.hoverCursor = 'auto';
this.startPiece = startPiece;
const runText = new fabric.Text('R\nu\nn', {
left:2,
fontSize:25,
top:pipelineRow * pieceheight + gridOffset.y + 1,
textAlign:'center',
width:20,
fill:'red',
height:pieceheight
});
const runRect = new fabric.Rect({
left:0,
top:pipelineRow * pieceheight + gridOffset.y,
width:20,
height:pieceheight-2,
stroke:'red',
strokeWidth:2
});
const runGroup:any = new fabric.Group([runRect, runText]);
runGroup.set({
hasControls:false,
selectable:false
});
runGroup.on('mouseover', function() {
if(! ('tooltipObj' in runGroup)) {
// TODO: add path information here (at least for now)
const tip = makeToolTip(
"Run the compiler!",
canvas,
{left:runGroup.left, top:runGroup.top, width:20, height:pieceheight},
new fabric.Point(10, 10),
{fill:'black', fontSize:40},
{fill:'#EEEEEE'});
runGroup.tooltipObj = tip;
runGroup.canvas.add(tip);
}
});
runGroup.on('mouseout', function() {
if('tooltipObj' in runGroup) {
canvas.remove(runGroup.tooltipObj);
delete runGroup.tooltipObj;
}
});
const srcLangDescripts = getSrcLangDescripts(Qcert.languages());
let maxCols:number = 0;
// create the list of languages that can be dragged onto the canvas
let srcrow=0;
for(srcrow=0; srcrow < srcLangDescripts.length; srcrow++) {
let rowelem = srcLangDescripts[srcrow];
if(rowelem == null) {
continue;
}
let srccol=0;
for(srccol=0; srccol < rowelem.length; srccol++) {
let colelem = rowelem[srccol];
if(colelem == null) {
continue;
}
colelem.row = srcrow;
colelem.col = srccol;
let piece = SourcePuzzlePiece.make(canvas, colelem);
sourcePieces[colelem.langid] = piece;
}
maxCols = Math.max(srccol, maxCols);
}
const errorOptions = {
langid:'error',
label:'Error',
langdescription:'This represents an error, probably an unsupported path',
fill:'#ff3300', sides:{}
};
errorPiece = SourcePuzzlePiece.make(canvas, errorOptions);
const canvasHeightChooser = srcrow;
this.maxCols = maxCols;
this.totalCanvasHeight = getSourceTop(srcrow)-15;
//const canvasElement = document.getElementById('main-canvas');
}
getLabel():string {
return "Path Builder ";
}
getRectOptions() {
return {fill:'#FEBF01'};
}
show():void {
// TODO: at some point enable this
// but upon creation remove any inappropriate (source) elements
// and set up the mouse up/down/hover code
// taking care that the algorithm may now need to move things multiple spaces
// canvas.on('selection:created', function (event) {
// canvas.getActiveGroup().set({hasControls : false});
// });
// canvas.on('object:moving', function (event) {
// const piece = event.target;
// piece.set({
// left: Math.round(piece.left / piecewidth) * piecewidth,
// top: Math.round(piece.top / pieceheight) * pieceheight
// });
// });
// disable group selection
//canvas.selection = false;
// create the start piece
// note that the start piece is meant to have a "real" piece put on top of it by the user
const canvas = this.canvas;
canvas.selection = false;
canvas.hoverCursor = 'pointer';
this.startPiece.show();
//canvas.add(runGroup);
canvas.add(separatorLine);
// add the source pieces
for(let piece in sourcePieces) {
sourcePieces[piece].show();
}
// add the grid pieces
const placedRows = placedPieces.length;
for(let row=0;row < placedRows; row++) {
const prow = placedPieces[row];
if(prow !== undefined) {
const placedCols = prow.length;
for(let col=0;col < placedCols; col++) {
const piece = prow[col];
if (piece !== undefined) {
piece.show();
}
}
}
}
// make sure the canvas is wide enough
ensureCanvasSourcePieceWidth(canvas, this.maxCols);
// TODO: also make sure that it is wide enough for the pieces in the grid
canvas.setHeight(this.totalCanvasHeight);
// TODO experimental
// const g = CompositePuzzlePiece.make(canvas, 1, 1,
// [getLangPiece("nraenv"),
// getLangPiece("nra"),
// getLangPiece("camp")]);
// g.show();
// TODO end:experimental
canvas.renderAll();
}
}
class CompileTab extends CanvasTab {
titleTextElement:Node;
inputTabElement:HTMLElement;
queryInput:HTMLElement;
defaultTitleTextElement:Node;
queryChooser:HTMLInputElement;
schemaChooser:HTMLInputElement;
static make(canvas:fabric.Canvas) {
return new CompileTab(canvas);
}
constructor(canvas:fabric.Canvas) {
super(canvas);
this.inputTabElement = document.getElementById("compile-tab");
this.titleTextElement = document.getElementById("compile-tab-lang-title");
this.defaultTitleTextElement = <HTMLElement>this.titleTextElement.cloneNode(true);
this.queryInput = document.getElementById("compile-tab-query-input");
this.queryChooser = <HTMLInputElement>document.getElementById("compile-tab-query-src-file");
this.schemaChooser = <HTMLInputElement>document.getElementById("compile-tab-query-schema-file");
}
getLabel() {
return "Compilation ";
}
getRectOptions() {
return {fill:'#FEBF01'};
}
static getSrcLanguagePiece() {
const pipeline = getPipelinePieces();
if(pipeline === undefined || pipeline.length == 0) {
return errorPiece;
} else {
return pipeline[0];
}
}
clearTitle() {
while(this.titleTextElement.hasChildNodes()) {
this.titleTextElement.removeChild(this.titleTextElement.firstChild);
}
}
setErrorTitleText() {
const newNode = this.defaultTitleTextElement.cloneNode(true)
this.titleTextElement.parentNode.replaceChild(newNode, this.titleTextElement);
this.titleTextElement = newNode;
}
setSrcLanguage(piece:BasicPuzzlePiece) {
this.clearTitle();
const titleElem = document.createElement('label');
titleElem.appendChild(document.createTextNode("Input Language: " + piece.langid + " [" + piece.langdescription + "]"));
this.titleTextElement.appendChild(titleElem);
const langInfo = getSourceLanguageExtraInfo(piece.langid);
this.queryChooser.accept = langInfo.accept;
// the following is static for now but set here since it may become dynamic in the future
this.schemaChooser.accept = schemaAccept;
}
update() {
const srcpiece = CompileTab.getSrcLanguagePiece();
if(srcpiece.langid == 'error') {
this.setErrorTitleText();
this.queryInput.style.display="none";
} else {
this.setSrcLanguage(srcpiece);
this.queryInput.style.display="block";
}
}
show() {
this.clearTitle();
this.update();
this.inputTabElement.style.display="block";
this.canvas.getElement().style.display="none";
}
hide() {
this.canvas.getElement().style.display="block";
this.inputTabElement.style.display="none";
}
}
class ExecTab extends CanvasTab {
titleTextElement:Node;
inputTabElement:HTMLElement;
dataInput:HTMLElement;
defaultTitleTextElement:Node;
dataChooser:HTMLInputElement;
static make(canvas:fabric.Canvas) {
return new ExecTab(canvas);
}
constructor(canvas:fabric.Canvas) {
super(canvas);
this.inputTabElement = document.getElementById("execute-tab");
this.titleTextElement = document.getElementById("execute-tab-lang-title");
this.defaultTitleTextElement = <HTMLElement>this.titleTextElement.cloneNode(true);
this.dataInput = document.getElementById("execute-tab-query-input");
this.dataChooser = <HTMLInputElement>document.getElementById("execute-tab-query-io-file");
}
getLabel() {
return " Evaluation ";
}
getRectOptions() {
return {fill:'#FEBF01'};
}
static getSrcLanguagePiece() {
const pipeline = getPipelinePieces();
if(pipeline === undefined || pipeline.length == 0) {
return errorPiece;
} else {
return pipeline[0];
}
}
clearTitle() {
while(this.titleTextElement.hasChildNodes()) {
this.titleTextElement.removeChild(this.titleTextElement.firstChild);
}
}
setErrorTitleText() {
const newNode = this.defaultTitleTextElement.cloneNode(true)
this.titleTextElement.parentNode.replaceChild(newNode, this.titleTextElement);
this.titleTextElement = newNode;
}
setSrcLanguage(piece:BasicPuzzlePiece) {
this.clearTitle();
const titleElem = document.createElement('label');
titleElem.appendChild(document.createTextNode("Input Language: " + piece.langid + " [" + piece.langdescription + "]"));
this.titleTextElement.appendChild(titleElem);
// the following is static for now but set here since it may become dynamic in the future
this.dataChooser.accept = dataAccept;
}
update() {
const srcpiece = CompileTab.getSrcLanguagePiece();
if(srcpiece.langid == 'error') {
this.setErrorTitleText();
this.dataInput.style.display="none";
} else {
this.setSrcLanguage(srcpiece);
this.dataInput.style.display="block";
}
}
show() {
this.clearTitle();
this.update();
this.inputTabElement.style.display="block";
this.canvas.getElement().style.display="none";
}
hide() {
this.canvas.getElement().style.display="block";
this.inputTabElement.style.display="none";
}
}
function getPipelinePieces():BasicPuzzlePiece[] {
const prow = placedPieces[pipelineRow];
const path:BasicPuzzlePiece[] = [];
if(prow === undefined) {
return path;
}
const rowLen = prow.length;
for(let col = 0; col < rowLen; col++) {
const piece = prow[col];
if(piece === undefined) {
return path;
}
path.push(piece);
}
return path;
}
function getPipelineLangs():{id:Qcert.Language,explicit:boolean}[] {
return getPipelinePieces().map(function (piece) {
if('langid' in piece) {
return {id:(<any>piece).langid, explicit:! piece.isTransient()};
} else {
return undefined;
}
});
}
// function expandLangsPath(path:Qcert.Language[]):{id:Qcert.Language,explicit:boolean}[] {
// let expanded = [];
// const pathLen = path.length;
// if(path == null || pathLen == 0) {
// return expanded;
// }
// let prev = path[0];
// expanded.push({id:prev, explicit:true});
// for(let i = 1; i < pathLen; i++) {
// const cur = path[i];
// const curPath = Qcert.LanguagesPath({
// source: prev,
// target:cur
// }).Path;
// const curPathLen = curPath.length;
// if(curPath == null
// || curPathLen == 0
// || (curPathLen == 1 && curPath[0] == "error")) {
// expanded.push("error");
// } else {
// for(let j = 1; j < curPathLen; j++) {
// expanded.push({id:curPath[j], explicit:(j+1)==curPathLen});
// }
// }
// prev = cur;
// }
// return expanded;
// }
function getLanguageMarkedLabel(langpack:{id:Qcert.Language, explicit:boolean}):string {
const lang = langpack.id;
let str:string = "";
if(lang in sourcePieces) {
str = sourcePieces[lang].label;
} else {
str = "error";
}
if(! langpack.explicit) {
str = "[" + str + "]";
}
return str;
}
//const coqdocBaseURL = 'https://querycert.github.io/doc/';
//const coqdocBaseURL = '../..//querycert.github.io/doc/';
const coqdocBaseURL = '../html/';
function makeLemmaURL(base:string, lemma:string) {
let url = coqdocBaseURL + "Qcert." + base + ".html";
//let url = coqdocBaseURL + base + ".html";
if(lemma != undefined) {
url = url + "#" + lemma;
}
return url;
}
function fixLabel(label) {
if (label == "SQL++") return "SQLPP";
if (label == "NRAᵉ") return "NRAEnv";
if (label == "cNRAᵉ") return "cNRAEnv";
if (label == "λNRA") return "LambdaNRA";
return label;
}
function makeTransitionURL(previouslangid, previouslabel, langid, label) {
var label = fixLabel(label);
var previouslabel = fixLabel(previouslabel);
if (previouslangid == langid) {
return makeLemmaURL(label+".Optim."+label+"Optimizer","run_"+langid + "_optims");
//return makeLemmaURL(label+"Optimizer","run_"+langid + "_optims");
}
else {
return makeLemmaURL("Translation."+previouslabel+"to"+label,previouslangid + "_to_" + langid + "_top");
//return makeLemmaURL(previouslabel+"to"+label,previouslangid + "_to_" + langid + "_top");
}
}
function makeOptimElement(modulebase:string, o:Qcert.OptimStepDescription):HTMLLIElement {
const entry = document.createElement('li');
entry.classList.add("optim-list");
entry.appendChild(document.createTextNode(o.name));
const lemmaLink = document.createElement('a');
lemmaLink.href = makeLemmaURL(modulebase, o.lemma);
lemmaLink.appendChild(document.createTextNode('✿'));
lemmaLink.classList.add('lemma-link');
lemmaLink.setAttribute('target','codebrowser');
entry.appendChild(lemmaLink);
entry.title = o.description;
entry.setAttribute('data-id', o.name);
return entry;
}
function makeAvailableOptimElement(modulebase:string, o:Qcert.OptimStepDescription):HTMLLIElement {
return makeOptimElement(modulebase, o);
}
function addRemoveButton(elem:HTMLElement) {
if (elem.innerText === optPlaceholder)
return;
const removenode = document.createElement('i');
removenode.classList.add('js-remove');
removenode.appendChild(document.createTextNode('✖'));
elem.appendChild(removenode);
}
function makeSimpleOptimElement(optim:string) {
const entry = document.createElement('li');
entry.classList.add('optim-list');
entry.appendChild(document.createTextNode(optim));
entry.setAttribute('data-id', optim);
return entry;
}
function makePhaseOptimElement(
modulebase:string,
optims:Qcert.OptimStepDescription[],
optim:string):HTMLLIElement {
const fulloptim = findFirstWithField(optims, 'name', optim);
const entry = fulloptim ? makeOptimElement(modulebase, fulloptim) : makeSimpleOptimElement(optim);
addRemoveButton(entry);
return entry;
}
function getCountWithUpdate(listnode:HTMLElement) {
const count = listnode.childElementCount;
if (count == 1 && listnode.children.item(0).innerHTML == optPlaceholder)
return 0;
if (count == 0) {
listnode.appendChild(makeSimpleOptimElement(optPlaceholder));
return 0;
}
if (count > 1)
for (let i = 0; i < count; i++) {
if (listnode.children.item(i).innerHTML == optPlaceholder) {
listnode.removeChild(listnode.children.item(i));
return count - 1;
}
}
return count;
}
class OptimPhaseTab extends CanvasDynamicTab {
static make(canvas:fabric.Canvas,
parentDiv:HTMLElement,
modulebase:string,
optims:Qcert.OptimStepDescription[],
phase:Qcert.OptimPhase,
options:{color:string, top?:number}):OptimPhaseTab {
return new OptimPhaseTab(canvas, parentDiv, modulebase, optims, phase, "top", options);
}
constructor(canvas:fabric.Canvas,
div:HTMLElement,
modulebase:string,
optims:Qcert.OptimStepDescription[],
phase:Qcert.OptimPhase,
optimsType:string,
options:{color:string, top?:number}) {
super(canvas);
this.name = phase.name;
this.iter = phase.iter;
this.top = options.top || 0;
this.color = options.color || '#FEBF01';
//this.body = document.getElementsByTagName("body")[0];
this.parentDiv = div;
const newdiv = document.createElement('div');
this.optimDiv = newdiv;
this.optimsType = optimsType;
const divTitle = document.createElement('h3');
divTitle.style.cssFloat = 'center';
const titlenodetext = (num:number) => "Currently selected optimizations (" + num + ")";
let displayedCount = phase.optims[optimsType].length;
if (displayedCount == 0)
phase.optims[optimsType] = [ optPlaceholder ];
else if (displayedCount == 1 && phase.optims[optimsType][0] == optPlaceholder)
displayedCount = 0;
const titlenode = document.createTextNode(titlenodetext(displayedCount));
divTitle.appendChild(titlenode);
newdiv.appendChild(divTitle);
const divIterations = document.createElement('h4');
divIterations.appendChild(document.createTextNode("These optimizations will be batched in " + phase.iter + " iterations "));
newdiv.appendChild(divIterations);
const listnode = document.createElement('ul');
listnode.classList.add('optim-list');
for(let i =0 ; i < phase.optims[optimsType].length; i++) {
listnode.appendChild(makePhaseOptimElement(modulebase, optims, phase.optims[optimsType][i]));
}
function updateListAndTitleContent() {
const elemCount = getCountWithUpdate(listnode);
titlenode.textContent = titlenodetext(elemCount);
}
const sort = Sortable.create(listnode,
{
group: {
name: 'optims',
pull: true,
put: true
},
sort: true,
animation: 150,
//handle: '.optim-handle',
filter: '.js-remove',
onFilter: function (evt) {
var el = sort.closest(evt.item); // get dragged item
el && el.parentNode.removeChild(el);
updateListAndTitleContent();
},
onAdd: function (evt) {
const item = evt.item;
addRemoveButton(item);
},
onSort: function(evt) {
updateListAndTitleContent();
},
dataIdAttr: 'data-id'
}
);
this.sortable = sort;
newdiv.appendChild(listnode);
}
readonly sortable:Sortable;
readonly top:number;
readonly color:string;
name:string;
iter:number;
getPhase():Qcert.OptimPhase {
let optims:string[] = this.sortable.toArray();
console.log(optims);
if (optims.length == 1 && optims[0] == optPlaceholder)
optims = [];
const ret = {
name:this.name,
optims:{},
iter: this.iter
};
ret.optims[this.optimsType] = optims;
return ret;
}
getLabel():string {
return this.name;
}
setLabel(newlabel:string):boolean {
this.name = newlabel;
return true;
}
getRectOptions() {
return {fill:this.color};
}
parentDiv:HTMLElement;
optimDiv:HTMLElement;
optimsType:string;
show() {
this.parentDiv.appendChild(this.optimDiv);
//this.canvas.add(this.rect);
}
hide() {
this.parentDiv.removeChild(this.optimDiv);
//this.canvas.remove(this.rect);
}
}
function optimPhaseMake(canvas:fabric.Canvas,
div:HTMLElement,
module_base:string,
optims:Qcert.OptimStepDescription[],
options:{color:string, top?:number}) {
return function(phase:Qcert.OptimPhase) {
return OptimPhaseTab.make(canvas, div, module_base, optims, phase, options);
}
}
class OptimizationManager extends CanvasTab {
static make(canvas:fabric.Canvas,
options:{rectOptions?:fabric.IRectOptions, textOptions?:fabric.IITextOptions, tabOrigin?:{left?:number, top?:number}},
language:Qcert.Language,
modulebase:string,
optims:Qcert.OptimStepDescription[],
cfg_phases:Qcert.OptimPhase[],
startTab:number=-1):OptimizationManager {
const tm = new OptimizationManager(canvas, options, language, modulebase, optims, cfg_phases);
return tm;
}
language:Qcert.Language;
optimTabs:OptimPhaseTab[];
tabManager:TabManager;
parentDiv:HTMLElement;
topDiv:HTMLElement;
phasesDiv:HTMLElement;
rectOptions?:fabric.IRectOptions;
textOptions?:fabric.IITextOptions;
protected constructor(
canvas:fabric.Canvas,
options:{rectOptions?:fabric.IRectOptions, textOptions?:fabric.IITextOptions, tabOrigin?:{left?:number, top?:number}},
language:Qcert.Language,
module_base:string,
optims:Qcert.OptimStepDescription[],
cfg_phases:Qcert.OptimPhase[]) {
super(canvas);
this.language = language;
this.rectOptions = options.rectOptions;
this.textOptions = options.textOptions;
const defaultTabOrigin = {left:10, top:5};
const tabOrigin = options.tabOrigin || defaultTabOrigin;
const tabTop = tabOrigin.top || defaultTabOrigin.top;
const tabLeft = tabOrigin.left || defaultTabOrigin.left;
this.parentDiv = document.getElementById("container");
const newdiv = document.createElement('div');
newdiv.style.position='absolute';
newdiv.style.left='10px';
newdiv.style.top=String(tabTop+60) + 'px';
this.topDiv = newdiv;
const listnode = document.createElement('ul');
listnode.classList.add('optim-list');
for(let i =0 ; i < optims.length; i++) {
const o = optims[i];
const entry = makeAvailableOptimElement(module_base, o);
listnode.appendChild(entry);
}
const leftdiv = document.createElement('div');
leftdiv.classList.add('phase-optims');
leftdiv.style.position = 'static';
leftdiv.style.cssFloat = 'left';
const rightdiv = document.createElement('div');
rightdiv.classList.add('all-optims');
rightdiv.style.position = 'static';
rightdiv.style.cssFloat = 'right';
rightdiv.style.paddingLeft='40px';
const rightDivTitle = document.createElement('h3');
rightDivTitle.style.cssFloat = 'center';
rightDivTitle.appendChild(document.createTextNode("Available optimizations (" + optims.length + ")"));
rightdiv.appendChild(rightDivTitle);
rightdiv.appendChild(listnode);
const sort = Sortable.create(listnode,
{
group: {
name: 'optims',
pull: 'clone',
put: false
},
sort: false,
animation: 150
}
);
newdiv.appendChild(leftdiv);
newdiv.appendChild(rightdiv);
this.phasesDiv = leftdiv;
const yoffset2 = tabTop+60;
this.optimTabs = cfg_phases.map(optimPhaseMake(canvas, leftdiv, module_base, optims, {color:'#ED7D32', top:yoffset2}));
this.tabManager = TabManager.make(canvas,
{
label:language,
rectOptions:options.rectOptions,
textOptions:options.textOptions,
tabOrigin:options.tabOrigin
}, this.optimTabs, 0);
}
getOptimConfig():Qcert.OptimConfig {
return {
language:this.language,
phases:this.getConfigPhases()
}
}
getConfigPhases():Qcert.OptimPhase[] {
return this.optimTabs.map((x) => x.getPhase());
}
getLabel():string {
return this.language;
}
getRectOptions():fabric.IRectOptions {
return this.rectOptions;
}
getTextOptions():fabric.ITextOptions {
return this.textOptions;
}
show() {
this.tabManager.show();
this.parentDiv.appendChild(this.topDiv);
document.getElementById('optim-config-buttons').style.display = "block";
}
hide() {
this.tabManager.hide();
this.parentDiv.removeChild(this.topDiv);
document.getElementById('optim-config-buttons').style.display = "none";
}
}
function findFirstWithField<T, K extends keyof T>(l:T[], field:K, lang:T[K]):T {
const f = l.filter((x) => x[field] == lang);
if(f.length == 0) {
return undefined;
} else {
return f[0];
}
}
// TODO: turn this into a wrapper class so that
// globalOptimTabs, OptimizationsTabMake, and getOptimConfig
// are encapsulated
let globalOptimTabs:OptimizationManager[];
function OptimizationsTabMake(canvas:fabric.Canvas) {
return OptimizationsTabMakeFromConfig(canvas, Qcert.optimDefaults().optims);
}
function OptimizationsTabMakeFromConfig(canvas:fabric.Canvas, defaults:Qcert.OptimConfig[]) {
const yoffset = 60;
const optims = Qcert.optimList().optims;
console.log("Setting optimization config");
console.log(optims);
const opts = {rectOptions:{fill:'#548235'}, tabOrigin:{top:yoffset}};
let optimTabs:OptimizationManager[] = [];
for(let i=0; i < optims.length; i++) {
const opt = optims[i];
const cfg = findFirstWithField(defaults, 'language', opt.language.name);
const cfg_phases = cfg === undefined ? [] : cfg.phases;
optimTabs.push(OptimizationManager.make(canvas, opts, opt.language.name, opt.language.modulebase, opt.optims["top"], cfg_phases));
}
globalOptimTabs = optimTabs;
return TabManager.make(canvas, {label:"Optim Config", rectOptions:{fill:'#FEBF01'}}, optimTabs, 0);
}
function getOptimConfig():Qcert.OptimConfig[] {
if(globalOptimTabs) {
return globalOptimTabs.map((x) => x.getOptimConfig());
} else {
return [];
}
}
const tabinitlist:((canvas:fabric.Canvas)=>CanvasTab)[] = [
BuilderTab.make,
OptimizationsTabMake,
CompileTab.make,
ExecTab.make
];
function init():void {
mainCanvas = new fabric.Canvas('main-canvas');
const tabscanvas = new fabric.Canvas('tabs-canvas');
const tabs = tabinitlist.map(function (elem) {
return elem(mainCanvas)
});
const tm = TabManager.make(tabscanvas, {label:"Q*cert"}, tabs, 0);
tm.show();
tabscanvas.renderAll();
tabManager = tm;
}
function handleCSVs(files:FileList) {
console.log("CSV file handler called");
var readFiles = {};
function readFile(index) {
if (index >= files.length) {
completeCSVs(readFiles);
return;
}
var file = files[index];
var reader = new FileReader();
reader.onload = function(event) {
var typeName = (<any>file.name).endsWith(".csv") ? file.name.substring(0, file.name.length - 4) : file.name;
readFiles[typeName] = (<any>event.target).result;
readFile(index+1);
}
reader.readAsText(file);
}
readFile(0);
}
function completeCSVs(readFiles) {
let schemaText = (<HTMLTextAreaElement>document.getElementById("compile-tab-query-schema-text")).value;
if (schemaText.length == 0) {
getExecInputArea().value = "[ Error: A schema must be specified (on the compile tab) to parse CSV files ]";
let form = <HTMLFormElement>document.getElementById('csvs-form');
form.reset();
return;
}
let delimiter = (<HTMLTextAreaElement>document.getElementById("delimiter")).value;
getExecInputArea().value = JSON.stringify({delimiter: delimiter, data: readFiles});
}
function handleOptimFile(files:FileList) {
if (files.length > 0) {
const file = files[0];
const reader = new FileReader();
reader.onload = function(event) {
const contents:string = (<any>event.target).result;
const optims = JSON.parse(contents) as Qcert.OptimConfig[];
addEmptyPhases(optims);
setConfig(optims);
setConfigStatus("Configuration loaded from " + file.name, true);
}
reader.readAsText(file);
}
}
function addEmptyPhases(optims:Qcert.OptimConfig[]) {
const empty = getClearConfig();
for (let i = 0; i < empty.length; i++) {
const conf = empty[i];
const match = findFirstWithField(optims, 'language', conf.language);
if (match) {
const emptyPhases = conf.phases;
const matchPhases = match.phases;
for (let j = 0; j < emptyPhases.length; j++) {
const phase = emptyPhases[j];
const phaseMatch = findFirstWithField(matchPhases, 'name', phase.name);
if (!phaseMatch)
// Add the empty phase
matchPhases.push(phase);
}
} else
// Add the entire empty language with all its phases
optims.push(conf);
}
}
function handleFile(output:string, isSchema:boolean, files:FileList) {
if (files.length > 0) {
const file = files[0];
const reader = new FileReader();
const outputElem:HTMLTextAreaElement = <HTMLTextAreaElement>document.getElementById(output);
outputElem.value = "[ Reading ]";
if ((<any>file.name).endsWith(".sem")) {
reader.onload = function(event) {
const contents:string = btoa(String.fromCharCode.apply(null,
new Uint8Array((<any>event.target).result)))
outputElem.value = contents;
}
reader.readAsArrayBuffer(file);
} else {
reader.onload = function(event) {
const contents:string = (<any>event.target).result;
outputElem.value = contents;
}
reader.readAsText(file);
}
}
}
function handleFileDrop(output:string, event:DragEvent) {
event.stopPropagation();
event.preventDefault();
var dt = event.dataTransfer;
var files = dt.files;
handleFile(output, false, files);
}
function getSrcInput():string {
const elem = <HTMLTextAreaElement>document.getElementById('compile-tab-query-src-text');
return elem.value;
}
function getSchemaInput():string {
const elem = <HTMLTextAreaElement>document.getElementById('compile-tab-query-schema-text');
return elem.value.length > 0 ? elem.value : "{}";
}
function getIOInput():string {
return getExecInputArea().value;
}
function getExecOutputArea():HTMLTextAreaElement {
return <HTMLTextAreaElement>document.getElementById('execute-tab-query-output-text');
}
function getExecInputArea():HTMLTextAreaElement {
return <HTMLTextAreaElement>document.getElementById('execute-tab-query-io-text');
}
function getCompiledQuery():string {
const elem = <HTMLTextAreaElement>document.getElementById('compile-tab-query-output-text');
return elem.value;
} | the_stack |
* @module WebGL
*/
import { assert, dispose, disposeArray, IDisposable } from "@itwin/core-bentley";
import { ColorDef, Quantization, RenderTexture } from "@itwin/core-common";
import { Matrix4d, Range2d, Range3d, Transform, Vector2d } from "@itwin/core-geometry";
import { GraphicBranch } from "../GraphicBranch";
import { RealityMeshGraphicParams, RealityMeshPrimitive } from "../primitives/mesh/RealityMeshPrimitive";
import { TerrainMeshPrimitive } from "../primitives/mesh/TerrainMeshPrimitive";
import { RenderGraphic } from "../RenderGraphic";
import { RenderMemory } from "../RenderMemory";
import { RenderPlanarClassifier } from "../RenderPlanarClassifier";
import { RenderSystem, TerrainTexture } from "../RenderSystem";
import { BufferHandle, BufferParameters, QBufferHandle2d, QBufferHandle3d } from "./AttributeBuffers";
import { AttributeMap } from "./AttributeMap";
import { IndexedGeometry, IndexedGeometryParams } from "./CachedGeometry";
import { GL } from "./GL";
import { Matrix4 } from "./Matrix";
import { PlanarClassifier } from "./PlanarClassifier";
import { Primitive } from "./Primitive";
import { RenderOrder } from "./RenderFlags";
import { System } from "./System";
import { Target } from "./Target";
import { TechniqueId } from "./TechniqueId";
const scratchOverlapRange = Range2d.createNull();
const scratchBytes = new Uint8Array(4);
const scratchBatchBaseId = new Uint32Array(scratchBytes.buffer);
const scratchRange2d = Range2d.createNull();
class ProjectedTexture {
public classifier: PlanarClassifier;
constructor(classifier: RenderPlanarClassifier, public meshParams: RealityMeshGraphicParams, public targetRectangle: Range2d) {
this.classifier = classifier as PlanarClassifier;
}
public clone(targetRectangle: Range2d) {
return new ProjectedTexture(this.classifier, this.meshParams, targetRectangle.clone());
}
}
type TerrainOrProjectedTexture = TerrainTexture | ProjectedTexture;
class RealityTextureParam implements IDisposable {
constructor(public texture: RenderTexture | undefined, private _projectedTextureOrMatrix: ProjectedTexture | Matrix4) { }
public get isProjected() { return this._projectedTextureOrMatrix instanceof ProjectedTexture; }
public dispose(): void {
this.texture = dispose(this.texture);
}
/* There are two methods of applying a texture to a reality mesh. the first member of "params" denotes which
method is to be used. A value of zero indicates a standard texture and one represents a classified texture.
A standard (nonprojected) texture is generated by multiplying v_textCoord by the scaling and translation packed into the first row
of "matrix". A clip rectangle is packed into second row of "matrix".
A "classified" reality mesh texture is used for map layers. It does not uses v_texCoord, the texture coordinates
are instead generated by a projection of the model position onto the X-Y plane. We only have eye position, not model position
so the matrix in this case is a real transform matrix that contains a mapping from eye to model position
followed by the model to texture projection.
*/
public getProjectionMatrix(): Matrix4d | undefined {
return this._projectedTextureOrMatrix instanceof ProjectedTexture ? this._projectedTextureOrMatrix.classifier.projectionMatrix : undefined;
}
public getTerrainMatrix(): Matrix4 | undefined {
return this._projectedTextureOrMatrix instanceof Matrix4 ? this._projectedTextureOrMatrix : undefined;
}
public getParams(result: Matrix4): Matrix4 {
/** Entry 0 is 0 for */
if (this._projectedTextureOrMatrix instanceof ProjectedTexture) {
const projectedTexture = this._projectedTextureOrMatrix;
result.data[0] = 1;
result.data[1] = projectedTexture.classifier.textureImageCount;
result.data[2] = projectedTexture.classifier.sourceTransparency === undefined ? 1.0 : (1.0 - projectedTexture.classifier.sourceTransparency);
scratchBatchBaseId[0] = projectedTexture.classifier.baseBatchId;
result.data[4] = scratchBytes[0];
result.data[5] = scratchBytes[1];
result.data[6] = scratchBytes[2];
result.data[7] = scratchBytes[3];
const points = [];
const meshParams = projectedTexture.meshParams;
// Calculate range in the tiles local coordinates.
const low = meshParams.tileRectangle.worldToLocal(projectedTexture.targetRectangle.low, scratchRange2d.low)!;
const high = meshParams.tileRectangle.worldToLocal(projectedTexture.targetRectangle.high, scratchRange2d.high)!;
points.push(meshParams.projection.getGlobalPoint(low.x, low.y, 0));
points.push( meshParams.projection.getGlobalPoint(high.x, low.y, 0));
points.push(meshParams.projection.getGlobalPoint(high.x, high.y, 0));
points.push(meshParams.projection.getGlobalPoint(low.x, high.y, 0));
for (let i = 0, j = 8; i < 4; i++) {
const projectedPoint = projectedTexture.classifier.projectionMatrix.multiplyPoint3dQuietNormalize(points[i]);
result.data[j++] = projectedPoint.x;
result.data[j++] = projectedPoint.y;
}
const x0 = result.data[10] - result.data[8], y0 = result.data[11] - result.data[9];
const x1 = result.data[12] - result.data[8], y1 = result.data[13] - result.data[9];
if (x0 * y1 - x1 * y0 < 0) {
const swap = ((i: number, j: number) => {
const temp = result.data[i];
result.data[i] = result.data[j];
result.data[j] = temp;
});
for (let i = 8, j = 14; i <= 10; i += 2, j -= 2) {
swap(i, j);
swap(i + 1, j + 1);
}
}
} else {
result.data[0] = 0;
}
return result;
}
}
/** @internal */
export class RealityTextureParams implements IDisposable {
constructor(public params: RealityTextureParam[]) { }
public static create(textures: TerrainOrProjectedTexture[]) {
const maxTexturesPerMesh = System.instance.maxRealityImageryLayers;
assert(textures.length <= maxTexturesPerMesh);
const textureParams = new Array<RealityTextureParam>();
for (const texture of textures) {
if (texture instanceof TerrainTexture) {
const terrainTexture = texture;
const matrix = new Matrix4(); // Published as Mat4.
assert(terrainTexture.texture !== undefined, "Texture not defined in TerrainTextureParams constructor");
matrix.data[0] = terrainTexture.translate.x;
matrix.data[1] = terrainTexture.translate.y;
matrix.data[2] = terrainTexture.scale.x;
matrix.data[3] = terrainTexture.scale.y;
if (terrainTexture.clipRectangle) {
matrix.data[4] = terrainTexture.clipRectangle.low.x;
matrix.data[5] = terrainTexture.clipRectangle.low.y;
matrix.data[6] = terrainTexture.clipRectangle.high.x;
matrix.data[7] = terrainTexture.clipRectangle.high.y;
} else {
matrix.data[4] = matrix.data[5] = 0;
matrix.data[6] = matrix.data[7] = 1;
}
matrix.data[8] = (1.0 - terrainTexture.transparency);
matrix.data[9] = terrainTexture.featureId;
textureParams.push(new RealityTextureParam(terrainTexture.texture, matrix));
} else {
const classifier = texture.classifier;
textureParams.push(new RealityTextureParam(classifier.getOrCreateClassifierTexture(), texture));
}
}
for (let i = textures.length; i < maxTexturesPerMesh; i++) {
const matrix = new Matrix4();
matrix.data[0] = matrix.data[1] = 0.0;
matrix.data[2] = matrix.data[3] = 1.0;
matrix.data[4] = matrix.data[5] = 1;
matrix.data[6] = matrix.data[7] = -1;
matrix.data[15] = 0; // Denotes a terrain texture.
textureParams.push(new RealityTextureParam(undefined, matrix));
}
return new RealityTextureParams(textureParams);
}
public dispose(): void {
disposeArray(this.params);
}
}
/** @internal */
export class RealityMeshGeometryParams extends IndexedGeometryParams {
public readonly uvParams: QBufferHandle2d;
public readonly featureID?: number;
public readonly normals?: BufferHandle;
protected constructor(positions: QBufferHandle3d, normals: BufferHandle | undefined, uvParams: QBufferHandle2d, indices: BufferHandle, numIndices: number, featureID?: number) {
super(positions, indices, numIndices);
let attrParams = AttributeMap.findAttribute("a_uvParam", TechniqueId.RealityMesh, false);
assert(attrParams !== undefined);
this.buffers.addBuffer(uvParams, [BufferParameters.create(attrParams.location, 2, GL.DataType.UnsignedShort, false, 0, 0, false)]);
this.uvParams = uvParams;
if (undefined !== normals) {
attrParams = AttributeMap.findAttribute("a_norm", TechniqueId.RealityMesh, false);
assert(attrParams !== undefined);
if (normals.bytesUsed > 0)
this.buffers.addBuffer(normals, [BufferParameters.create(attrParams.location, 2, GL.DataType.UnsignedByte, false, 0, 0, false)]);
this.normals = normals;
}
this.featureID = featureID;
}
private static createFromBuffers(posBuf: QBufferHandle3d, uvParamBuf: QBufferHandle2d, indices: Uint16Array, normBuf: BufferHandle | undefined, featureID: number) {
const indBuf = BufferHandle.createBuffer(GL.Buffer.Target.ElementArrayBuffer, indices);
if (undefined === indBuf)
return undefined;
return new RealityMeshGeometryParams(posBuf, normBuf, uvParamBuf, indBuf, indices.length, featureID);
}
public static createFromRealityMesh(mesh: RealityMeshPrimitive) {
const posBuf = QBufferHandle3d.create(mesh.pointQParams, mesh.points);
const uvParamBuf = QBufferHandle2d.create(mesh.uvQParams, mesh.uvs);
const normalBuf = mesh.normals ? BufferHandle.createArrayBuffer(mesh.normals) : undefined;
return (undefined === posBuf || undefined === uvParamBuf) ? undefined : this.createFromBuffers(posBuf, uvParamBuf, mesh.indices, normalBuf, mesh.featureID);
}
public override get isDisposed(): boolean {
return super.isDisposed && this.uvParams.isDisposed;
}
public get bytesUsed(): number { return this.positions.bytesUsed + (undefined === this.normals ? 0 : this.normals.bytesUsed) + this.uvParams.bytesUsed + this.indices.bytesUsed; }
public override dispose() {
super.dispose();
dispose(this.uvParams);
}
}
/** @internal */
export class RealityMeshGeometry extends IndexedGeometry implements IDisposable, RenderMemory.Consumer {
public readonly hasTextures: boolean;
public override get asRealityMesh(): RealityMeshGeometry | undefined { return this; }
public override get isDisposed(): boolean { return this._realityMeshParams.isDisposed; }
public get uvQParams() { return this._realityMeshParams.uvParams.params; }
public override get hasFeatures(): boolean { return this._realityMeshParams.featureID !== undefined; }
public override get supportsThematicDisplay() { return true; }
public get overrideColorMix() { return .5; } // This could be a setting from either the mesh or the override if required.
public get transform(): Transform | undefined { return this._transform; }
private _realityMeshParams: RealityMeshGeometryParams;
public textureParams: RealityTextureParams | undefined;
private readonly _transform: Transform | undefined;
public readonly baseColor: ColorDef | undefined;
private _baseIsTransparent: boolean;
private _isTerrain: boolean;
private _disableTextureDisposal: boolean;
private constructor(props: {
realityMeshParams: RealityMeshGeometryParams;
textureParams?: RealityTextureParams;
transform?: Transform;
baseColor?: ColorDef;
baseIsTransparent: boolean;
isTerrain: boolean;
disableTextureDisposal: boolean;
}) {
super(props.realityMeshParams);
this._realityMeshParams = props.realityMeshParams;
this.textureParams = props.textureParams;
this._transform = props.transform;
this.baseColor = props.baseColor;
this._baseIsTransparent = props.baseIsTransparent;
this._isTerrain = props.isTerrain;
this._disableTextureDisposal = props.disableTextureDisposal;
this.hasTextures = undefined !== this.textureParams && this.textureParams.params.some((x) => undefined !== x.texture);
}
public override dispose() {
super.dispose();
dispose(this._realityMeshParams);
if (true !== this._disableTextureDisposal)
dispose(this.textureParams);
}
public static createFromTerrainMesh(terrainMesh: TerrainMeshPrimitive, transform: Transform | undefined, disableTextureDisposal = false) {
const params = RealityMeshGeometryParams.createFromRealityMesh(terrainMesh);
return params ? new RealityMeshGeometry({realityMeshParams: params, transform, baseIsTransparent: false, isTerrain: true, disableTextureDisposal}) : undefined;
}
public static createFromRealityMesh(realityMesh: RealityMeshPrimitive, disableTextureDisposal = false): RealityMeshGeometry | undefined {
const params = RealityMeshGeometryParams.createFromRealityMesh(realityMesh);
if (!params)
return undefined;
const texture = realityMesh.texture ? new TerrainTexture(realityMesh.texture, realityMesh.featureID, Vector2d.create(1.0, -1.0), Vector2d.create(0.0, 1.0), Range2d.createXYXY(0, 0, 1, 1), 0, 0) : undefined;
return new RealityMeshGeometry({realityMeshParams: params, textureParams: texture ? RealityTextureParams.create([texture]) : undefined, baseIsTransparent: false, isTerrain: false, disableTextureDisposal});
}
public getRange(): Range3d {
return Range3d.createXYZXYZ(this.qOrigin[0], this.qOrigin[1], this.qOrigin[2], this.qOrigin[0] + Quantization.rangeScale16 * this.qScale[0], this.qOrigin[1] + Quantization.rangeScale16 * this.qScale[1], this.qOrigin[2] + Quantization.rangeScale16 * this.qScale[2]);
}
public static createGraphic(system: RenderSystem, params: RealityMeshGraphicParams, disableTextureDisposal = false): RenderGraphic | undefined {
const meshes = [];
const textures = params.textures ?? [];
const realityMesh = params.realityMesh as RealityMeshGeometry;
const { baseColor, baseTransparent, featureTable, tileId, layerClassifiers } = params;
const texturesPerMesh = System.instance.maxRealityImageryLayers;
const layers = new Array<(TerrainTexture | ProjectedTexture)[]>();
// Collate the textures and classifiers layers into a single array.
for (const texture of textures) {
const layer = layers[texture.layerIndex];
if (layer) {
(layer as TerrainTexture[]).push(texture);
} else {
layers[texture.layerIndex] = [texture];
}
}
params.layerClassifiers?.forEach((layerClassifier, layerIndex) => layers[layerIndex] = [new ProjectedTexture(layerClassifier, params, params.tileRectangle)]);
if (layers.length < 2 && !layerClassifiers?.size && textures.length < texturesPerMesh) {
// If only there is not more than one layer then we can group all of the textures into a single draw call.
meshes.push(new RealityMeshGeometry({realityMeshParams: realityMesh._realityMeshParams, textureParams: RealityTextureParams.create(textures), transform: realityMesh._transform, baseColor, baseIsTransparent: baseTransparent, isTerrain: realityMesh._isTerrain, disableTextureDisposal}));
} else {
let primaryLayer;
while (primaryLayer === undefined)
primaryLayer = layers.shift();
if (!primaryLayer)
return undefined;
for (const primaryTexture of primaryLayer) {
const targetRectangle = primaryTexture.targetRectangle;
const overlapMinimum = 1.0E-5 * (targetRectangle.high.x - targetRectangle.low.x) * (targetRectangle.high.y - targetRectangle.low.y);
let layerTextures = [primaryTexture];
for (const secondaryLayer of layers) {
if (!secondaryLayer)
continue;
for (const secondaryTexture of secondaryLayer) {
if (secondaryTexture instanceof ProjectedTexture) {
layerTextures.push(secondaryTexture.clone(targetRectangle));
} else {
const secondaryRectangle = secondaryTexture.targetRectangle;
const overlap = targetRectangle.intersect(secondaryRectangle, scratchOverlapRange);
if (!overlap.isNull && (overlap.high.x - overlap.low.x) * (overlap.high.y - overlap.low.y) > overlapMinimum) {
const textureRange = Range2d.createXYXY(overlap.low.x, overlap.low.y, overlap.high.x, overlap.high.y);
secondaryRectangle.worldToLocal(textureRange.low, textureRange.low);
secondaryRectangle.worldToLocal(textureRange.high, textureRange.high);
if (secondaryTexture.clipRectangle)
textureRange.intersect(secondaryTexture.clipRectangle, textureRange);
if (!textureRange.isNull && textureRange) {
layerTextures.push(secondaryTexture.cloneWithClip(textureRange));
}
}
}
}
}
while (layerTextures.length > texturesPerMesh) {
meshes.push(new RealityMeshGeometry({realityMeshParams: realityMesh._realityMeshParams, textureParams: RealityTextureParams.create(layerTextures.slice(0, texturesPerMesh)), transform: realityMesh._transform, baseColor, baseIsTransparent: baseTransparent, isTerrain: realityMesh._isTerrain, disableTextureDisposal}));
layerTextures = layerTextures.slice(texturesPerMesh);
}
meshes.push(new RealityMeshGeometry({realityMeshParams: realityMesh._realityMeshParams, textureParams: RealityTextureParams.create(layerTextures), transform: realityMesh._transform, baseColor, baseIsTransparent: baseTransparent, isTerrain: realityMesh._isTerrain, disableTextureDisposal}));
}
}
if (meshes.length === 0)
return undefined;
const branch = new GraphicBranch(true);
for (const mesh of meshes) {
const primitive = Primitive.create(mesh);
branch.add(system.createBatch(primitive!, featureTable, mesh.getRange(), { tileId }));
}
return system.createBranch(branch, realityMesh._transform ? realityMesh._transform : Transform.createIdentity());
}
public collectStatistics(stats: RenderMemory.Statistics): void {
this._isTerrain ? stats.addTerrain(this._realityMeshParams.bytesUsed) : stats.addRealityMesh(this._realityMeshParams.bytesUsed);
}
public get techniqueId(): TechniqueId { return TechniqueId.RealityMesh; }
public override getPass(target: Target) {
if (target.isDrawingShadowMap)
return "none";
if (this._baseIsTransparent || (target.wantThematicDisplay && target.uniforms.thematic.wantIsoLines))
return "translucent";
return "opaque";
}
public get renderOrder(): RenderOrder { return RenderOrder.UnlitSurface; }
public override draw(): void {
this._params.buffers.bind();
System.instance.context.drawElements(GL.PrimitiveType.Triangles, this._params.numIndices, GL.DataType.UnsignedShort, 0);
this._params.buffers.unbind();
}
} | the_stack |
import { DefaultLastReferenceIdManager } from "../lastReferenceIdManager/DefaultLastReferenceIdManager.js";
import { ILastReferenceIdManager } from "../lastReferenceIdManager/ILastReferenceIdManager.js";
import { ILog } from "../logging/ILog.js";
import { ConsoleLog } from "../logging/ConsoleLog.js";
import { NullLog } from "../logging/NullLog.js";
import { UserInfo } from "../models/data/UserInfo.js";
import { HeartbeatPlugin } from "../plugins/default/HeartbeatPlugin.js";
import { EventPluginContext } from "../plugins/EventPluginContext.js";
import { IEventPlugin } from "../plugins/IEventPlugin.js";
import { DefaultEventQueue } from "../queue/DefaultEventQueue.js";
import { IEventQueue } from "../queue/IEventQueue.js";
import { ISubmissionClient } from "../submission/ISubmissionClient.js";
import { DefaultSubmissionClient } from "../submission/DefaultSubmissionClient.js";
import { guid } from "../Utils.js";
import { KnownEventDataKeys } from "../models/Event.js";
import { InMemoryStorage } from "../storage/InMemoryStorage.js";
import { IStorage } from "../storage/IStorage.js";
import { LocalStorage } from "../storage/LocalStorage.js";
import { ServerSettings } from "./SettingsManager.js";
export class Configuration {
constructor() {
this.services = {
lastReferenceIdManager: new DefaultLastReferenceIdManager(),
log: new NullLog(),
storage: new InMemoryStorage(),
queue: new DefaultEventQueue(this),
submissionClient: new DefaultSubmissionClient(this),
};
}
/**
* A default list of tags that will automatically be added to every
* report submitted to the server.
*/
public defaultTags: string[] = [];
/**
* A default list of of extended data objects that will automatically
* be added to every report submitted to the server.
*/
public defaultData: Record<string, unknown> = {};
/**
* Whether the client is currently enabled or not. If it is disabled,
* submitted errors will be discarded and no data will be sent to the server.
*
* @returns {boolean}
*/
public enabled = true;
public services: IConfigurationServices;
/**
* Maximum number of events that should be sent to the server together in a batch. (Defaults to 50)
*/
public submissionBatchSize = 50;
/**
* Contains a dictionary of custom settings that can be used to control
* the client and will be automatically updated from the server.
*/
public settings: Record<string, string> = {};
public settingsVersion = 0;
/**
* The API key that will be used when sending events to the server.
*/
public apiKey = "";
/**
* The server url that all events will be sent to.
* @type {string}
*/
private _serverUrl = "https://collector.exceptionless.io";
/**
* The config server url that all configuration will be retrieved from.
*/
public configServerUrl = "https://config.exceptionless.io";
/**
* The heartbeat server url that all heartbeats will be sent to.
*/
public heartbeatServerUrl = "https://heartbeat.exceptionless.io";
/**
* How often the client should check for updated server settings when idle. The default is every 2 minutes.
*/
private _updateSettingsWhenIdleInterval = 120000;
/**
* A list of exclusion patterns.
*/
private _dataExclusions: string[] = [];
private _includePrivateInformation = true;
private _includeUserName = true;
private _includeMachineName = true;
private _includeIpAddress = true;
private _includeCookies = true;
private _includePostData = true;
private _includeQueryString = true;
/**
* A list of user agent patterns.
*/
private _userAgentBotPatterns: string[] = [];
/**
* The list of plugins that will be used in this configuration.
*/
private _plugins: IEventPlugin[] = [];
/**
* A list of subscribers that will be fired when configuration changes.
*/
private _subscribers: Array<(config: Configuration) => void> = [];
/**
* Returns true if the apiKey is valid.
*/
public get isValid(): boolean {
return this.apiKey?.length >= 10;
}
/**
* The server url that all events will be sent to.
*/
public get serverUrl(): string {
return this._serverUrl;
}
/**
* The server url that all events will be sent to.
*/
public set serverUrl(value: string) {
if (value) {
this._serverUrl = value;
this.configServerUrl = value;
this.heartbeatServerUrl = value;
}
}
/**
* How often the client should check for updated server settings when idle. The default is every 2 minutes.
*/
public get updateSettingsWhenIdleInterval(): number {
return this._updateSettingsWhenIdleInterval;
}
/**
* How often the client should check for updated server settings when idle. The default is every 2 minutes.
*/
public set updateSettingsWhenIdleInterval(value: number) {
if (typeof value !== "number") {
return;
}
if (value <= 0) {
value = -1;
} else if (value > 0 && value < 120000) {
value = 120000;
}
this._updateSettingsWhenIdleInterval = value;
}
/**
* A list of exclusion patterns that will automatically remove any data that
* matches them from any data submitted to the server.
*
* For example, entering CreditCard will remove any extended data properties,
* form fields, cookies and query parameters from the report.
*/
public get dataExclusions(): string[] {
// TODO: Known settings keys.
const exclusions: string = this.settings["@@DataExclusions"];
return this._dataExclusions.concat(
exclusions && exclusions.split(",") || [],
);
}
/**
* Add items to the list of exclusion patterns that will automatically remove any
* data that matches them from any data submitted to the server.
*
* For example, entering CreditCard will remove any extended data properties, form
* fields, cookies and query parameters from the report.
*/
public addDataExclusions(...exclusions: string[]): void {
this._dataExclusions = [...this._dataExclusions, ...exclusions];
}
/**
* Gets a value indicating whether to include private information about the local machine.
*/
public get includePrivateInformation(): boolean {
return this._includePrivateInformation;
}
/**
* Sets a value indicating whether to include private information about the local machine
*/
public set includePrivateInformation(value: boolean) {
const val = value === true;
this._includePrivateInformation = val;
this._includeUserName = val;
this._includeMachineName = val;
this._includeIpAddress = val;
this._includeCookies = val;
this._includePostData = val;
this._includeQueryString = val;
}
/**
* Gets a value indicating whether to include User Name.
*/
public get includeUserName(): boolean {
return this._includeUserName;
}
/**
* Sets a value indicating whether to include User Name.
*/
public set includeUserName(value: boolean) {
this._includeUserName = value === true;
}
/**
* Gets a value indicating whether to include MachineName in MachineInfo.
*/
public get includeMachineName(): boolean {
return this._includeMachineName;
}
/**
* Sets a value indicating whether to include MachineName in MachineInfo.
*/
public set includeMachineName(value: boolean) {
this._includeMachineName = value === true;
}
/**
* Gets a value indicating whether to include Ip Addresses in MachineInfo and RequestInfo.
*/
public get includeIpAddress(): boolean {
return this._includeIpAddress;
}
/**
* Sets a value indicating whether to include Ip Addresses in MachineInfo and RequestInfo.
*/
public set includeIpAddress(value: boolean) {
this._includeIpAddress = value === true;
}
/**
* Gets a value indicating whether to include Cookies.
* NOTE: DataExclusions are applied to all Cookie keys when enabled.
*/
public get includeCookies(): boolean {
return this._includeCookies;
}
/**
* Sets a value indicating whether to include Cookies.
* NOTE: DataExclusions are applied to all Cookie keys when enabled.
*/
public set includeCookies(value: boolean) {
this._includeCookies = value === true;
}
/**
* Gets a value indicating whether to include Form/POST Data.
* NOTE: DataExclusions are only applied to Form data keys when enabled.
*/
public get includePostData(): boolean {
return this._includePostData;
}
/**
* Sets a value indicating whether to include Form/POST Data.
* NOTE: DataExclusions are only applied to Form data keys when enabled.
*/
public set includePostData(value: boolean) {
this._includePostData = value === true;
}
/**
* Gets a value indicating whether to include query string information.
* NOTE: DataExclusions are applied to all Query String keys when enabled.
*/
public get includeQueryString(): boolean {
return this._includeQueryString;
}
/**
* Sets a value indicating whether to include query string information.
* NOTE: DataExclusions are applied to all Query String keys when enabled.
*/
public set includeQueryString(value: boolean) {
this._includeQueryString = value === true;
}
/**
* A list of user agent patterns that will cause any event with a matching user agent to not be submitted.
*
* For example, entering *Bot* will cause any events that contains a user agent of Bot will not be submitted.
*/
public get userAgentBotPatterns(): string[] {
// TODO: Known settings keys.
const patterns: string = this.settings["@@UserAgentBotPatterns"];
return this._userAgentBotPatterns.concat(
patterns && patterns.split(",") || [],
);
}
/**
* Add items to the list of user agent patterns that will cause any event with a matching user agent to not be submitted.
*
* For example, entering *Bot* will cause any events that contains a user agent of Bot will not be submitted.
*/
public addUserAgentBotPatterns(...userAgentBotPatterns: string[]): void {
this._userAgentBotPatterns = [
...this._userAgentBotPatterns,
...userAgentBotPatterns,
];
}
/**
* The list of plugins that will be used in this configuration.
*/
public get plugins(): IEventPlugin[] {
return this._plugins.sort((p1: IEventPlugin, p2: IEventPlugin) => {
if (p1 == null && p2 == null) {
return 0;
}
if (p1?.priority == null) {
return -1;
}
if (p2?.priority == null) {
return 1;
}
if (p1.priority == p2.priority) {
return 0;
}
return p1.priority > p2.priority ? 1 : -1;
});
}
/**
* Register an plugin to be used in this configuration.
*/
public addPlugin(plugin: IEventPlugin): void;
/**
* Register an plugin to be used in this configuration.
*/
public addPlugin(name: string | undefined, priority: number, pluginAction: (context: EventPluginContext) => Promise<void>): void;
public addPlugin(pluginOrName: IEventPlugin | string | undefined, priority?: number, pluginAction?: (context: EventPluginContext) => Promise<void>): void {
const plugin: IEventPlugin = pluginAction
? <IEventPlugin>{ name: pluginOrName as string, priority, run: pluginAction }
: pluginOrName as IEventPlugin;
if (!plugin || !(plugin.startup || plugin.run)) {
this.services.log.error("Add plugin failed: startup or run method not defined");
return;
}
if (!plugin.name) {
plugin.name = guid();
}
if (!plugin.priority) {
plugin.priority = 0;
}
if (!this._plugins.find(f => f.name === plugin.name)) {
this._plugins.push(plugin);
}
}
/**
* Remove an plugin by key from this configuration.
*/
public removePlugin(pluginOrName: IEventPlugin | string): void {
const name: string = typeof pluginOrName === "string"
? pluginOrName
: pluginOrName.name || "";
if (!name) {
this.services.log.error("Remove plugin failed: Plugin name not defined");
return;
}
const plugins = this._plugins; // optimization for minifier.
for (let index = 0; index < plugins.length; index++) {
if (plugins[index].name === name) {
plugins.splice(index, 1);
break;
}
}
}
/**
* The application version for events.
*/
public get version(): string {
return <string>this.defaultData[KnownEventDataKeys.Version];
}
/**
* Set the application version for events.
*/
public set version(version: string) {
if (version) {
this.defaultData[KnownEventDataKeys.Version] = version;
} else {
delete this.defaultData[KnownEventDataKeys.Version];
}
}
/**
* Set the default user identity for all events. If the heartbeat interval is
* greater than 0 (default: 30000ms), heartbeats will be sent after the first
* event submission.
*/
public setUserIdentity(userInfo: UserInfo, heartbeatInterval?: number): void;
public setUserIdentity(identity: string, heartbeatInterval?: number): void;
public setUserIdentity(identity: string, name: string, heartbeatInterval?: number): void;
public setUserIdentity(userInfoOrIdentity: UserInfo | string, nameOrHeartbeatInterval?: string | number, heartbeatInterval: number = 30000): void {
const name: string | undefined = typeof nameOrHeartbeatInterval === "string" ? nameOrHeartbeatInterval : undefined;
const userInfo: UserInfo = typeof userInfoOrIdentity !== "string"
? userInfoOrIdentity
: <UserInfo>{ identity: userInfoOrIdentity, name };
const interval: number = typeof nameOrHeartbeatInterval === "number" ? nameOrHeartbeatInterval : heartbeatInterval;
const plugin = new HeartbeatPlugin(interval);
const shouldRemove: boolean = !userInfo || (!userInfo.identity && !userInfo.name);
if (shouldRemove) {
this.removePlugin(plugin)
delete this.defaultData[KnownEventDataKeys.UserInfo];
} else {
this.addPlugin(plugin)
this.defaultData[KnownEventDataKeys.UserInfo] = userInfo;
}
this.services.log.info(`user identity: ${shouldRemove ? "null" : <string>userInfo.identity} (heartbeat interval: ${interval}ms)`);
}
/**
* Used to identify the client that sent the events to the server.
*/
public get userAgent(): string {
return "exceptionless-js/2.0.0-dev";
}
/**
* Use localStorage for persisting things like server configuration cache and persisted queue entries (depends on usePersistedQueueStorage).
*/
public useLocalStorage(): void {
if (globalThis?.localStorage) {
this.services.storage = new LocalStorage();
}
}
/**
* Writes events to storage on enqueue and removes them when submitted. (Defaults to false)
* This setting only works in environments that supports persisted storage.
* There is also a performance penalty of extra IO/serialization.
*/
public usePersistedQueueStorage = false;
private originalSettings?: Record<string, string>;
public applyServerSettings(serverSettings: ServerSettings): void {
if (!this.originalSettings)
this.originalSettings = JSON.parse(JSON.stringify(this.settings)) as Record<string, string>;
this.services.log.trace(`Applying saved settings: v${serverSettings.version}`);
this.settings = Object.assign(this.originalSettings, serverSettings.settings);
this.settingsVersion = serverSettings.version;
this.notifySubscribers();
}
// TODO: Support a min log level.
public useDebugLogger(): void {
this.services.log = new ConsoleLog();
}
public subscribeServerSettingsChange(handler: (config: Configuration) => void): void {
handler && this._subscribers.push(handler);
}
private notifySubscribers() {
for (const handler of this._subscribers) {
try {
handler(this);
} catch (ex) {
this.services.log.error(`Error calling subscribe handler: ${ex instanceof Error ? ex.message : ex + ''}`);
}
}
}
}
interface IConfigurationServices {
lastReferenceIdManager: ILastReferenceIdManager;
log: ILog;
submissionClient: ISubmissionClient;
storage: IStorage;
queue: IEventQueue;
} | the_stack |
import { gte } from "semver";
import {
ArrayType,
assert,
Block,
ContractDefinition,
ContractKind,
DataLocation,
Expression,
FunctionCallKind,
FunctionDefinition,
FunctionStateMutability,
FunctionVisibility,
IfStatement,
IntType,
LiteralKind,
MappingType,
MemberAccess,
Mutability,
PointerType,
SourceUnit,
Statement,
StateVariableVisibility,
StructDefinition,
TypeName,
TypeNode,
UncheckedBlock,
UserDefinedType,
VariableDeclaration,
VariableDeclarationStatement
} from "solc-typed-ast";
import { single } from "../util/misc";
import { InstrumentationContext } from "./instrumentation_context";
import { transpileType } from "./transpile";
import { getTypeDesc, getTypeLocation, needsLocation, ScribbleFactory } from "./utils";
function makeStruct(
factory: ScribbleFactory,
keyT: TypeNode,
valueT: TypeNode,
lib: ContractDefinition
): StructDefinition {
const struct = factory.makeStructDefinition("S", "S", lib.id, "", []);
factory.addStructField("innerM", new MappingType(keyT, valueT), struct);
factory.addStructField("keys", new ArrayType(keyT), struct);
factory.addStructField("keyIdxM", new MappingType(keyT, new IntType(256, false)), struct);
if (valueT instanceof IntType) {
factory.addStructField("sum", new IntType(256, valueT.signed), struct);
}
return struct;
}
function mkInnerM(
factory: ScribbleFactory,
base: Expression,
struct: StructDefinition
): MemberAccess {
return factory.mkStructFieldAcc(base, struct, 0);
}
function mkVarDecl(
factory: ScribbleFactory,
name: string,
typ: TypeName,
location: DataLocation,
initialVal: Expression | undefined,
fun: FunctionDefinition
): [VariableDeclaration, VariableDeclarationStatement] {
const decl = factory.makeVariableDeclaration(
false,
false,
name,
fun.id,
false,
location,
StateVariableVisibility.Default,
Mutability.Mutable,
"<missing>",
undefined,
typ
);
const stmt = factory.makeVariableDeclarationStatement(
initialVal ? [decl.id] : [],
[decl],
initialVal
);
return [decl, stmt];
}
export function makeIncDecFun(
ctx: InstrumentationContext,
keyT: TypeNode,
valueT: TypeNode,
lib: ContractDefinition,
operator: "++" | "--",
prefix: boolean,
unchecked: boolean
): FunctionDefinition {
const factory = ctx.factory;
const struct = single(lib.vStructs);
const name =
(operator == "++" ? "inc" : "dec") + (prefix ? "_pre" : "") + (unchecked ? "_unch" : "");
const fn = factory.addEmptyFun(ctx, name, FunctionVisibility.Internal, lib);
const m = factory.addFunArg(
"m",
new UserDefinedType(struct.name, struct),
DataLocation.Storage,
fn
);
const key = factory.addFunArg(
"key",
keyT,
needsLocation(keyT) ? DataLocation.Memory : DataLocation.Default,
fn
);
const ret = factory.addFunRet(
ctx,
"RET",
valueT,
needsLocation(valueT) ? DataLocation.Storage : DataLocation.Default,
fn
);
let body: Block | UncheckedBlock;
if (unchecked) {
body = factory.addStmt(fn, factory.makeUncheckedBlock([])) as UncheckedBlock;
} else {
body = fn.vBody as Block;
}
const mkInnerM = () => factory.mkStructFieldAcc(factory.makeIdentifierFor(m), struct, 0);
const curVal = factory.makeIndexAccess("<missing>", mkInnerM(), factory.makeIdentifierFor(key));
const newVal = factory.makeBinaryOperation(
"<missing>",
operator[0],
curVal,
factory.makeLiteral("<missing>", LiteralKind.Number, "", "1")
);
const setter = single(lib.vFunctions.filter((f) => f.name == "set"));
const update = factory.makeFunctionCall(
"<missing>",
FunctionCallKind.FunctionCall,
factory.makeIdentifierFor(setter),
[factory.makeIdentifierFor(m), factory.makeIdentifierFor(key), newVal]
);
if (prefix) {
factory.addStmt(body, factory.makeReturn(fn.vReturnParameters.id, update));
} else {
factory.addStmt(
body,
factory.makeAssignment(
"<missing>",
"=",
factory.makeIdentifierFor(ret),
factory.makeIndexAccess("<missing>", mkInnerM(), factory.makeIdentifierFor(key))
)
);
factory.addStmt(body, update);
}
return fn;
}
function makeRemoveKeyFun(
ctx: InstrumentationContext,
keyT: TypeNode,
struct: StructDefinition,
lib: ContractDefinition
): FunctionDefinition {
const factory = ctx.factory;
const fn = factory.addEmptyFun(ctx, "removeKey", FunctionVisibility.Private, lib);
const m = factory.addFunArg(
"m",
new UserDefinedType(struct.name, struct),
DataLocation.Storage,
fn
);
const key = factory.addFunArg("key", keyT, getTypeLocation(keyT, DataLocation.Memory), fn);
const mkKeys = () => factory.mkStructFieldAcc(factory.makeIdentifierFor(m), struct, 1);
const mkKeysLen = () => factory.makeMemberAccess("<missing>", mkKeys(), "length", -1);
const mkKeyIdxM = () => factory.mkStructFieldAcc(factory.makeIdentifierFor(m), struct, 2);
const mkDelete = (exp: Expression) =>
factory.makeExpressionStatement(
factory.makeUnaryOperation("<missing>", true, "delete", exp)
);
const mkKeysPop = () => factory.makeMemberAccess("<missing>", mkKeys(), "pop", -1);
// uint idx = m.keyIdxM[key];
const [idx, declStmt] = mkVarDecl(
factory,
"idx",
factory.makeElementaryTypeName("<missing>", "uint256"),
DataLocation.Default,
factory.makeIndexAccess("<missing>", mkKeyIdxM(), factory.makeIdentifierFor(key)),
fn
);
factory.addStmt(fn, declStmt);
// if (idx == 0) {
// return;
// }
factory.addStmt(
fn,
factory.makeIfStatement(
factory.makeBinaryOperation(
"<missing>",
"==",
factory.makeIdentifierFor(idx),
factory.makeLiteral("<missing>", LiteralKind.Number, "", "0")
),
factory.makeReturn(fn.vReturnParameters.id)
)
);
// if (idx != m.keys.length - 1) {
const cond = factory.makeBinaryOperation(
"<missing>",
"!=",
factory.makeIdentifierFor(idx),
factory.makeBinaryOperation(
"<missing>",
"-",
mkKeysLen(),
factory.makeLiteral("<missing>", LiteralKind.Number, "", "1")
)
);
const ifBody: Statement[] = [];
// uint lastKey = m.keys[m.keys.length - 1];
const [lastKey, lastKeyDecl] = mkVarDecl(
factory,
"lastKey",
transpileType(keyT, factory),
getTypeLocation(keyT, DataLocation.Storage),
factory.makeIndexAccess(
"<missing>",
mkKeys(),
factory.makeBinaryOperation(
"<missing>",
"-",
mkKeysLen(),
factory.makeLiteral("<missing>", LiteralKind.Number, "", "1")
)
),
fn
);
ifBody.push(lastKeyDecl);
// m.keys[idx] = lastKey;
ifBody.push(
factory.makeExpressionStatement(
factory.makeAssignment(
"<missing>",
"=",
factory.makeIndexAccess("<missing>", mkKeys(), factory.makeIdentifierFor(idx)),
factory.makeIdentifierFor(lastKey)
)
)
);
// m.keyIdxM[lastKey] = idx;
ifBody.push(
factory.makeExpressionStatement(
factory.makeAssignment(
"<missing>",
"=",
factory.makeIndexAccess(
"<missing>",
mkKeyIdxM(),
factory.makeIdentifierFor(lastKey)
),
factory.makeIdentifierFor(idx)
)
)
);
// }
factory.addStmt(fn, factory.makeIfStatement(cond, factory.makeBlock(ifBody)));
// m.keys.pop();
factory.addStmt(
fn,
factory.makeFunctionCall("<missing>", FunctionCallKind.FunctionCall, mkKeysPop(), [])
);
// delete m.keyIdxM[key];
factory.addStmt(
fn,
mkDelete(factory.makeIndexAccess("<mising>", mkKeyIdxM(), factory.makeIdentifierFor(key)))
);
return fn;
}
function makeAddKeyFun(
ctx: InstrumentationContext,
keyT: TypeNode,
struct: StructDefinition,
lib: ContractDefinition
): FunctionDefinition {
const factory = ctx.factory;
const fn = factory.addEmptyFun(ctx, "addKey", FunctionVisibility.Private, lib);
const m = factory.addFunArg(
"m",
new UserDefinedType(struct.name, struct),
DataLocation.Storage,
fn
);
const key = factory.addFunArg("key", keyT, getTypeLocation(keyT, DataLocation.Memory), fn);
const mkKeys = () => factory.mkStructFieldAcc(factory.makeIdentifierFor(m), struct, 1);
const mkKeysLen = () => factory.makeMemberAccess("<missing>", mkKeys(), "length", -1);
const mkKeysPush = () => factory.makeMemberAccess("<missing>", mkKeys(), "push", -1);
const mkKeyIdxM = () => factory.mkStructFieldAcc(factory.makeIdentifierFor(m), struct, 2);
// uint idx = m.keyIdxM[key];
const [idx, idxStmt] = mkVarDecl(
factory,
"idx",
factory.makeElementaryTypeName("<missing>", "uint"),
DataLocation.Default,
factory.makeIndexAccess("<missing>", mkKeyIdxM(), factory.makeIdentifierFor(key)),
fn
);
factory.addStmt(fn, idxStmt);
// if (idx == 0) {
const ifNoIdxStmt = factory.addStmt(
fn,
factory.makeIfStatement(
factory.makeBinaryOperation(
"<missing>",
"==",
factory.makeIdentifierFor(idx),
factory.makeLiteral("<missing>", LiteralKind.Number, "", "0")
),
factory.makeBlock([])
)
) as IfStatement;
// if (m.keys.length == 0) {
const ifFirstKeyStmt = factory.addStmt(
ifNoIdxStmt.vTrueBody as Block,
factory.makeIfStatement(
factory.makeBinaryOperation(
"<missing>",
"==",
mkKeysLen(),
factory.makeLiteral("<missing>", LiteralKind.Number, "", "0")
),
factory.makeBlock([])
)
) as IfStatement;
// m.keys.push();
factory.addStmt(
ifFirstKeyStmt.vTrueBody as Block,
factory.makeFunctionCall("<missing>", FunctionCallKind.FunctionCall, mkKeysPush(), [])
);
// }
// m.keyIdxM[key] = m.keys.length;
factory.addStmt(
ifNoIdxStmt.vTrueBody as Block,
factory.makeAssignment(
"<missing>",
"=",
factory.makeIndexAccess("<missing>", mkKeyIdxM(), factory.makeIdentifierFor(key)),
mkKeysLen()
)
);
// m.keys.push(key);
factory.addStmt(
ifNoIdxStmt.vTrueBody as Block,
factory.makeFunctionCall("<missing>", FunctionCallKind.FunctionCall, mkKeysPush(), [
factory.makeIdentifierFor(key)
])
);
// }
return fn;
}
export function makeGetFun(
ctx: InstrumentationContext,
keyT: TypeNode,
valueT: TypeNode,
lib: ContractDefinition,
lhs: boolean
): FunctionDefinition {
const factory = ctx.factory;
const fn = factory.addEmptyFun(ctx, lhs ? "get_lhs" : "get", FunctionVisibility.Internal, lib);
fn.stateMutability = lhs ? FunctionStateMutability.NonPayable : FunctionStateMutability.View;
const struct = single(lib.vStructs);
const m = factory.addFunArg(
"m",
new UserDefinedType(struct.name, struct),
DataLocation.Storage,
fn
);
const key = factory.addFunArg("key", keyT, getTypeLocation(keyT, DataLocation.Memory), fn);
factory.addFunRet(ctx, "", valueT, getTypeLocation(valueT, DataLocation.Storage), fn);
// When indexes appear on the LHS of assignments we need to update the keys array as well
if (lhs) {
const addKey = single(lib.vFunctions.filter((fun) => fun.name === "addKey"));
factory.addStmt(
fn,
factory.makeFunctionCall(
"<missing>",
FunctionCallKind.FunctionCall,
factory.mkLibraryFunRef(ctx, addKey),
[factory.makeIdentifierFor(m), factory.makeIdentifierFor(key)]
)
);
}
// return m.innerM[key];
factory.addStmt(
fn,
factory.makeReturn(
fn.vReturnParameters.id,
factory.makeIndexAccess(
"<missing>",
mkInnerM(factory, factory.makeIdentifierFor(m), struct),
factory.makeIdentifierFor(key)
)
)
);
return fn;
}
export function makeSetFun(
ctx: InstrumentationContext,
keyT: TypeNode,
valueT: TypeNode,
lib: ContractDefinition,
newValT: TypeNode
): FunctionDefinition {
const factory = ctx.factory;
const specializedValueT = setterNeedsSpecialization(valueT, newValT) ? newValT : valueT;
const name = getSetterName(valueT, newValT);
const struct = single(lib.vStructs);
const fn = factory.addEmptyFun(ctx, name, FunctionVisibility.Internal, lib);
ctx.addGeneralInstrumentation(fn.vBody as Block);
const m = factory.addFunArg(
"m",
new UserDefinedType(struct.name, struct),
DataLocation.Storage,
fn
);
const key = factory.addFunArg("key", keyT, getTypeLocation(keyT, DataLocation.Memory), fn);
const val = factory.addFunArg(
"val",
specializedValueT,
getTypeLocation(specializedValueT, DataLocation.Memory),
fn
);
factory.addFunRet(ctx, "", valueT, getTypeLocation(valueT, DataLocation.Storage), fn);
const mkInnerM = () => factory.mkStructFieldAcc(factory.makeIdentifierFor(m), struct, 0);
const mkSum = () => factory.mkStructFieldAcc(factory.makeIdentifierFor(m), struct, 3);
if (valueT instanceof IntType) {
// TODO: There is risk of overflow/underflow here
const incStmts = [
// m.sum -= m.innerM[key];
factory.makeExpressionStatement(
factory.makeAssignment(
"<missing>",
"-=",
mkSum(),
factory.makeIndexAccess("<missing>", mkInnerM(), factory.makeIdentifierFor(key))
)
),
// m.sum += val;
factory.makeExpressionStatement(
factory.makeAssignment("<missing>", "+=", mkSum(), factory.makeIdentifierFor(val))
)
];
if (gte(ctx.compilerVersion, "0.8.0")) {
const block = factory.makeUncheckedBlock(incStmts);
factory.addStmt(fn, block);
} else {
incStmts.forEach((stmt) => factory.addStmt(fn, stmt));
}
}
//m.innerM[key] = val;
factory.addStmt(
fn,
factory.makeAssignment(
"<missing>",
"=",
factory.makeIndexAccess("<missing>", mkInnerM(), factory.makeIdentifierFor(key)),
factory.makeIdentifierFor(val)
)
);
// addKey(m, key);
const addKey = single(lib.vFunctions.filter((fun) => fun.name === "addKey"));
factory.addStmt(
fn,
factory.makeFunctionCall(
"<missing>",
FunctionCallKind.FunctionCall,
factory.mkLibraryFunRef(ctx, addKey),
[factory.makeIdentifierFor(m), factory.makeIdentifierFor(key)]
)
);
// return m.innerM[key];
factory.addStmt(
fn,
factory.makeReturn(
fn.vReturnParameters.id,
factory.makeIndexAccess("<missing>", mkInnerM(), factory.makeIdentifierFor(key))
)
);
return fn;
}
export function makeDeleteFun(
ctx: InstrumentationContext,
keyT: TypeNode,
valueT: TypeNode,
lib: ContractDefinition
): FunctionDefinition {
const factory = ctx.factory;
const struct = single(lib.vStructs);
const fn = factory.addEmptyFun(ctx, "deleteKey", FunctionVisibility.Internal, lib);
ctx.addGeneralInstrumentation(fn.vBody as Block);
const m = factory.addFunArg(
"m",
new UserDefinedType(struct.name, struct),
DataLocation.Storage,
fn
);
const key = factory.addFunArg("key", keyT, getTypeLocation(keyT, DataLocation.Memory), fn);
const mkInnerM = () => factory.mkStructFieldAcc(factory.makeIdentifierFor(m), struct, 0);
const mkDelete = (exp: Expression) =>
factory.makeExpressionStatement(
factory.makeUnaryOperation("<missing>", true, "delete", exp)
);
const mkSum = () => factory.mkStructFieldAcc(factory.makeIdentifierFor(m), struct, 3);
if (valueT instanceof IntType) {
// m.sum -= m.innerM[key];
factory.addStmt(
fn,
factory.makeAssignment(
"<missing>",
"-=",
mkSum(),
factory.makeIndexAccess("<missing>", mkInnerM(), factory.makeIdentifierFor(key))
)
);
}
// delete m.innerM[key];
factory.addStmt(
fn,
mkDelete(factory.makeIndexAccess("<missing>", mkInnerM(), factory.makeIdentifierFor(key)))
);
const removeKey = single(lib.vFunctions.filter((fun) => fun.name === "removeKey"));
factory.addStmt(
fn,
factory.makeFunctionCall(
"<missing>",
FunctionCallKind.FunctionCall,
factory.mkLibraryFunRef(ctx, removeKey),
[factory.makeIdentifierFor(m), factory.makeIdentifierFor(key)]
)
);
return fn;
}
export function generateMapLibrary(
ctx: InstrumentationContext,
keyT: TypeNode,
valueT: TypeNode,
container: SourceUnit
): ContractDefinition {
const factory = ctx.factory;
const libName = `${getTypeDesc(keyT)}_to_${getTypeDesc(valueT)}`;
const lib = factory.makeContractDefinition(
libName,
container.id,
ContractKind.Library,
false,
true,
[],
[]
);
container.appendChild(lib);
const struct = makeStruct(factory, keyT, valueT, lib);
lib.appendChild(struct);
makeAddKeyFun(ctx, keyT, struct, lib);
makeRemoveKeyFun(ctx, keyT, struct, lib);
// All get,set,delete, inc and dec functions are generated on demand(see InstrumentationContext for details)
return lib;
}
function setterNeedsSpecialization(formalT: TypeNode, newValT: TypeNode): newValT is PointerType {
if (!(formalT instanceof ArrayType)) {
return false;
}
assert(
newValT instanceof PointerType && newValT.to instanceof ArrayType,
"Invalid new val type {0} in setter to {1}",
newValT,
formalT
);
return formalT.size !== newValT.to.size || formalT.elementT.pp() !== newValT.to.elementT.pp();
}
export function getSetterName(formalT: TypeNode, newValT: TypeNode): string {
return `set${setterNeedsSpecialization(formalT, newValT) ? `_${getTypeDesc(newValT)}` : ""}`;
} | the_stack |
import { around } from "monkey-around";
import {
App,
debounce,
EphemeralState,
HoverParent,
ItemView,
MarkdownPreviewRenderer,
MarkdownPreviewRendererStatic,
MarkdownView,
Menu,
Platform,
Plugin,
PopoverState,
TAbstractFile,
TFile,
ViewState,
Workspace,
WorkspaceLeaf,
} from "obsidian";
import { onLinkHover } from "./onLinkHover";
import { HoverEditorParent, HoverEditor, isHoverLeaf, setMouseCoords } from "./popover";
import { DEFAULT_SETTINGS, HoverEditorSettings, SettingTab } from "./settings/settings";
import { snapActivePopover, snapDirections, restoreActivePopover, minimizeActivePopover } from "./utils/measure";
export default class HoverEditorPlugin extends Plugin {
settings: HoverEditorSettings;
settingsTab: SettingTab;
async onload() {
this.registerActivePopoverHandler();
this.registerFileRenameHandler();
this.registerViewportResizeHandler();
this.registerContextMenuHandler();
this.registerCommands();
this.patchUnresolvedGraphNodeHover();
this.patchWorkspace();
this.patchQuickSwitcher();
this.patchWorkspaceLeaf();
this.patchItemView();
this.patchMarkdownPreviewRenderer();
await this.loadSettings();
this.registerSettingsTab();
this.app.workspace.onLayoutReady(() => {
this.patchSlidingPanes();
this.patchLinkHover();
setTimeout(() => {
// workaround to ensure our plugin shows up properly within Style Settings
this.app.workspace.trigger("css-change");
}, 2000);
});
}
get activePopovers(): HoverEditor[] {
return HoverEditor.activePopovers();
}
patchWorkspaceLeaf() {
this.register(
around(WorkspaceLeaf.prototype, {
getRoot(old) {
return function () {
const top = old.call(this);
return top.getRoot === this.getRoot ? top : top.getRoot();
};
},
onResize(old) {
return function () {
this.view?.onResize();
};
},
setViewState(old) {
return async function (viewState: ViewState, eState?: unknown) {
const result = await old.call(this, viewState, eState);
// try and catch files that are opened from outside of the
// HoverEditor class so that we can update the popover title bar
try {
const he = HoverEditor.forLeaf(this);
if (he) {
if (viewState.type) he.hoverEl.setAttribute("data-active-view-type", viewState.type);
const titleEl = he.hoverEl.querySelector(".popover-title");
if (titleEl) {
titleEl.textContent = this.view?.getDisplayText();
if (this.view?.file?.path) {
titleEl.setAttribute("data-path", this.view.file.path);
} else {
titleEl.removeAttribute("data-path");
}
}
}
} catch {}
return result;
};
},
setEphemeralState(old) {
return function (state: EphemeralState) {
old.call(this, state);
if (state.focus && this.view?.getViewType() === "empty") {
// Force empty (no-file) view to have focus so dialogs don't reset active pane
this.view.contentEl.tabIndex = -1;
this.view.contentEl.focus();
}
};
},
}),
);
}
patchQuickSwitcher() {
const plugin = this;
const { QuickSwitcherModal } = this.app.internalPlugins.plugins.switcher.instance;
const uninstaller = around(QuickSwitcherModal.prototype, {
open(old) {
return function () {
const result = old.call(this);
this.setInstructions([
{
command: Platform.isMacOS ? "cmd p" : "ctrl p",
purpose: "to open in new popover",
},
]);
this.scope.register(["Mod"], "p", (event: KeyboardEvent) => {
this.close();
const item = this.chooser.values[this.chooser.selectedItem];
if (!item?.file) return;
const newLeaf = plugin.spawnPopover(undefined, () =>
this.app.workspace.setActiveLeaf(newLeaf, false, true),
);
newLeaf.openFile(item.file);
return false;
});
return result;
};
},
});
this.register(uninstaller);
}
patchItemView() {
const plugin = this;
const uninstaller = around(ItemView.prototype, {
onMoreOptionsMenu(old) {
return function (menu: Menu, ...args: unknown[]) {
const popover = this.leaf ? HoverEditor.forLeaf(this.leaf) : undefined;
if (!popover) {
menu.addItem(item => {
item
.setIcon("popup-open")
.setTitle("Open in Hover Editor")
.onClick(() => {
const newLeaf = plugin.spawnPopover();
if (this.leaf?.getViewState) newLeaf.setViewState(this.leaf.getViewState());
});
});
menu.addItem(item => {
item
.setIcon("popup-open")
.setTitle("Convert to Hover Editor")
.onClick(() => {
plugin.convertLeafToPopover(this.leaf);
});
});
} else {
menu.addItem(item => {
item
.setIcon("popup-open")
.setTitle("Dock Hover Editor to workspace")
.onClick(() => {
plugin.dockPopoverToWorkspace(this.leaf);
});
});
}
return old.call(this, menu, ...args);
};
},
});
this.register(uninstaller);
}
patchMarkdownPreviewRenderer() {
const plugin = this;
const uninstaller = around(MarkdownPreviewRenderer as MarkdownPreviewRendererStatic, {
registerDomEvents(old: Function) {
return function (
el: HTMLElement,
instance: { app: App; getFile(): TFile; hoverParent: HoverParent },
...args: unknown[]
) {
el?.on("mouseover", ".internal-embed.is-loaded", (event: MouseEvent, targetEl: HTMLElement) => {
if (targetEl && plugin.settings.hoverEmbeds) {
instance.app.workspace.trigger("hover-link", {
event: event,
source: instance.hoverParent.type === "source" ? "editor" : "preview",
hoverParent: instance.hoverParent,
targetEl: targetEl,
linktext: targetEl.getAttribute("src"),
sourcePath: instance.getFile()?.path || "",
});
}
});
return old.call(this, el, instance, ...args);
};
},
});
this.register(uninstaller);
}
patchWorkspace() {
let layoutChanging = false;
const uninstaller = around(Workspace.prototype, {
changeLayout(old) {
return async function (workspace: unknown) {
layoutChanging = true;
try {
// Don't consider hover popovers part of the workspace while it's changing
await old.call(this, workspace);
} finally {
layoutChanging = false;
}
};
},
recordHistory(old) {
return function (leaf: WorkspaceLeaf, pushHistory: boolean, ...args: unknown[]) {
const paneReliefLoaded = this.app.plugins.plugins["pane-relief"]?._loaded;
if (!paneReliefLoaded && isHoverLeaf(leaf)) return;
return old.call(this, leaf, pushHistory, ...args);
};
},
iterateAllLeaves(old) {
return function (cb) {
this.iterateRootLeaves(cb);
this.iterateLeaves(cb, this.leftSplit);
this.iterateLeaves(cb, this.rightSplit);
};
},
iterateRootLeaves(old) {
return function (callback: (leaf: WorkspaceLeaf) => unknown) {
return old.call(this, callback) || (!layoutChanging && HoverEditor.iteratePopoverLeaves(this, callback));
};
},
getDropLocation(old) {
return function getDropLocation(event: MouseEvent) {
for (const popover of HoverEditor.activePopovers()) {
const dropLoc = this.recursiveGetTarget(event, popover.rootSplit);
if (dropLoc) return { target: dropLoc, sidedock: false };
}
return old.call(this, event);
};
},
onDragLeaf(old) {
return function (event: MouseEvent, leaf: WorkspaceLeaf) {
const hoverPopover = HoverEditor.forLeaf(leaf);
hoverPopover?.togglePin(true);
return old.call(this, event, leaf);
};
},
});
this.register(uninstaller);
}
patchSlidingPanes() {
const SlidingPanesPlugin = this.app.plugins.plugins["sliding-panes-obsidian"]?.constructor;
if (SlidingPanesPlugin) {
const uninstaller = around(SlidingPanesPlugin.prototype, {
handleFileOpen(old: Function) {
return function (...args: unknown[]) {
// sliding panes needs to ignore popover open events or else it freaks out
if (isHoverLeaf(this.app.workspace.activeLeaf)) return;
return old.call(this, ...args);
};
},
handleLayoutChange(old: Function) {
return function (...args: unknown[]) {
// sliding panes needs to ignore popovers or else it activates the wrong pane
if (isHoverLeaf(this.app.workspace.activeLeaf)) return;
return old.call(this, ...args);
};
},
focusActiveLeaf(old: Function) {
return function (...args: unknown[]) {
// sliding panes tries to add popovers to the root split if we don't exclude them
if (isHoverLeaf(this.app.workspace.activeLeaf)) return;
return old.call(this, ...args);
};
},
});
this.register(uninstaller);
}
}
patchLinkHover() {
const plugin = this;
const pagePreviewPlugin = this.app.internalPlugins.plugins["page-preview"];
if (!pagePreviewPlugin.enabled) return;
const uninstaller = around(pagePreviewPlugin.instance.constructor.prototype, {
onHoverLink(old: Function) {
return function (options: { event: MouseEvent }, ...args: unknown[]) {
if (options && options.event instanceof MouseEvent) setMouseCoords(options.event);
return old.call(this, options, ...args);
};
},
onLinkHover(old: Function) {
return function (
parent: HoverEditorParent,
targetEl: HTMLElement,
linkText: string,
path: string,
state: EphemeralState,
...args: unknown[]
) {
onLinkHover(plugin, parent, targetEl, linkText, path, state, ...args);
};
},
});
this.register(uninstaller);
// This will recycle the event handlers so that they pick up the patched onLinkHover method
pagePreviewPlugin.disable();
pagePreviewPlugin.enable();
plugin.register(function () {
if (!pagePreviewPlugin.enabled) return;
pagePreviewPlugin.disable();
pagePreviewPlugin.enable();
});
}
registerContextMenuHandler() {
this.registerEvent(
this.app.workspace.on("file-menu", (menu: Menu, file: TAbstractFile, source: string, leaf?: WorkspaceLeaf) => {
const popover = leaf ? HoverEditor.forLeaf(leaf) : undefined;
if (file instanceof TFile && !popover && !leaf) {
menu.addItem(item => {
item
.setIcon("popup-open")
.setTitle("Open in Hover Editor")
.onClick(() => {
const newLeaf = this.spawnPopover();
newLeaf.openFile(file);
});
});
}
}),
);
}
registerActivePopoverHandler() {
this.registerEvent(
this.app.workspace.on("active-leaf-change", leaf => {
document.querySelector("body > .popover.hover-popover.is-active")?.removeClass("is-active");
const hoverEditor = leaf ? HoverEditor.forLeaf(leaf) : undefined;
if (hoverEditor && leaf) {
hoverEditor.hoverEl.addClass("is-active");
const titleEl = hoverEditor.hoverEl.querySelector(".popover-title");
if (!titleEl) return;
titleEl.textContent = leaf.view?.getDisplayText();
if (leaf?.view?.getViewType()) {
hoverEditor.hoverEl.setAttribute("data-active-view-type", leaf.view.getViewType());
}
if (leaf.view?.file?.path) {
titleEl.setAttribute("data-path", leaf.view.file.path);
} else {
titleEl.removeAttribute("data-path");
}
}
}),
);
}
registerFileRenameHandler() {
this.app.vault.on("rename", (file, oldPath) => {
HoverEditor.iteratePopoverLeaves(this.app.workspace, leaf => {
if (file === leaf?.view?.file && file instanceof TFile) {
const hoverEditor = HoverEditor.forLeaf(leaf);
if (hoverEditor?.hoverEl) {
const titleEl = hoverEditor.hoverEl.querySelector(".popover-title");
if (!titleEl) return;
const filePath = titleEl.getAttribute("data-path");
if (oldPath === filePath) {
titleEl.textContent = leaf.view?.getDisplayText();
titleEl.setAttribute("data-path", file.path);
}
}
}
});
});
}
debouncedPopoverReflow = debounce(
() => {
HoverEditor.activePopovers().forEach(popover => {
popover.interact?.reflow({ name: "drag", axis: "xy" });
});
},
100,
true,
);
registerViewportResizeHandler() {
// we can't use the native obsidian onResize event because
// it triggers for WAY more than just a main window resize
window.addEventListener("resize", this.debouncedPopoverReflow);
this.register(() => {
window.removeEventListener("resize", this.debouncedPopoverReflow);
});
}
patchUnresolvedGraphNodeHover() {
const leaf = new (WorkspaceLeaf as new (app: App) => WorkspaceLeaf)(this.app);
const view = this.app.internalPlugins.plugins.graph.views.localgraph(leaf);
const GraphEngine = view.engine.constructor;
leaf.detach(); // close the view
view.renderer?.worker?.terminate(); // ensure the worker is terminated
const uninstall = around(GraphEngine.prototype, {
onNodeHover(old: Function) {
return function (event: UIEvent, linkText: string, nodeType: string, ...items: unknown[]) {
if (nodeType === "unresolved") {
if ((this.onNodeUnhover(), event instanceof MouseEvent)) {
if (
this.hoverPopover &&
this.hoverPopover.state !== PopoverState.Hidden &&
this.lastHoverLink === linkText
) {
this.hoverPopover.onTarget = true;
return void this.hoverPopover.transition();
}
this.lastHoverLink = linkText;
this.app.workspace.trigger("hover-link", {
event: event,
source: "graph",
hoverParent: this,
targetEl: null,
linktext: linkText,
});
}
} else {
return old.call(this, event, linkText, nodeType, ...items);
}
};
},
});
this.register(uninstall);
leaf.detach();
}
onunload(): void {
HoverEditor.activePopovers().forEach(popover => popover.hide());
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
registerCommands() {
this.addCommand({
id: "bounce-popovers",
name: "Toggle bouncing popovers",
callback: () => {
this.activePopovers.forEach(popover => {
popover.toggleBounce();
});
},
});
this.addCommand({
id: "open-new-popover",
name: "Open new Hover Editor",
callback: () => {
// Focus the leaf after it's shown
const newLeaf = this.spawnPopover(undefined, () => this.app.workspace.setActiveLeaf(newLeaf, false, true));
},
});
this.addCommand({
id: "open-link-in-new-popover",
name: "Open link under cursor in new Hover Editor",
checkCallback: (checking: boolean) => {
const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (activeView) {
if (!checking) {
const token = activeView.editor.getClickableTokenAt(activeView.editor.getCursor());
if (token?.type === "internal-link") {
const newLeaf = this.spawnPopover(undefined, () =>
this.app.workspace.setActiveLeaf(newLeaf, false, true),
);
newLeaf.openLinkText(token.text, activeView.file.path);
}
}
return true;
}
return false;
},
});
this.addCommand({
id: "open-current-file-in-new-popover",
name: "Open current file in new Hover Editor",
checkCallback: (checking: boolean) => {
const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (activeView) {
if (!checking) {
const newLeaf = this.spawnPopover(undefined, () => this.app.workspace.setActiveLeaf(newLeaf, false, true));
newLeaf.openFile(activeView.file);
}
return true;
}
return false;
},
});
this.addCommand({
id: "convert-active-pane-to-popover",
name: "Convert active pane to Hover Editor",
checkCallback: (checking: boolean) => {
const { activeLeaf } = this.app.workspace;
if (activeLeaf) {
if (!checking) {
this.convertLeafToPopover(activeLeaf);
}
return true;
}
return false;
},
});
this.addCommand({
id: "dock-active-popover-to-workspace",
name: "Dock active Hover Editor to workspace",
checkCallback: (checking: boolean) => {
const { activeLeaf } = this.app.workspace;
if (activeLeaf && HoverEditor.forLeaf(activeLeaf)) {
if (!checking) {
this.dockPopoverToWorkspace(activeLeaf);
}
return true;
}
return false;
},
});
this.addCommand({
id: `restore-active-popover`,
name: `Restore active Hover Editor`,
checkCallback: (checking: boolean) => {
return restoreActivePopover(checking);
},
});
this.addCommand({
id: `minimize-active-popover`,
name: `Minimize active Hover Editor`,
checkCallback: (checking: boolean) => {
return minimizeActivePopover(checking);
},
});
snapDirections.forEach(direction => {
this.addCommand({
id: `snap-active-popover-to-${direction}`,
name: `Snap active Hover Editor to ${direction}`,
checkCallback: (checking: boolean) => {
return snapActivePopover(direction, checking);
},
});
});
}
convertLeafToPopover(oldLeaf: WorkspaceLeaf) {
if (!oldLeaf) return;
const newLeaf = this.spawnPopover(undefined, () => {
const { parentSplit: newParentSplit } = newLeaf;
const { parentSplit: oldParentSplit } = oldLeaf;
oldParentSplit.removeChild(oldLeaf);
newParentSplit.replaceChild(0, oldLeaf, true);
this.app.workspace.setActiveLeaf(oldLeaf, false, true);
});
return newLeaf;
}
dockPopoverToWorkspace(oldLeaf: WorkspaceLeaf) {
if (!oldLeaf) return;
oldLeaf.parentSplit.removeChild(oldLeaf);
this.app.workspace.rootSplit.insertChild(-1, oldLeaf);
return oldLeaf;
}
spawnPopover(initiatingEl?: HTMLElement, onShowCallback?: () => unknown): WorkspaceLeaf {
const parent = this.app.workspace.activeLeaf as unknown as HoverEditorParent;
if (!initiatingEl) initiatingEl = parent.containerEl;
const hoverPopover = new HoverEditor(parent, initiatingEl!, this, undefined, onShowCallback);
hoverPopover.togglePin(true);
return hoverPopover.attachLeaf();
}
registerSettingsTab() {
this.settingsTab = new SettingTab(this.app, this);
this.addSettingTab(this.settingsTab);
}
}
export function genId(size: number) {
const chars = [];
for (let n = 0; n < size; n++) chars.push(((16 * Math.random()) | 0).toString(16));
return chars.join("");
} | the_stack |
import { assert, translate as $t } from '../helpers';
import { hasForbiddenOrMissingField, hasForbiddenField } from '../../shared/validators';
import { DEFAULT_ACCOUNT_ID } from '../../shared/settings';
import DefaultSettings from '../../shared/default-settings';
import {
Account,
Access,
AccessCustomField,
Alert,
Budget,
Category,
PartialTransaction,
Rule,
} from '../models';
import { FinishUserActionFields } from './banks';
import { DeepPartial } from 'redux';
class Request {
url: string;
method: 'GET' | 'POST' | 'PUT' | 'DELETE' | null = null;
contentType: string | null = null;
bodyContent: string | null = null;
extraOptions: Record<string, string> | null = null;
constructor(url: string) {
this.url = url;
}
put() {
assert(this.method === null, 'method redefined');
this.method = 'PUT';
return this;
}
delete() {
assert(this.method === null, 'method redefined');
this.method = 'DELETE';
return this;
}
post() {
assert(this.method === null, 'method redefined');
this.method = 'POST';
return this;
}
json(record: Record<string, any>) {
assert(this.contentType === null, 'content type redefined');
assert(this.bodyContent === null, 'body redefined');
this.contentType = 'application/json';
this.bodyContent = JSON.stringify(record);
return this;
}
text(textContent: string) {
assert(this.contentType === null, 'content type redefined');
assert(this.bodyContent === null, 'body redefined');
this.contentType = 'text/plain';
this.bodyContent = textContent;
return this;
}
options(extraOptions: Record<string, string>) {
assert(this.extraOptions === null, 'options redefined');
this.extraOptions = extraOptions;
return this;
}
async run() {
const options: any = {
// Send credentials in case the API is behind an HTTP auth.
credentials: 'include',
...this.extraOptions,
};
if (this.method !== null) {
options.method = this.method;
}
if (this.contentType !== null) {
options.headers = {
'Content-Type': this.contentType,
};
}
if (this.bodyContent) {
options.body = this.bodyContent;
}
let response;
try {
response = await window.fetch(this.url, options);
} catch (e) {
let message = e.message || '?';
let shortMessage = message;
if (message && message.includes('NetworkError')) {
message = shortMessage = $t('client.general.network_error');
}
throw {
code: null,
message,
shortMessage,
};
}
const contentType = response.headers.get('Content-Type');
const isJsonResponse = contentType !== null && contentType.includes('json');
// Do the JSON parsing ourselves. Otherwise, we cannot access the raw
// text in case of a JSON decode error nor can we only decode if the
// body is not empty.
const body = await response.text();
let bodyOrJson;
if (!isJsonResponse) {
bodyOrJson = body;
} else if (!body) {
bodyOrJson = {};
} else {
try {
bodyOrJson = JSON.parse(body);
} catch (e) {
throw {
code: null,
message: e.message || '?',
shortMessage: $t('client.general.json_parse_error'),
};
}
}
// If the initial response status code wasn't in the 200 family, the
// JSON describes an error.
if (!response.ok) {
throw {
code: bodyOrJson.code,
message: bodyOrJson.message || '?',
shortMessage: bodyOrJson.shortMessage || bodyOrJson.message || '?',
};
}
return bodyOrJson;
}
}
// /api/all
export function init() {
return new Request('api/all/').options({ cache: 'no-cache' }).run();
}
export function importInstance(data: any, maybePassword?: string) {
return new Request('api/all')
.post()
.json({
data,
encrypted: !!maybePassword,
passphrase: maybePassword,
})
.run();
}
export function importOFX(data: string, _maybePassword?: string) {
return new Request('api/all/import/ofx').post().text(data).run();
}
export function exportInstance(maybePassword?: string) {
return new Request('api/all/export')
.post()
.json({
encrypted: !!maybePassword,
passphrase: maybePassword,
})
.run();
}
// /api/accesses
export function createAccess(
vendorId: string,
login: string,
password: string,
customFields: AccessCustomField[],
customLabel: string | null,
userActionFields: FinishUserActionFields | null = null
) {
const data = {
vendorId,
login,
password,
customLabel,
fields: customFields,
// TODO would be nice to separate the access' fields from the user action fields.
userActionFields,
};
return new Request('api/accesses').post().json(data).run();
}
export function updateAccess(accessId: number, update: Partial<Access>) {
const error = hasForbiddenField(update, ['enabled', 'customLabel']);
if (error) {
return Promise.reject(`Developer error when updating an access: ${error}`);
}
return new Request(`api/accesses/${accessId}`).put().json(update).run();
}
export function updateAndFetchAccess(
accessId: number,
access: {
login: string;
password: string;
customFields: AccessCustomField[];
},
userActionFields: FinishUserActionFields | null = null
) {
const error = hasForbiddenField(access, ['login', 'password', 'customFields']);
if (error) {
return Promise.reject(`Developer error when updating an access: ${error}`);
}
// Transform the customFields update to the server's format.
const { customFields, ...rest } = access;
const data = { fields: customFields, ...rest, userActionFields };
return new Request(`api/accesses/${accessId}/fetch/accounts`).put().json(data).run();
}
export function getNewAccounts(
accessId: number,
userActionFields: FinishUserActionFields | null = null
) {
let request = new Request(`api/accesses/${accessId}/fetch/accounts`).post();
if (userActionFields !== null) {
request = request.json({
userActionFields,
});
}
return request.run();
}
export function getNewOperations(
accessId: number,
userActionFields: FinishUserActionFields | null = null
) {
let request = new Request(`api/accesses/${accessId}/fetch/operations`).post();
if (userActionFields !== null) {
request = request.json({
userActionFields,
});
}
return request.run();
}
export function deleteAccess(accessId: number) {
return new Request(`api/accesses/${accessId}`).delete().run();
}
export function deleteAccessSession(accessId: number) {
return new Request(`api/accesses/${accessId}/session`).delete().run();
}
// /api/accounts
export function updateAccount(accountId: number, newFields: Partial<Account>) {
const error = hasForbiddenField(newFields, ['excludeFromBalance', 'customLabel']);
if (error) {
return Promise.reject(`Developer error when updating an account: ${error}`);
}
return new Request(`api/accounts/${accountId}`).put().json(newFields).run();
}
export function deleteAccount(accountId: number) {
return new Request(`api/accounts/${accountId}`).delete().run();
}
export async function resyncBalance(
accountId: number,
userActionFields: FinishUserActionFields | null = null
) {
let request = new Request(`api/accounts/${accountId}/resync-balance`).post();
if (userActionFields !== null) {
request = request.json({ userActionFields });
}
return request.run();
}
// /api/operations
export function createOperation(operation: PartialTransaction) {
return new Request('api/operations').post().json(operation).run();
}
export function updateOperation(id: number, newOp: PartialTransaction) {
return new Request(`api/operations/${id}`).put().json(newOp).run();
}
export function setCategoryForOperation(operationId: number, categoryId: number | null) {
return updateOperation(operationId, { categoryId });
}
export function setTypeForOperation(operationId: number, type: string) {
return updateOperation(operationId, { type });
}
export function setCustomLabel(operationId: number, customLabel: string) {
return updateOperation(operationId, { customLabel });
}
export function setOperationBudgetDate(operationId: number, budgetDate: Date | null) {
return updateOperation(operationId, { budgetDate });
}
export function deleteOperation(opId: number) {
return new Request(`api/operations/${opId}`).delete().run();
}
export function mergeOperations(toKeepId: number, toRemoveId: number) {
return new Request(`api/operations/${toKeepId}/mergeWith/${toRemoveId}`).put().run();
}
// /api/categories
export function addCategory(category: Partial<Category>) {
const error = hasForbiddenOrMissingField(category, ['label', 'color']);
if (error) {
return Promise.reject(`Developer error when adding a category: ${error}`);
}
return new Request('api/categories').post().json(category).run();
}
export function updateCategory(id: number, category: Partial<Category>) {
const error = hasForbiddenField(category, ['label', 'color']);
if (error) {
return Promise.reject(`Developer error when updating a category: ${error}`);
}
return new Request(`api/categories/${id}`).put().json(category).run();
}
export function deleteCategory(categoryId: number, replaceByCategoryId: number | null) {
return new Request(`api/categories/${categoryId}`).delete().json({ replaceByCategoryId }).run();
}
// /api/budgets
export function fetchBudgets(year: number, month: number) {
return new Request(`api/budgets/${year}/${month}`).run();
}
export function updateBudget(budget: Partial<Budget>) {
const { categoryId, year, month } = budget;
return new Request(`api/budgets/${categoryId}/${year}/${month}`).put().json(budget).run();
}
// /api/alerts
export function createAlert(newAlert: Partial<Alert>) {
return new Request('api/alerts').post().json(newAlert).run();
}
export function updateAlert(alertId: number, attributes: Partial<Alert>) {
return new Request(`api/alerts/${alertId}`).put().json(attributes).run();
}
export function deleteAlert(alertId: number) {
return new Request(`api/alerts/${alertId}`).delete().run();
}
// /api/settings
export function saveSetting(key: string, value: string | null) {
let normalizedValue;
switch (key) {
case DEFAULT_ACCOUNT_ID:
normalizedValue = value === null ? DefaultSettings.get(DEFAULT_ACCOUNT_ID) : value;
break;
default:
normalizedValue = value;
break;
}
return new Request('api/settings').post().json({ key, value: normalizedValue }).run();
}
// /api/instance
export function sendTestEmail(email: string) {
return new Request('api/instance/test-email').post().json({ email }).run();
}
export function sendTestNotification(appriseUrl: string) {
return new Request('api/instance/test-notification').post().json({ appriseUrl }).run();
}
export function updateWoob() {
return new Request('api/instance/woob/').put().run();
}
export function fetchWoobVersion() {
return new Request('api/instance/woob').run();
}
// /api/logs & /api/demo
export function fetchLogs() {
return new Request('api/logs').run();
}
export function clearLogs() {
return new Request('api/logs').delete().run();
}
export function enableDemoMode() {
return new Request('api/demo').post().run();
}
export function disableDemoMode() {
return new Request('api/demo').delete().run();
}
// /api/rules
export function loadRules(): Promise<Rule[]> {
return new Request('api/rules').run();
}
export function createRule(rule: DeepPartial<Rule>): Promise<Rule> {
return new Request('api/rules').post().json(rule).run();
}
export function updateRule(ruleId: number, newAttr: Partial<Rule>): Promise<Rule> {
return new Request(`api/rules/${ruleId}`).put().json(newAttr).run();
}
export function swapRulePositions(ruleId: number, otherRuleId: number): Promise<void> {
return new Request(`api/rules/swap/${ruleId}/${otherRuleId}`).put().run();
}
export function deleteRule(ruleId: number) {
return new Request(`api/rules/${ruleId}`).delete().run();
} | the_stack |
import { TestBed } from '@angular/core/testing';
import { PlayerTranscriptService } from
'pages/exploration-player-page/services/player-transcript.service';
import { StateCard } from 'domain/state_card/state-card.model';
import { AudioTranslationLanguageService } from
'pages/exploration-player-page/services/audio-translation-language.service';
import { Interaction } from 'domain/exploration/InteractionObjectFactory';
import { RecordedVoiceovers } from 'domain/exploration/recorded-voiceovers.model';
import { WrittenTranslations } from 'domain/exploration/WrittenTranslationsObjectFactory';
import { LoggerService } from 'services/contextual/logger.service';
describe('Player transcript service', () => {
let pts: PlayerTranscriptService;
let atls: AudioTranslationLanguageService;
let ls: LoggerService;
beforeEach(() => {
pts = TestBed.inject(PlayerTranscriptService);
atls = TestBed.inject(AudioTranslationLanguageService);
ls = TestBed.inject(LoggerService);
});
it('should reset the transcript correctly', () => {
pts.addNewCard(StateCard.createNewCard(
'First state', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls));
pts.addNewCard(StateCard.createNewCard(
'Second state', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls));
expect(pts.getNumCards()).toBe(2);
pts.init();
expect(pts.getNumCards()).toBe(0);
pts.addNewCard(StateCard.createNewCard(
'Third state', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls));
expect(pts.getCard(0).getStateName()).toBe('Third state');
});
it(
'should correctly check whether a state have been encountered before',
() => {
pts.addNewCard(StateCard.createNewCard(
'First state', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls));
pts.addNewCard(StateCard.createNewCard(
'Second state', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls));
pts.addNewCard(StateCard.createNewCard(
'First state', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls));
expect(pts.hasEncounteredStateBefore('First state')).toEqual(true);
expect(pts.hasEncounteredStateBefore('Third state')).toEqual(false);
});
it('should add a new card correctly', () => {
pts.addNewCard(StateCard.createNewCard(
'First state', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls));
let firstCard = pts.getCard(0);
expect(firstCard.getStateName()).toEqual('First state');
expect(firstCard.getContentHtml()).toEqual('Content HTML');
expect(firstCard.getInteractionHtml()).toEqual(
'<oppia-text-input-html></oppia-text-input-html>');
});
it('should add a previous card correctly', () => {
pts.addNewCard(StateCard.createNewCard(
'First state', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls));
pts.addNewCard(StateCard.createNewCard(
'Second state', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls));
pts.addPreviousCard();
expect(pts.getNumCards()).toEqual(3);
expect(pts.getCard(0).getStateName()).toEqual('First state');
expect(pts.getCard(1).getStateName()).toEqual('Second state');
expect(pts.getCard(2).getStateName()).toEqual('First state');
});
it('should throw error when there is only one card and' +
'adding previous card fails', () => {
pts.addNewCard(StateCard.createNewCard(
'First state', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls));
expect(() => pts.addPreviousCard()).toThrowError(
'Exploration player is on the first card and hence no previous ' +
'card exists.');
});
it('should set lastAnswer correctly', () => {
pts.addNewCard(StateCard.createNewCard(
'First state', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls));
let lastAnswer = pts.getLastAnswerOnDisplayedCard(0);
expect(lastAnswer).toEqual(null);
pts.addNewInput('first answer', false);
pts.addNewCard(StateCard.createNewCard(
'Second state', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls));
lastAnswer = pts.getLastAnswerOnDisplayedCard(0);
expect(lastAnswer).toEqual('first answer');
pts.addNewCard(StateCard.createNewCard(
'Third state', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls));
// Variable lastAnswer should be null as no answers were provided in the
// second state.
lastAnswer = pts.getLastAnswerOnDisplayedCard(1);
expect(lastAnswer).toEqual(null);
});
it('should record answer/feedback pairs in the correct order', () => {
pts.addNewCard(StateCard.createNewCard(
'First state', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls));
pts.addNewInput('first answer', false);
expect(() => {
pts.addNewInput('invalid answer', false);
}).toThrowError(
'Trying to add an input before the response for the previous ' +
'input has been received.');
pts.addNewResponse('feedback');
pts.addNewInput('second answer', true);
let firstCard = pts.getCard(0);
expect(firstCard.getInputResponsePairs()).toEqual([{
learnerInput: 'first answer',
oppiaResponse: 'feedback',
isHint: false
}, {
learnerInput: 'second answer',
oppiaResponse: null,
isHint: true
}]);
expect(pts.getNumSubmitsForLastCard()).toBe(1);
});
it('should retrieve the last card of the transcript correctly', () => {
pts.addNewCard(StateCard.createNewCard(
'First state', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls));
pts.addNewCard(StateCard.createNewCard(
'Second state', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls));
expect(pts.getNumCards()).toBe(2);
expect(pts.getLastCard().getStateName()).toBe('Second state');
expect(pts.isLastCard(0)).toBe(false);
expect(pts.isLastCard(1)).toBe(true);
expect(pts.isLastCard(2)).toBe(false);
expect(pts.getLastStateName()).toBe('Second state');
expect(pts.getNumSubmitsForLastCard()).toBe(0);
pts.addNewInput('first answer', false);
expect(pts.getNumSubmitsForLastCard()).toBe(1);
pts.addNewResponse('first feedback');
expect(pts.getNumSubmitsForLastCard()).toBe(1);
pts.addNewInput('second answer', false);
expect(pts.getNumSubmitsForLastCard()).toBe(2);
});
it('should update interaction html of the latest card', () => {
pts.addNewCard(StateCard.createNewCard(
'First state', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls));
let secondCard = StateCard.createNewCard(
'Second state', 'Content HTML',
'<oppia-number-input-html></oppia-number-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls);
pts.updateLatestInteractionHtml(secondCard.getInteractionHtml());
expect(pts.getLastCard().getInteractionHtml()).toEqual(
secondCard.getInteractionHtml());
});
it('should restore the old transcript', () => {
let card1 = StateCard.createNewCard(
'First State', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls);
let card2 = StateCard.createNewCard(
'Second State', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls);
let card3 = StateCard.createNewCard(
'Third State', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls);
let card4 = StateCard.createNewCard(
'Fourth State', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls);
let oldTranscript = [card3, card4];
pts.addNewCard(card1);
pts.addNewCard(card2);
expect(pts.getCard(0).getStateName()).toEqual('First State');
expect(pts.getCard(1).getStateName()).toEqual('Second State');
pts.restore(oldTranscript);
expect(pts.getCard(0).getStateName()).toEqual('Third State');
expect(pts.getCard(1).getStateName()).toEqual('Fourth State');
});
it('should restore the old transcript immutably', () => {
let card1 = StateCard.createNewCard(
'First State', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls);
let card2 = StateCard.createNewCard(
'Second State', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls);
let card3 = StateCard.createNewCard(
'Third State', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls);
let card4 = StateCard.createNewCard(
'Fourth State', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls);
let oldTranscript = [card3, card4];
pts.addNewCard(card1);
pts.addNewCard(card2);
expect(pts.getCard(0).getStateName()).toEqual('First State');
expect(pts.getCard(1).getStateName()).toEqual('Second State');
pts.restoreImmutably(oldTranscript);
expect(pts.getCard(0).getStateName()).toEqual('Third State');
expect(pts.getCard(1).getStateName()).toEqual('Fourth State');
});
it('should show error on the console when invalid index is provided', () => {
spyOn(ls, 'error');
pts.addNewCard(StateCard.createNewCard(
'First State', 'Content HTML',
'<oppia-text-input-html></oppia-text-input-html>',
{} as Interaction, {} as RecordedVoiceovers,
{} as WrittenTranslations, '', atls));
pts.getCard(1);
expect(ls.error).toHaveBeenCalledWith(
'Requested card with index 1, but transcript only has length 1 cards.');
});
}); | the_stack |
import { removeDeferred } from './src/deferred'
import { isTimeToYield, yieldOrContinue, yieldControl } from './index'
import { startTrackingPhases, stopTrackingPhases } from './src/phaseTracking'
describe('main-thread-scheculing', () => {
let requestIdleCallbackMock = createRequestIdleCallbackMock()
let requestAnimationFrameMock = createRequestAnimationFrameMock()
function callAnimationAndIdleFrames(timeRemaining: number, didTimeout: boolean): void {
requestAnimationFrameMock.callRequestAnimationFrame()
requestIdleCallbackMock.callRequestIdleCallback(timeRemaining, didTimeout)
}
beforeEach(async () => {
await wait()
callAnimationAndIdleFrames(100, false)
await wait()
requestIdleCallbackMock.mockRestore()
requestAnimationFrameMock.mockRestore()
requestIdleCallbackMock = createRequestIdleCallbackMock()
requestAnimationFrameMock = createRequestAnimationFrameMock()
})
it(`calling yieldOrContinue() for the first time should yield to the main thread`, async () => {
const jestFn = jest.fn()
const ready = (async () => {
await yieldOrContinue('background')
jestFn()
})()
await wait()
callAnimationAndIdleFrames(0, false)
await ready
expect(jestFn.mock.calls.length).toBe(1)
})
it(`calling yieldOrContinue() when there is enough time should resolve immediately`, async () => {
const jestFn = jest.fn()
const ready = (async () => {
await yieldOrContinue('background')
await yieldOrContinue('background')
jestFn()
})()
await wait()
callAnimationAndIdleFrames(100, false)
await ready
expect(jestFn.mock.calls.length).toBe(1)
})
it(`background tasks should be executed after user-visible tasks`, async () => {
const userVisibleTaskDone = jest.fn()
const backgroundTaskDone = jest.fn()
const ready = (async () => {
await Promise.all([
(async () => {
await yieldControl('user-visible')
userVisibleTaskDone()
})(),
(async () => {
await yieldControl('background')
backgroundTaskDone()
})(),
])
})()
await wait()
callAnimationAndIdleFrames(100, false)
await ready
expect(
backgroundTaskDone.mock.invocationCallOrder[0]! >
userVisibleTaskDone.mock.invocationCallOrder[0]!,
).toBe(true)
})
it(`tasks wait for next idle callback when there is no time left`, async () => {
const jestFn = jest.fn()
const ready = (async () => {
await yieldControl('background')
await yieldControl('background')
jestFn()
})()
await wait()
callAnimationAndIdleFrames(0, false)
const promise = ready
await wait()
callAnimationAndIdleFrames(0, false)
await promise
expect(jestFn.mock.calls.length).toBe(1)
})
it(`concurrent tasks wait for next idle callback when there is no time left`, async () => {
const jestFn = jest.fn()
const ready = (async () => {
await Promise.all([yieldControl('background'), yieldControl('background')])
jestFn()
})()
await wait()
callAnimationAndIdleFrames(0, false)
await wait()
callAnimationAndIdleFrames(0, false)
await ready
expect(jestFn.mock.calls.length).toBe(1)
})
it(`tasks execute in the same browser task when there is enough time`, async () => {
const jestFn = jest.fn()
const ready = (async () => {
await Promise.all([yieldControl('user-visible'), yieldControl('user-visible')])
jestFn()
})()
await wait()
callAnimationAndIdleFrames(1000, false)
await ready
expect(jestFn.mock.calls.length).toBe(1)
})
it('tracking idle phase stops on the idle callback without pending tasks', async () => {
const jestFn = jest.fn()
const ready = (async () => {
await yieldControl('user-visible')
jestFn()
})()
await wait()
callAnimationAndIdleFrames(0, false)
await wait()
callAnimationAndIdleFrames(0, false)
await ready
expect(jestFn.mock.calls.length).toBe(1)
})
it('calling startTrackingPhases() twice throws an error', () => {
expect(() => startTrackingPhases()).not.toThrow()
expect(() => startTrackingPhases()).toThrow()
// reset state
stopTrackingPhases()
})
it('cover the case that stopTrackingPhases() can throw an unreachable code error', () => {
expect(() => stopTrackingPhases()).toThrow()
})
it('cover the case that removeDeferred() can throw an unreachable code error', () => {
expect(() =>
removeDeferred({
priority: 'background',
ready: new Promise(() => {}),
resolve: () => {},
}),
).toThrow()
})
it(`when isInputPending() is available and returns false – don't yield`, async () => {
;(navigator as any).scheduling = {
isInputPending: () => false,
}
const jestFn = jest.fn()
const ready = (async () => {
await yieldControl('user-visible')
expect(isTimeToYieldMocked('user-visible')).toBe(false)
expect(isTimeToYieldMocked('background')).toBe(false)
jestFn()
})()
await wait()
callAnimationAndIdleFrames(100, false)
await ready
expect(jestFn.mock.calls.length).toBe(1)
;(navigator as any).scheduling = undefined
})
it(`when isInputPending() is available and returns true – yield`, async () => {
;(navigator as any).scheduling = {
isInputPending: () => true,
}
const jestFn = jest.fn()
const ready = (async () => {
await yieldControl('user-visible')
expect(isTimeToYieldMocked('user-visible')).toBe(true)
expect(isTimeToYieldMocked('background')).toBe(true)
jestFn()
})()
await wait()
callAnimationAndIdleFrames(100, false)
await ready
expect(jestFn.mock.calls.length).toBe(1)
;(navigator as any).scheduling = undefined
})
it('isTimeToYield() logic is called once per milisecond, caches result, return true ', async () => {
const promise = yieldControl('user-visible')
await wait()
callAnimationAndIdleFrames(100, false)
await promise
// mock
const orignalDateNow = Date.now
Date.now = () => 100
;(navigator as any).scheduling = {
isInputPending: () => false,
}
expect(isTimeToYield('user-visible')).toBe(false)
//
;(navigator as any).scheduling = {
isInputPending: () => true,
}
expect(isTimeToYield('user-visible')).toBe(false)
// unmock
Date.now = orignalDateNow
;(navigator as any).scheduling = undefined
})
it(`background task isn't called when it's a timeouted idle callback`, async () => {
const jestFn = jest.fn()
;(async () => {
await yieldControl('background')
jestFn()
})()
await wait()
callAnimationAndIdleFrames(100, true)
await wait()
expect(jestFn.mock.calls.length).toBe(0)
// expect(isTimeToYieldMocked('background')).toBe(false)
callAnimationAndIdleFrames(100, false)
await wait()
expect(jestFn.mock.calls.length).toBe(1)
// expect(isTimeToYieldMocked('background')).toBe(false)
})
it('requestIdleCallback is called without requestAnimationFrame before it', async () => {
const jestFn = jest.fn()
;(async () => {
await yieldControl('background')
jestFn()
})()
await wait()
requestIdleCallbackMock.callRequestIdleCallback(100, false)
await wait()
expect(jestFn.mock.calls.length).toBe(1)
})
})
// we use wait because:
// - we call `requestLaterMicrotask()` inside of `yieldControl()` that makes
// `requestIdleCallback()` to not be called immediately. this way we are sure
// `requestIdleCallback()` has been called
async function wait() {
return new Promise<void>((resolve) => {
setTimeout(() => {
resolve()
}, 30)
})
}
function createRequestIdleCallbackMock() {
let globalCallbackId = 1
let callbacks: {
id: number
func: IdleRequestCallback
options: IdleRequestOptions | undefined
}[] = []
let animationFrameCallbacks: { id: number; func: FrameRequestCallback }[] = []
const originalRequestIdleCallback = window.requestIdleCallback
const originalCancelIdleCallback = window.cancelIdleCallback
window.requestIdleCallback = (callback, options) => {
const callbackId = globalCallbackId
callbacks.push({ id: callbackId, func: callback, options })
globalCallbackId += 1
return callbackId
}
window.cancelIdleCallback = (id: number) => {
const index = callbacks.findIndex((callback) => callback.id === id)
if (index !== -1) {
callbacks.splice(index, 1)
}
}
return {
callRequestIdleCallback(timeRemaining: number, didTimeout: boolean) {
// call requestAnimationFrame() callbacks
{
const pendingAnimationFrameCallbacks = [...animationFrameCallbacks]
animationFrameCallbacks = []
for (const pending of pendingAnimationFrameCallbacks) {
pending.func(performance.now())
}
}
const pendingCallbacks = didTimeout
? callbacks.filter((callback) => typeof callback.options?.timeout === 'number')
: [...callbacks]
callbacks = callbacks.filter((callback) => !pendingCallbacks.includes(callback))
for (const callback of pendingCallbacks) {
callback.func({ timeRemaining: () => timeRemaining, didTimeout })
}
},
mockRestore() {
window.cancelIdleCallback = originalCancelIdleCallback
window.requestIdleCallback = originalRequestIdleCallback
},
}
}
function createRequestAnimationFrameMock() {
let globalCallbackId = 1
let callbacks: { id: number; func: FrameRequestCallback }[] = []
const originalRequestAnimationFrame = window.requestAnimationFrame
const originalCancelAnimationFrame = window.cancelAnimationFrame
window.requestAnimationFrame = (callback) => {
const callbackId = globalCallbackId
callbacks.push({ id: callbackId, func: callback })
globalCallbackId += 1
return callbackId
}
window.cancelAnimationFrame = (id: number) => {
const index = callbacks.findIndex((callback) => callback.id === id)
if (index !== -1) {
callbacks.splice(index, 1)
}
}
return {
callRequestAnimationFrame() {
const pendingCallbacks = [...callbacks]
callbacks = []
for (const pending of pendingCallbacks) {
pending.func(performance.now())
}
},
mockRestore() {
window.requestAnimationFrame = originalRequestAnimationFrame
window.cancelAnimationFrame = originalCancelAnimationFrame
},
}
}
function isTimeToYieldMocked(priority: 'background' | 'user-visible'): boolean {
const originalDateNow = Date.now
Date.now = () => Math.random()
const result = isTimeToYield(priority)
Date.now = originalDateNow
return result
} | the_stack |
import {
GraphicsIR,
IDiagramArtist,
Text,
Group,
safeAssign,
calculateTextDimensions,
PointTuple,
Rect,
TSize,
getPointAt,
symbolRegistry,
GSymbol,
mat3,
} from '@pintora/core'
import { ComponentDiagramIR, LineType, Relationship } from './db'
import { ComponentConf, getConf } from './config'
import { createLayoutGraph, getGraphBounds, LayoutEdge, LayoutGraph, LayoutNode, LayoutNodeOption } from '../util/graph'
import { makeMark, drawArrowTo, calcDirection, makeLabelBg } from '../util/artist-util'
import dagre from '@pintora/dagre'
import { Edge } from '@pintora/graphlib'
let conf: ComponentConf
function getEdgeName(relationship: Relationship) {
return `${relationship.from.name}_${relationship.to.name}_${relationship.message}`
}
type EdgeData = {
name: string
relationship: Relationship
onLayout(data: LayoutEdge<EdgeData>, edge: Edge): void
}
const componentArtist: IDiagramArtist<ComponentDiagramIR, ComponentConf> = {
draw(ir) {
// logger.info('[artist] component', ir)
conf = getConf(ir.styleParams)
const rootMark: Group = {
type: 'group',
attrs: {},
children: [],
}
const g = createLayoutGraph({
multigraph: true,
directed: true,
compound: true,
}).setGraph({
nodesep: 20,
edgesep: 20,
ranksep: 60,
})
drawComponentsTo(rootMark, ir, g)
drawInterfacesTo(rootMark, ir, g)
drawGroupsTo(rootMark, ir, g)
// add relationships
drawRelationshipsTo(rootMark, ir, g)
// do layout
dagre.layout(g, {
// debugTiming: true,
})
// ;(window as any).graph = g
adjustMarkInGraph(g)
const gBounds = getGraphBounds(g)
const pad = conf.diagramPadding
rootMark.matrix = mat3.fromTranslation(mat3.create(), [
-Math.min(0, gBounds.left) + pad,
-Math.min(0, gBounds.top) + pad,
])
const width = gBounds.width + pad * 2
const height = gBounds.height + pad * 2
return {
mark: rootMark,
width,
height,
} as GraphicsIR
},
}
function drawComponentsTo(parentMark: Group, ir: ComponentDiagramIR, g: LayoutGraph) {
const groups: Group[] = []
const fontConfig = { fontSize: conf.fontSize }
for (const component of Object.values(ir.components)) {
const id = component.name
const label = component.label || component.name
const componentLabelDims = calculateTextDimensions(label || '', fontConfig as any)
const compWidth = Math.round(componentLabelDims.width + conf.componentPadding * 2)
const compHeight = Math.round(componentLabelDims.height + conf.componentPadding * 2)
const rectMark = makeMark(
'rect',
{
width: compWidth,
height: compHeight,
fill: conf.componentBackground,
stroke: conf.componentBorderColor,
lineWidth: conf.lineWidth,
radius: 4,
},
{ class: 'component__component-rect' },
)
const textMark = makeMark('text', {
text: label,
fill: conf.textColor,
textAlign: 'center',
textBaseline: 'middle',
...fontConfig,
})
const group = makeMark(
'group',
{},
{
children: [rectMark, textMark],
class: 'component__component',
},
)
groups.push(group)
parentMark.children.push(group)
g.setNode(id, {
width: compWidth,
height: compHeight,
id,
onLayout(data: LayoutNode) {
const { x, y } = data // the center of the node
safeAssign(rectMark.attrs, { x: x - compWidth / 2, y: y - compHeight / 2 })
safeAssign(textMark.attrs, { x, y })
},
})
}
}
function drawInterfacesTo(parentMark: Group, ir: ComponentDiagramIR, g: LayoutGraph) {
const groups: Group[] = []
const fontConfig = { fontSize: conf.fontSize }
for (const interf of Object.values(ir.interfaces)) {
const id = interf.name
const label = interf.label || interf.name
const labelDims = calculateTextDimensions(label, fontConfig as any)
const interfaceSize = conf.interfaceSize
const circleMark = makeMark(
'circle',
{
x: 0,
y: 0,
r: interfaceSize / 2,
fill: conf.componentBackground,
stroke: conf.componentBorderColor,
lineWidth: conf.lineWidth,
},
{ class: 'component__interface' },
)
const textMark = makeMark('text', {
text: label,
fill: conf.textColor,
textAlign: 'center',
textBaseline: 'top',
...fontConfig,
})
const group = makeMark(
'group',
{},
{
children: [circleMark, textMark],
class: 'component__group',
},
)
groups.push(group)
parentMark.children.push(group)
const outerWidth = Math.max(interfaceSize, labelDims.width)
const nodeHeight = interfaceSize + labelDims.height
const layoutNode: LayoutNodeOption = {
width: interfaceSize,
height: nodeHeight,
id,
outerWidth,
onLayout(data: LayoutNode) {
const { x, y } = data // the center of the node
safeAssign(circleMark.attrs, { x, y: y - labelDims.height / 2 + 2 })
safeAssign(textMark.attrs, { x, y: y + 2 })
},
}
g.setNode(id, layoutNode)
if (labelDims.width > interfaceSize) {
const marginH = (labelDims.width - interfaceSize) / 2
layoutNode.marginl = marginH
layoutNode.marginr = marginH
}
}
}
function drawGroupsTo(parentMark: Group, ir: ComponentDiagramIR, g: LayoutGraph) {
for (const cGroup of Object.values(ir.groups)) {
const groupId = cGroup.name
const groupType = cGroup.groupType
// console.log('[draw] group', cGroup)
let bgMark: Rect | GSymbol
const symbolDef = symbolRegistry.get(groupType)
if (symbolDef) {
// wait till onLayout
} else {
bgMark = makeMark(
'rect',
{
fill: conf.groupBackground,
stroke: conf.groupBorderColor,
lineWidth: conf.groupBorderWidth,
radius: 2,
},
{ class: 'component__group-rect' },
)
}
const groupLabel = cGroup.label || cGroup.name
const labelMark = makeMark(
'text',
{
text: groupLabel,
fill: conf.textColor,
textAlign: 'center',
fontWeight: 'bold',
fontSize: conf.fontSize,
},
{ class: 'component__group-rect' },
)
const typeText = `[${cGroup.groupType}]`
const typeMark = makeMark(
'text',
{
text: typeText,
fill: conf.textColor,
fontSize: conf.fontSize,
textBaseline: 'hanging', // have to hack a little, otherwise label will collide with rect border in downloaded svg
},
{ class: 'component__type' },
)
const labelTextDims = calculateTextDimensions(groupLabel)
const typeTextDims = calculateTextDimensions(typeText)
const nodeMargin = {}
if (symbolDef && symbolDef.symbolMargin) {
Object.assign(nodeMargin, {
marginl: symbolDef.symbolMargin.left,
marginr: symbolDef.symbolMargin.right,
margint: symbolDef.symbolMargin.top,
marginb: symbolDef.symbolMargin.bottom,
})
}
g.setNode(groupId, {
id: groupId,
...nodeMargin,
onLayout(data: LayoutNode) {
const { x, y, width, height } = data
const containerWidth = Math.max(width, labelTextDims.width + 10)
// console.log('[group] onLayout', data, 'containerWidth', containerWidth)
if (bgMark && bgMark.type === 'rect') {
safeAssign(bgMark.attrs, { x: x - containerWidth / 2, y: y - height / 2, width: containerWidth, height })
group.children.unshift(bgMark)
} else {
bgMark = symbolRegistry.create(groupType, {
mode: 'container',
contentArea: data,
attrs: {
fill: conf.groupBackground,
stroke: conf.groupBorderColor,
lineWidth: conf.groupBorderWidth,
},
})
if (bgMark) {
// console.log('bgMark', groupId, bgMark, 'bounds', bgMark.symbolBounds)
const node: LayoutNode = g.node(groupId) as any
// node.outerTop = bgMark.symbolBounds.top + y
// node.outerBottom = bgMark.symbolBounds.bottom + y
// node.outerLeft = bgMark.symbolBounds.left + x
// node.outerRight = bgMark.symbolBounds.right + x
node.outerHeight = bgMark.symbolBounds.height
node.outerWidth = bgMark.symbolBounds.width
group.children.unshift(bgMark)
}
}
safeAssign(labelMark.attrs, { x, y: y - height / 2 + labelTextDims.height + 5 })
safeAssign(typeMark.attrs, { x: x - containerWidth / 2 + 2, y: y + height / 2 - 2 - typeTextDims.height })
},
})
for (const child of cGroup.children) {
if ('name' in child) {
const childNode: LayoutNodeOption = g.node(child.name)
if (childNode) {
g.setParent(childNode.id, groupId)
if (childNode.dummyBoxId) {
g.setParent(childNode.id, childNode.dummyBoxId)
g.setParent(childNode.dummyBoxId, groupId)
}
}
}
}
const group = makeMark(
'group',
{},
{
children: [labelMark, typeMark],
},
)
parentMark.children.unshift(group)
}
}
function drawRelationshipsTo(parentMark: Group, ir: ComponentDiagramIR, g: LayoutGraph) {
ir.relationships.forEach(function (r) {
const lineMark = makeMark(
'polyline',
{
points: [],
stroke: conf.relationLineColor,
lineCap: 'round',
},
{ class: 'component__rel-line' },
)
if ([LineType.DOTTED_ARROW, LineType.DOTTED].includes(r.line.lineType)) {
lineMark.attrs.lineDash = [4, 4]
}
let relText: Text
let relTextBg: Rect
let labelDims: TSize
if (r.message) {
labelDims = calculateTextDimensions(r.message)
relText = makeMark(
'text',
{
text: r.message,
fill: conf.textColor,
textAlign: 'center',
textBaseline: 'middle',
fontSize: conf.fontSize,
},
{ class: 'component__rel-text' },
)
relTextBg = makeLabelBg(labelDims, { x: 0, y: 0 }, { fill: conf.labelBackground })
}
const shouldDrawArrow = r.line.lineType !== LineType.STRAIGHT
g.setEdge(r.from.name, r.to.name, {
name: getEdgeName(r),
relationship: r,
labelpos: 'r',
labeloffset: 100,
onLayout(data, edge) {
// console.log('edge onlayout', data, 'points', data.points.map(t => `${t.x},${t.y}`))
const points = data.points.map(p => [p.x, p.y]) as PointTuple[]
lineMark.attrs.points = points
if (relText) {
// do not choose 0.5, otherwise label would probably cover other nodes
const anchorPoint = getPointAt(data.points, 0.4, true)
safeAssign(relText.attrs, { x: anchorPoint.x + labelDims.width / 2, y: anchorPoint.y })
safeAssign(relTextBg.attrs, { x: anchorPoint.x, y: anchorPoint.y - labelDims.height / 2 })
}
if (shouldDrawArrow) {
const lastPoint = data.points[data.points.length - 1]
const pointsForDirection = data.points.slice(-2)
const arrowRad = calcDirection.apply(null, pointsForDirection)
const arrowMark = drawArrowTo(lastPoint, 8, arrowRad, {
color: conf.relationLineColor,
})
// arrowMark.class = 'component__rel-arrow'
relationGroupMark.children.push(arrowMark)
}
},
} as EdgeData)
const relationGroupMark = makeMark(
'group',
{},
{
children: [lineMark, relTextBg, relText].filter(o => Boolean(o)),
},
)
parentMark.children.push(relationGroupMark)
})
}
const adjustMarkInGraph = function (graph: LayoutGraph) {
// console.log('adjustMarkInGraphNodes', graph)
graph.nodes().forEach(function (v) {
const nodeData: LayoutNode = graph.node(v) as any
if (nodeData) {
if (nodeData.onLayout) {
nodeData.onLayout(nodeData)
}
}
})
graph.edges().forEach(function (e) {
const edgeData: LayoutEdge<EdgeData> = graph.edge(e)
if (edgeData?.onLayout) {
edgeData.onLayout(edgeData, e)
}
})
}
export default componentArtist | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace FormSync_Error {
interface Header extends DevKit.Controls.IHeader {
/** Unique identifier of the user or team who owns the sync error. */
OwnerId: DevKit.Controls.Lookup;
/** Select the sync error status. */
StatusCode: DevKit.Controls.OptionSet;
}
interface tab_Details_Sections {
}
interface tab_General_Tab_Sections {
SYNCERROR_INFORMATION: DevKit.Controls.Section;
}
interface tab_Details extends DevKit.Controls.ITab {
Section: tab_Details_Sections;
}
interface tab_General_Tab extends DevKit.Controls.ITab {
Section: tab_General_Tab_Sections;
}
interface Tabs {
Details: tab_Details;
General_Tab: tab_General_Tab;
}
interface Body {
Tab: Tabs;
/** Action Name for which sync error has occurred */
Action: DevKit.Controls.String;
/** Enter a short description of the sync error. */
Description: DevKit.Controls.String;
/** Displays the error code. */
ErrorCode: DevKit.Controls.String;
/** Error description from the exception */
ErrorDetail: DevKit.Controls.String;
/** Error Message of the exception */
ErrorMessage: DevKit.Controls.String;
/** Date and time when the upsync request was executed on CRM server */
ErrorTime: DevKit.Controls.DateTime;
/** Select the preferred error type. */
ErrorType: DevKit.Controls.OptionSet;
/** Entity name of the record for which sync error has occurred */
Name: DevKit.Controls.String;
/** Choose the record that the sync error relates to. */
RegardingObjectId: DevKit.Controls.Lookup;
}
}
class FormSync_Error extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Sync_Error
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form Sync_Error */
Body: DevKit.FormSync_Error.Body;
/** The Header section of form Sync_Error */
Header: DevKit.FormSync_Error.Header;
}
class SyncErrorApi {
/**
* DynamicsCrm.DevKit SyncErrorApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Action Name for which sync error has occurred */
Action: DevKit.WebApi.StringValue;
/** Show the action data */
ActionData: DevKit.WebApi.StringValue;
/** Unique identifier of the user who created the sync error. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the sync Error was created. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who created the sync error. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Enter a short description of the sync error. */
Description: DevKit.WebApi.StringValue;
/** Displays the error code. */
ErrorCode: DevKit.WebApi.StringValue;
/** Error description from the exception */
ErrorDetail: DevKit.WebApi.StringValue;
/** Error Message of the exception */
ErrorMessage: DevKit.WebApi.StringValue;
/** Date and time when the upsync request was executed on CRM server */
ErrorTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Select the preferred error type. */
ErrorType: DevKit.WebApi.OptionSetValue;
/** Unique identifier of the user who last modified the sync error. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the sync error was last modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who last modified the sync error. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Entity name of the record for which sync error has occurred */
Name: DevKit.WebApi.StringValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Business unit that owns the sync error. */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the team who owns the sync error. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the user who owns the sync error. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Choose the record that the sync error relates to. */
regardingobjectid_account_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_activityfileattachment: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_activitymimeattachment_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_activityparty_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_annotation_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_appelement: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_applicationuser: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_appmodulecomponentedge: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_appmodulecomponentnode: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_appnotification: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_appointment_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_appsetting: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_appusersetting: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_attachment_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_attributeimageconfig: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_bot: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_botcomponent: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_businessdatalocalizedlabel_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_businessunit_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_canvasappextendedmetadata: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_cascadegrantrevokeaccessrecordstracker: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_cascadegrantrevokeaccessversiontracker: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_catalog: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_catalogassignment: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_category_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_channelaccessprofile_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_channelaccessprofilerule_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_channelaccessprofileruleitem_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_connection_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_connectionreference: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_connectionrole_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_connector: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_contact_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_conversationtranscript: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_customapi: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_customapirequestparameter: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_customapiresponseproperty: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_customeraddress_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_datalakefolder: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_datalakefolderpermission: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_datalakeworkspace: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_datalakeworkspacepermission: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_devkit_bpfaccount: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_duplicaterule_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_duplicaterulecondition_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_email_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_emailserverprofile_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_entityanalyticsconfig: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_entityimageconfig: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_environmentvariabledefinition: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_environmentvariablevalue: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_ExpiredProcess_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_exportsolutionupload: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_externalparty_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_externalpartyitem_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_fax_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_featurecontrolsetting: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_feedback_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_fieldpermission_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_fieldsecurityprofile_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_fileattachment_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_flowmachine: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_flowmachinegroup: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_flowsession: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_goal_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_goalrollupquery_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_holidaywrapper: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_importmap_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_internaladdress_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_internalcatalogassignment: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_kbarticle_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_kbarticletemplate_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_keyvaultreference: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_knowledgearticle_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_knowledgearticleviews_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_knowledgebaserecord_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_letter_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_mailbox_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_mailmergetemplate_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_managedidentity: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_metric_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdynce_botcontent: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_aibdataset: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_aibdatasetfile: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_aibdatasetrecord: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_aibdatasetscontainer: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_aibfile: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_aibfileattacheddata: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_aiconfiguration: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_aifptrainingdocument: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_aimodel: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_aiodimage: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_aiodlabel: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_aiodtrainingboundingbox: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_aiodtrainingimage: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_aitemplate: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_dataflow: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_federatedarticle: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_federatedarticleincident: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_helppage: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_kalanguagesetting: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_kmfederatedsearchconfig: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_kmpersonalizationsetting: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_knowledgearticleimage: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_knowledgearticletemplate: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_knowledgeinteractioninsight: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_knowledgepersonalfilter: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_knowledgesearchfilter: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_knowledgesearchinsight: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_pminferredtask: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_pmrecording: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_richtextfile: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_serviceconfiguration: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_slakpi: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_msdyn_tour: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_NewProcess_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_offlinecommanddefinition_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_organization_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_organizationdatasyncsubscription: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_organizationdatasyncsubscriptionentity: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_organizationsetting: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_package: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_pdfsetting: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_phonecall_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_pluginpackage: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_position_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_postfollow_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_processsession_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_processstage_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_processstageparameter: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_processtrigger_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_provisionlanguageforuser: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_publisher_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_queue_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_queueitem_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_recurringappointmentmaster_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_relationshipattribute: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_report_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_reportcategory_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_revokeinheritedaccessrecordstracker: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_role_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_rollupfield_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_savedquery_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_savedqueryvisualization_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_serviceplan: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_serviceplanmapping: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_settingdefinition: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_sharepointdocumentlocation_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_sharepointsite_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_sla_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_slaitem_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_slakpiinstance_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_socialactivity_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_socialprofile_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_solution_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_solutioncomponentattributeconfiguration: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_solutioncomponentbatchconfiguration: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_solutioncomponentconfiguration: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_solutioncomponentrelationshipconfiguration: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_stagesolutionupload: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_subject_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_syncerror_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_systemuser_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_systemuserauthorizationchangetracker: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_task_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_team_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_teammobileofflineprofilemembership: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_teamtemplate_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_template_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_territory_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_transactioncurrency_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_TranslationProcess_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_usermobileofflineprofilemembership: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_userquery_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_userqueryvisualization_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_virtualentitymetadata: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_workflow_syncerror: DevKit.WebApi.LookupValue;
/** Choose the record that the sync error relates to. */
regardingobjectid_workflowbinary: DevKit.WebApi.LookupValue;
/** Request data for the entity that had the sync error. */
RequestData: DevKit.WebApi.StringValue;
/** Shows whether the sync error is active or resolved. */
StateCode: DevKit.WebApi.OptionSetValue;
/** Select the sync error status. */
StatusCode: DevKit.WebApi.OptionSetValue;
/** Unique identifier of the sync error. */
SyncErrorId: DevKit.WebApi.GuidValue;
/** Shows the version number of the sync error. */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace SyncError {
enum ErrorType {
/** 0 */
Conflict,
/** 3 */
Others,
/** 2 */
Record_already_exists,
/** 1 */
Record_not_found
}
enum StateCode {
/** 0 */
Active,
/** 1 */
Resolved
}
enum StatusCode {
/** 0 */
Active,
/** 1 */
Fixed
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Sync Error'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
'use strict';
import { GenericOAuth2Router } from '../common/generic-router';
import { AuthRequest, AuthResponse, IdentityProvider, EndpointDefinition, IdpOptions, CheckRefreshDecision, LdapIdpConfig, TokenInfo, ErrorLink } from '../common/types';
import { OidcProfile, WickedUserInfo, Callback } from 'wicked-sdk';
const { debug, info, warn, error } = require('portal-env').Logger('portal-auth:ldap');
import * as wicked from 'wicked-sdk';
const Router = require('express').Router;
const qs = require('querystring');
const request = require('request');
import { LdapClient } from './ldap-client';
import { utils } from '../common/utils';
import { failMessage, failError, failOAuth, makeError } from '../common/utils-fail';
import { WickedApi } from 'wicked-sdk';
import { profileStore } from '../common/profile-store';
export class LdapIdP implements IdentityProvider {
private genericFlow: GenericOAuth2Router;
private basePath: string;
private authMethodId: string;
private authMethodConfig: LdapIdpConfig;
private ldapAttributes: string[];
private options: IdpOptions;
constructor(basePath: string, authMethodId: string, authMethodConfig: LdapIdpConfig, options: IdpOptions) {
debug(`constructor(${basePath}, ${authMethodId}, ...)`);
this.basePath = basePath;
this.genericFlow = new GenericOAuth2Router(basePath, authMethodId);
this.authMethodId = authMethodId;
this.authMethodConfig = authMethodConfig;
this.checkConfig();
this.options = options;
this.genericFlow.initIdP(this);
}
private checkConfig(): void {
const config = this.authMethodConfig;
if (!config.profile)
throw new Error('LDAP configuration: profile property is empty; must contain mapping of OIDC property to LDAP attribute');
if (!config.profile.sub)
throw new Error('LDAP Configuration: profile property must contain "sub" mapping');
if (!config.profile.email)
throw new Error('LDAP Configuration: profile property must contain "email" mapping');
if (!config.url)
throw new Error('LDAP Configuration: url not specified');
if (!config.filter || (config.filter.indexOf('%username%') < 0))
throw new Error('LDAP Configuration: filter not specified, or does not contain "%username%"');
// We always need the distinguished name, no matter what is in the profile mapping
const attributes = {
'dn': true
};
for (let profileAttribute in config.profile) {
const ldapAttribute = config.profile[profileAttribute];
attributes[ldapAttribute] = true;
}
const attributeList = [];
for (let ldapAttribute in attributes) {
attributeList.push(ldapAttribute);
}
this.ldapAttributes = attributeList;
}
public getType(): string {
return "ldap";
}
public supportsPrompt(): boolean {
return false;
}
public getRouter() {
return this.genericFlow.getRouter();
}
public authorizeWithUi(req, res, next, authRequest: AuthRequest) {
// Render a login mask...
const prefillUsername = authRequest.prefill_username;
this.renderLogin(req, res, next, null, prefillUsername);
}
public authorizeByUserPass = async (user, pass, callback: Callback<AuthResponse>) => {
debug('authorizeByUserPass()');
// loginUser returns an authResponse, so we can use that to verify that the user
// does not interactively have to change his password.
try {
const authResponse = await this.loginUser(user, pass);
debug('loginUser() successfully returned.');
debug(authResponse);
return callback(null, authResponse);
} catch (err) {
error('loginUser() failed:' + err.message);
return callback(err);
}
}
public checkRefreshToken(tokenInfo: TokenInfo, apiInfo: WickedApi, callback: Callback<CheckRefreshDecision>) {
debug('checkRefreshToken()');
const instance = this;
// TODO: How to decide whether a user is allowed to refresh over LDAP or not?
return callback(null, {
allowRefresh: true
});
}
public endpoints(): EndpointDefinition[] {
return [
{
method: 'post',
uri: '/login',
handler: this.loginHandler
}
];
}
public getErrorLinks(): ErrorLink {
return null;
}
private loginHandler = async (req, res, next) => {
debug(`POST ${this.authMethodId}/login`);
debug('loginHandler()');
// When you're done with whatever (like verifying username and password,
// or checking a callback from a 3rd party IdP), you must use the registered
// generic flow implementation object (genericFlow from the constructor) to
// pass back the same type of structure as in the authorizeByUserPass below.
const body = req.body;
const csrfToken = body._csrf;
const expectedCsrfToken = utils.getAndDeleteCsrfToken(req, 'login');
const instance = this;
if (!csrfToken || csrfToken !== expectedCsrfToken)
return this.renderLogin(req, res, next, 'Suspected login forging detected (CSRF protection).');
const username = req.body.username;
const password = req.body.password;
debug(`username: ${username}, password: ***`);
try {
const authResponse = await this.loginUser(username, password);
// Continue as normal
instance.genericFlow.continueAuthorizeFlow(req, res, next, authResponse);
} catch (err) {
debug(err);
// Delay redisplay of login page a little
await utils.delay(500);
instance.renderLogin(req, res, next, 'Username or password invalid.', username);
}
};
private renderLogin(req, res, next, flashMessage: string, prefillUsername?: string) {
debug('renderLogin()');
const authRequest = utils.getAuthRequest(req, this.authMethodId);
const authSession = utils.getSession(req, this.authMethodId);
authSession.tmpAuthResponse = null;
const instance = this;
const viewModel = utils.createViewModel(req, instance.authMethodId, 'login');
viewModel.errorMessage = flashMessage;
viewModel.disableSignup = true;
delete viewModel.forgotPasswordUrl;
if (this.authMethodConfig.forgotPasswordUrl)
viewModel.forgotPasswordUrl = this.authMethodConfig.forgotPasswordUrl;
if (prefillUsername)
viewModel.prefillUsername = prefillUsername;
if (this.authMethodConfig.usernamePrompt)
viewModel.usernamePrompt = this.authMethodConfig.usernamePrompt;
if (this.authMethodConfig.passwordPrompt)
viewModel.usernamePrompt = this.authMethodConfig.passwordPrompt;
utils.render(req, res, 'login', viewModel, authRequest);
}
private async loginUser(username: string, password: string): Promise<AuthResponse> {
const instance = this;
// Validate username; check that we don't have any wildcards or such in it
if (!/^[a-zA-Z0-9\-_@\.+]+$/.test(username)) {
warn('An invalid username (invalid characters, regex not passing) was passed in. Rejecting.');
throw new Error('loginUser(): Username contains invalid characters.');
}
let ldapClient: LdapClient;
try {
const config = instance.authMethodConfig;
ldapClient = new LdapClient({
url: config.url
});
await ldapClient.connect(config.ldapUser, config.ldapPassword);
const filter = config.filter.replace('%username%', username);
const userList = await ldapClient.search(
instance.authMethodConfig.base,
instance.ldapAttributes,
filter);
if (userList.length <= 0) {
warn(`Unknown username: ${username}`)
throw new Error('Username not known');
} else if (userList.length > 1) {
error(`LDAP search return multiple results; this should not be possible. Quitting. ${userList.length} results returned.`);
throw new Error('Ambigous user search; internal server error.');
}
const user = userList[0];
const userDN = user.dn;
if (!userDN)
throw new Error('LDAP: Successfully retrieved user, but it does not contain "dn" attribute');
debug(`Successfully retrieved DN "${userDN}"`);
// Now check whether the password is correct; this will throw if not correct
await ldapClient.checkDNPass(userDN, password);
debug('checkDNPass returned, so it has to have been successful');
// Yay, now convert the user to a profile.
return instance.createAuthResponse(user);
} finally {
if (ldapClient) {
debug('Destroying ldapClient.')
await ldapClient.destroy();
debug('Destroyed ldapClient.')
}
}
}
private createAuthResponse(user: any): AuthResponse {
debug('createAuthResponse()');
const profile = this.createProfile(user);
return {
userId: null,
customId: `${this.authMethodId}:${profile.sub}`,
defaultGroups: [],
defaultProfile: profile
};
}
private createProfile(user: any): OidcProfile {
debug('createProfile()');
debug(JSON.stringify(user));
const profileConfig = this.authMethodConfig.profile;
const profile: OidcProfile = {
sub: null
};
for (let profileAttribute in profileConfig) {
profile[profileAttribute] = user[profileConfig[profileAttribute]];
}
if (!profile.sub) {
throw new Error('LDAP: Retrieved profile could not resolve a "sub" property correctly. Is undefined or empty.');
}
if (!profile.email) {
throw new Error('LDAP: Retrieved profile could not resolve a "email" property correctly. Is undefined or empty.');
}
if (this.authMethodConfig.trustUsers) {
profile.email_verified = true;
}
debug('createProfile(): ' + JSON.stringify(profile));
return profile;
}
} | the_stack |
module TypeSystemObserver {
export interface ObjectObserver extends GUI.GUIElement {
}
export class VoidObjectObserver implements ObjectObserver {
constructor(private object: TS.VoidObject) { }
private element: JQuery;
getElement(): JQuery {
if (!this.element) {
this.element = $('<div></div>');
this.element.addClass('objectElement');
}
return this.element;
}
updateUI() {
}
}
export class BaseClassObjectObserver implements ObjectObserver {
constructor(private object: TS.BaseClassObject) { }
private element: JQuery;
private value: JQuery;
getElement(): JQuery {
if (!this.element) {
this.element = $('<div></div>');
this.element.addClass('objectElement');
this.value = $('<div></div>');
this.value.addClass('baseObjectValue');
this.value.append(this.object.rawValue);
this.element.append(this.value);
}
return this.element;
}
updateUI() {
this.value.text(this.object.rawValue);
}
}
export class FunctionObserver implements ObjectObserver {
constructor(private fun: TS.FunctionObject) { }
private element: JQuery;
private value: JQuery;
getElement(): JQuery {
if (!this.element) {
this.element = $('<div></div>');
this.element.addClass('objectElement');
this.value = $('<div></div>');
this.value.addClass('customObjectValue');
this.value.text('<fun>');
this.element.append(this.value);
}
return this.element;
}
updateUI() { }
}
export class ClassFieldObserver implements MemoryObservers.MemoryFieldObserver {
constructor(public field: TS.ClassObjectField) { }
private element: JQuery;
private elementName: JQuery;
//private elementEqual: JQuery;
private elementValue: JQuery;
getElement(): JQuery {
if (!this.element) {
this.element = $('<div></div>');
this.element.addClass('objectField');
this.elementName = $('<div></div>');
this.elementName.addClass('objectFieldName');
//this.elementEqual = $('<div>=</div>');
//this.elementEqual.addClass('objectFieldEqual');
this.elementValue = $('<div></div>');
this.elementValue.addClass('objectFieldValue');
this.elementName.append(this.field.name);
this.element.append(this.elementName);
//this.element.append(this.elementEqual);
this.element.append(this.elementValue);
}
return this.element;
}
setFieldValue(value: TS.Obj) {
this.getElement();
this.elementValue.empty();
this.elementValue.append(value.observer.getElement());
value.observer.updateUI();
}
updateUI() {
DS.Stack.forAll(
this.field.getReferences(),
(value: TS.Reference) => {
value.observer.updateUI();
});
this.field.getValue().observer.updateUI();
}
}
export class ClassObjectObserver implements ObjectObserver {
constructor(private object: TS.ClassObject) { }
private element: JQuery;
getElement(): JQuery {
if (!this.element) {
this.element = $('<div></div>');
this.element.addClass('objectElement');
var fields = this.object.fields;
for (var key in fields) {
this.element.append(fields[key].observer.getElement());
}
}
return this.element;
}
updateUI() {
for (var key in this.object.fields)
{
this.object.fields[key].observer.updateUI();
}
}
}
export class ArrayFieldObserver implements MemoryObservers.MemoryFieldObserver {
constructor(public field: TS.ArrayField) { }
private element: JQuery;
private elementIndex: JQuery;
//private elementEqual: JQuery;
private elementValue: JQuery;
getElement(): JQuery {
if (!this.element) {
this.element = $('<div></div>');
this.element.addClass('objectField');
this.elementIndex = $('<div></div>');
this.elementIndex.addClass('objectFieldName');
//this.elementEqual = $('<div>:</div>');
//this.elementEqual.addClass('objectFieldEqual');
this.elementValue = $('<div></div>');
this.elementValue.addClass('objectFieldValue');
this.elementIndex.append(this.field.index.toString());
this.element.append(this.elementIndex);
//this.element.append($('<div></div>').append(this.elementEqual));
this.element.append(this.elementValue);
}
return this.element;
}
setFieldValue(value: TS.Obj) {
this.getElement();
this.elementValue.empty();
this.elementValue.append(value.observer.getElement());
}
updateUI() {
DS.Stack.forAll(
this.field.getReferences(),
(value: TS.Reference) => {
value.observer.updateUI();
});
this.field.getValue().observer.updateUI();
}
}
export class ArrayObjectObserver implements ObjectObserver {
constructor(private object: TS.ArrayObject) { }
private element: JQuery;
getElement(): JQuery {
if (!this.element) {
this.element = $('<div></div>');
this.element.addClass('objectElement');
var fields = this.object.values;
for (var i = 0; i < this.object.prototype.length; i++) {
this.element.append(fields[i].observer.getElement());
}
}
return this.element;
}
updateUI() {
for (var i = 0; i < this.object.prototype.length; i++) {
this.object.values[i].observer.updateUI();
}
}
}
export class ReferenceObserver implements ObjectObserver {
constructor(private reference: TS.Reference) {
}
private element: JQuery;
private value: JQuery;
private svg: JQuery;
private svgCircleA: JQuery;
private svgCircleB: JQuery;
private svgLineA: JQuery;
private svgLineB: JQuery;
private svgArrow1A: JQuery;
private svgArrow2A: JQuery;
private svgArrow1B: JQuery;
private svgArrow2B: JQuery;
protected strokeColor = '#5a2569';
protected fillColor = '#9e61b0';
getElement(): JQuery {
if (!this.element) {
this.element = $('<div></div>');
this.element.addClass('objectElement');
this.element.addClass('reference');
this.svg = $('<svg class="svgConnection"></svg>');
this.svgCircleB = GUI.svgElement('circle').appendTo(this.svg).attr('fill', this.strokeColor).attr('r', '5');
var svgBackground = GUI.svgElement('g').addClass('svgBackground').appendTo(this.svg).attr('stroke', this.strokeColor).attr('stroke-width', '4').attr('fill', 'transparent').attr('stroke-linecap', 'round');
this.svgLineB = GUI.svgElement('path').appendTo(svgBackground);
this.svgArrow1B = GUI.svgElement('path').appendTo(svgBackground);
this.svgArrow2B = GUI.svgElement('path').appendTo(svgBackground);
this.svgCircleA = GUI.svgElement('circle').appendTo(this.svg).attr('fill', this.fillColor).attr('r', '4');
var svgForeground = GUI.svgElement('g').addClass('svgForeground').appendTo(this.svg).attr('stroke', this.fillColor).attr('stroke-width', '2').attr('fill', 'transparent').attr('stroke-linecap', 'round');
this.svgLineA = GUI.svgElement('path').appendTo(svgForeground);
this.svgArrow1A = GUI.svgElement('path').appendTo(svgForeground);
this.svgArrow2A = GUI.svgElement('path').appendTo(svgForeground);
this.element.append(this.svg);
this.value = $('<div></div>');
this.value.addClass('referenceValue');
this.element.append(this.value);
}
return this.element;
}
updateUI() {
this.getElement();
if (this.reference.reference) {
var referenced = this.reference.reference.observer.getElement();
var endPoint = {
x: referenced.offset().left + 2 - (this.element.offset().left + this.element.width() / 2),
y: referenced.offset().top + referenced.height() / 2 - (this.element.offset().top + this.element.height() / 2)
}
var offset = Math.sqrt(Math.pow(endPoint.x, 2) + Math.pow(endPoint.y, 2)) / 2;
var bizarreCurve = 'M0,0 C0,0 ' + (endPoint.x - offset) + ',' + endPoint.y + ' ' + endPoint.x + ',' + endPoint.y + ' C' + (endPoint.x - offset) + ',' + endPoint.y + ' 0,0 0,0';
this.svgLineA.attr('d', bizarreCurve);
this.svgLineB.attr('d', bizarreCurve);
var arrow1 = 'M ' + endPoint.x + ',' + endPoint.y + ' L' + (endPoint.x - 5) + ',' + (endPoint.y - 5);
var arrow2 = 'M ' + endPoint.x + ',' + endPoint.y + ' L' + (endPoint.x - 5) + ',' + (endPoint.y + 5);
this.svgArrow1A.attr('d', arrow1);
this.svgArrow1B.attr('d', arrow1);
this.svgArrow2A.attr('d', arrow2);
this.svgArrow2B.attr('d', arrow2);
}
else {
var bizarreCurve = 'M0,0 L20,0';
this.svgLineA.attr('d', bizarreCurve);
this.svgLineB.attr('d', bizarreCurve);
var arrow1 = 'M20,0 L20,-5';
var arrow2 = 'M20,0 L20,5'
this.svgArrow1A.attr('d', arrow1);
this.svgArrow1B.attr('d', arrow1);
this.svgArrow2A.attr('d', arrow2);
this.svgArrow2B.attr('d', arrow2);
}
}
}
export class AliasObserver extends ReferenceObserver {
protected strokeColor = '#2f652b';
protected fillColor = '#467d42';
}
export class PrototypeObserver implements ObjectObserver {
constructor(private typ: TS.Prototype) { }
private element: JQuery;
private value: JQuery;
getElement(): JQuery {
if (!this.element) {
this.element = $('<div></div>');
this.element.addClass('objectElement');
this.value = $('<div></div>');
this.value.addClass('customObjectValue');
this.value.text('<type>');
this.element.append(this.value);
}
return this.element;
}
updateUI() { }
}
}
module MemoryObservers {
class StackFieldLabel {
public element: JQuery = $('<div></div>').addClass('stackField');
constructor(private index: number) {
this.setText(index);
}
private setText(index: number) {
this.element.empty();
var hex = index.toString(16);
this.element.text('0x' + '00000'.slice(hex.length) + hex);
}
}
var _environmentObserver: EnvironmentObserver = null;
export function getEnvironmentObserver(): EnvironmentObserver {
if (!_environmentObserver)
_environmentObserver = new EnvironmentObserver();
return _environmentObserver;
}
class EnvironmentObserver {
private tempStack: JQuery;
private stack: JQuery;
private heap: JQuery;
private stackValues: JQuery = $('<div></div>').addClass('stackValuesHolder');
private tempStackValues: JQuery = $('<div></div>').addClass('stackValuesHolder');
private stackLabels: JQuery = $('<div></div>').addClass('stackLabels');
private tempStackLabels: JQuery = $('<div></div>').addClass('stackLabels');
private stackLabelsInner: JQuery = $('<div></div>').addClass('stackLabelsInner');
private tempStackLabelsInner: JQuery = $('<div></div>').addClass('stackLabelsInner');
constructor() {
this.tempStack = $('.tempStack');
this.stack = $('.stack');
this.heap = $('.heap');
this.stack.append($('<div></div>').addClass('stackPartName').text('Stack'));
this.tempStack.append($('<div></div>').addClass('stackPartName').text('Temporary'));
this.stack.append(this.stackLabels);
this.stackLabels.append(this.stackLabelsInner);
this.tempStack.append(this.tempStackLabels);
this.tempStackLabels.append(this.tempStackLabelsInner);
this.stack.append(this.stackValues);
this.tempStack.append(this.tempStackValues);
this.clear();
}
clear() {
this.heap.empty();
this.stackValues.empty();
this.tempStackValues.empty();
this.stackLabelsInner.empty();
this.tempStackLabelsInner.empty();
this.stackFieldsNumber = 0;
this.tempStackFieldsNumber = 0;
for (var i = 0; i < 140; i++) {
this.addStackLabel();
this.addTempStackLabel();
}
this.updateLabelsOffest();
this.updateTempLabelsOffest();
}
private stackFieldsNumber = 0;
private addStackLabel() {
var newStackField = new StackFieldLabel(this.stackFieldsNumber);
this.stackLabelsInner.append(newStackField.element);
this.stackFieldsNumber++;
}
private tempStackFieldsNumber = 0;
private addTempStackLabel() {
var newStackField = new StackFieldLabel(this.tempStackFieldsNumber);
this.tempStackLabelsInner.append(newStackField.element);
this.tempStackFieldsNumber++;
}
// Manages the offset of the backgrouns, so fields addresses do not overlap with values.
private updateLabelsOffest() {
var valuesHeight = this.stackValues.innerHeight();
this.stackLabels.css('margin-top', valuesHeight);
this.stackLabelsInner.css('margin-top', -valuesHeight);
}
private updateTempLabelsOffest() {
var valuesHeight = this.tempStackValues.innerHeight();
this.tempStackLabels.css('margin-top', valuesHeight);
this.tempStackLabelsInner.css('margin-top', -valuesHeight);
}
addFieldToStack(field: Memory.StackField) {
this.stackValues.append(field.observer.getElement());
field.observer.updateUI();
this.updateLabelsOffest();
}
removeFieldFromStack(field: Memory.StackField) {
field.observer.getElement().detach();
this.updateLabelsOffest();
}
addScopeToStack(scope: Memory.StackScope) {
this.stackValues.append(scope.observer.getElement());
scope.observer.updateUI();
this.updateLabelsOffest();
}
removeScopeFromStack(scope: Memory.StackScope) {
scope.observer.getElement().detach();
this.updateLabelsOffest();
}
addFieldToHeap(field: Memory.HeapField) {
var element = field.observer.getElement();
element.css('left', this.heap.width()/4);
var relativeElement = this.heap.children().last();
if (relativeElement.length)
element.css('top', parseInt(relativeElement.css('top')) + relativeElement.height() + 20);
else
element.css('top', 10);
this.heap.append(field.observer.getElement());
field.observer.updateUI();
}
addFieldToTempStack(field: Memory.TempStackField) {
this.tempStackValues.append(field.observer.getElement());
field.observer.updateUI();
this.updateTempLabelsOffest();
}
removeFieldFromTempStack(field: Memory.TempStackField) {
field.observer.getElement().detach();
this.updateTempLabelsOffest();
}
}
export class ScopeObserver {
constructor(private scope: Memory.StackScope) {
}
private element: JQuery;
private elementName: JQuery;
getElement(): JQuery {
if (!this.element) {
this.element = $('<div></div>');
this.element.addClass('scope');
var wrapper = $('<div></div>');
this.elementName = $('<div></div>');
this.elementName.addClass('scopeName');
this.elementName.append(this.scope.name);
this.element.append(this.elementName);
}
return this.element;
}
updateUI() { }
// Called when the variable gets covered/uncovered
visible(isVisible: boolean) {
if (isVisible)
this.element.removeClass('onStackElementHidden');
else
this.element.addClass('onStackElementHidden');
}
}
export interface MemoryFieldObserver {
getElement(): JQuery;
setFieldValue(value: TS.Obj);
updateUI();
}
export class StackFieldObserver implements MemoryFieldObserver {
constructor(private field: Memory.StackField) {
}
private element: JQuery;
private elementName: JQuery;
private elementValue: JQuery;
getElement(): JQuery {
if (!this.element) {
this.element = $('<div></div>');
this.element.addClass('onStackElement');
var wrapper = $('<div></div>');
this.elementName = $('<div></div>');
this.elementName.addClass('onStackElementName');
this.elementValue = $('<div></div>');
this.elementValue.addClass('onStackElementValue');
this.elementName.append(this.field.name);
this.element.append(this.elementName);
this.element.append(this.elementValue);
}
return this.element;
}
setFieldValue(value: TS.Obj) {
this.getElement();
this.elementValue.empty();
this.elementValue.append(value.observer.getElement());
value.observer.updateUI();
}
updateUI() {
DS.Stack.forAll(
this.field.getReferences(),
(value: TS.Reference) => {
value.observer.updateUI();
});
this.field.getValue().observer.updateUI();
}
// Called when the variable gets covered/uncovered
visible(isVisible: boolean) {
if (isVisible)
this.element.removeClass('onStackElementHidden');
else
this.element.addClass('onStackElementHidden');
}
}
export class TempStackFieldObserver implements MemoryFieldObserver {
constructor(private field: Memory.TempStackField) {
}
private element: JQuery;
private elementValue: JQuery;
getElement(): JQuery {
if (!this.element) {
this.element = $('<div></div>');
this.element.addClass('onStackElement');
var wrapper = $('<div></div>');
this.elementValue = $('<div></div>');
this.elementValue.addClass('onStackElementValue');
this.element.append(this.elementValue);
}
return this.element;
}
setFieldValue(value: TS.Obj) {
this.getElement();
this.elementValue.empty();
this.elementValue.append(value.observer.getElement());
value.observer.updateUI();
}
updateUI() {
DS.Stack.forAll(
this.field.getReferences(),
(value: TS.Reference) => {
value.observer.updateUI();
});
this.field.getValue().observer.updateUI();
}
}
export class HeapFieldObserver implements MemoryFieldObserver {
constructor(private field: Memory.HeapField) {
}
private element: JQuery;
private elementValue: JQuery;
getElement(): JQuery {
if (!this.element) {
this.element = $('<div></div>');
this.element.addClass('onHeapElement');
this.elementValue = $('<div></div>');
this.elementValue.addClass('onHeapElementValue');
this.element.append(this.elementValue);
this.element.draggable(<any>{
scroll: false,
containment: "parent",
drag: (event, ui) => {
if (!this.UIUpdated)
return;
this.UIUpdated = false;
requestAnimationFrame(() => {
this.updateUI();
});
},
stop: (event, ui) => {
this.updateUI();
}
});
}
return this.element;
}
setFieldValue(value: TS.Obj) {
this.getElement();
this.elementValue.empty();
this.elementValue.append(value.observer.getElement());
value.observer.updateUI();
}
private UIUpdated = true;
updateUI() {
this.UIUpdated = false;
DS.Stack.forAll(
this.field.getReferences(),
(value: TS.Reference) => {
value.observer.updateUI();
});
this.element.css('left', Math.min(parseInt(this.element.css('left')), this.element.parent().width() - this.element.outerWidth()));
this.element.css('left', Math.max(parseInt(this.element.css('left')), 0));
this.field.getValue().observer.updateUI();
this.UIUpdated = true;
}
}
} | the_stack |
import { clip, getNote, getDuration } from './browser-clip';
import { errorHasMessage, IIndexable } from './utils';
/**
* Get the next logical position to play in the session
* Tone has a build-in method `Tone.Transport.nextSubdivision('4n')`
* but I think it s better to round off as follows for live performance
*/
const getNextPos = (
clip: null | { align?: string; alignOffset?: string }
): number | string => {
// TODO: (soon) convert to using transportPosTicks (fewer computations)
const arr = Tone.Transport.position.split(':');
// If we are still around 0:0:0x, then set start position to 0
if (arr[0] === '0' && arr[1] === '0') {
return 0;
}
// Else set it to the next bar
const transportPosTicks = Tone.Transport.ticks;
const align = clip?.align || '1m';
const alignOffset = clip?.alignOffset || '0';
const alignTicks: number = Tone.Ticks(align).toTicks();
const alignOffsetTicks: number = Tone.Ticks(alignOffset).toTicks();
const nextPosTicks = Tone.Ticks(
Math.floor(transportPosTicks / alignTicks + 1) * alignTicks +
alignOffsetTicks
);
// const nextPosBBS = nextPosTicks.toBarsBeatsSixteenths();
// return nextPosBBS; // Extraneous computations
return nextPosTicks;
};
/**
* Channel
* A channel is made up of a Tone.js Player/Instrument, one or more
* Tone.js sequences (known as clips in Scribbletune)
* & optionally a set of effects (with or without presets)
*
* API:
* clips -> Get all clips for this channel
* addClip -> Add a new clip to the channel
* startClip -> Start a clip at the provided index
* stopClip -> Stop a clip at the provided index
* activeClipIdx -> Get the clip that is currently playing
*/
export class Channel {
idx: number | string;
name: string;
activePatternIdx: number;
channelClips: any;
clipNoteCount: number;
instrument: any;
external: any;
initializerTask: Promise<void>;
hasLoaded: boolean; // if (!this.hasLoaded) - don't play this channel. Either still loading, or (initOutputProducer() rejected,
hasFailed: boolean | Error;
private eventCbFn: EventFn | undefined;
private playerCbFn: playerObserverFnc | undefined;
private counterResetTask: number | undefined;
constructor(params: ChannelParams) {
this.idx = params.idx || 0;
this.name = params.name || 'ch ' + params.idx;
this.activePatternIdx = -1;
this.channelClips = [];
this.clipNoteCount = 0;
// Filter out unrequired params and create clip params object
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { clips, samples, sample, synth, ...params1 } = params;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { external, sampler, buffer, ...params2 } = params1;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { player, instrument, volume, ...params3 } = params2;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { eventCb, playerCb, effects, ...params4 } = params3;
const { context = Tone.getContext(), ...originalParamsFiltered } = params4;
this.eventCbFn = eventCb;
this.playerCbFn = playerCb;
// Async section
this.hasLoaded = false;
this.hasFailed = false;
this.initializerTask = this.initOutputProducer(context, params).then(() => {
return this.initInstrument(context, params).then(() => {
return this.adjustInstrument(context, params).then(() => {
return this.initEffects(context, params);
});
});
});
// End Async section
// Sync section
let clipsFailed: { message: string } | false = false;
try {
params.clips.forEach((c: any, i: number) => {
try {
this.addClip({
...c,
...originalParamsFiltered,
});
} catch (e) {
// Annotate the error with Clip info
throw new Error(
`${errorHasMessage(e) ? e.message : e} in clip ${i + 1}`
);
}
}, this);
} catch (e) {
clipsFailed = e as { message: string }; // Stash the error
}
// End Sync section
// Reconcile sync section with async section
this.initializerTask
.then(() => {
if (clipsFailed) {
throw clipsFailed;
}
this.hasLoaded = true;
this.eventCb('loaded', {}); // Report async load completion.
})
.catch(e => {
this.hasFailed = e;
this.eventCb('error', { e }); // Report async errors.
});
}
static setTransportTempo(valueBpm: number): void {
Tone.Transport.bpm.value = valueBpm;
}
static startTransport(): void {
Tone.start();
Tone.Transport.start();
}
static stopTransport(deleteEvents = true): void {
Tone.Transport.stop();
if (deleteEvents) {
// Delete all events in the Tone.Transport
Tone.Transport.cancel();
}
}
setVolume(volume: number): void {
// ? this.volume = volume;
// Change volume of the player
// if (this.player) {
// this.player.volume.value = volume;
// }
// Change volume of the sampler
// if (this.sampler) {
// this.sampler.volume.value = volume;
// }
// Change volume of the instrument
if (this.instrument) {
this.instrument.volume.value = volume;
}
// Change volume of the external
if (this.external) {
this.external.setVolume?.(volume);
}
}
startClip(idx: number, position?: number | string): void {
const clip = this.channelClips[idx];
position = position || (position === 0 ? 0 : getNextPos(clip));
// Stop any other currently running clip
if (this.activePatternIdx > -1 && this.activePatternIdx !== idx) {
this.stopClip(this.activePatternIdx, position);
}
if (clip && clip.state !== 'started') {
// We need to schedule that for just before when clip?.start(position) events start coming.
this.counterResetTask = Tone.Transport.scheduleOnce(
(/* time: Tone.Seconds */) => {
this.clipNoteCount = 0;
},
position
);
this.activePatternIdx = idx;
// clip?.stop(position); // DEBUG: trying to clear out start/stop events
// clip?.clear(position); // DEBUG: trying to clear out events
clip?.start(position);
}
}
stopClip(idx: number, position?: number | string): void {
const clip = this.channelClips[idx];
position = position || (position === 0 ? 0 : getNextPos(clip));
clip?.stop(position);
if (idx === this.activePatternIdx) {
this.activePatternIdx = -1;
}
}
addClip(clipParams: ClipParams, idx?: number): void {
idx = idx || this.channelClips.length;
if (clipParams.pattern) {
this.channelClips[idx as number] = clip(
{
...clipParams,
},
this
);
// Pass certain clipParams into getNextPos()
['align', 'alignOffset'].forEach(key => {
if ((clipParams as IIndexable)[key]) {
this.channelClips[idx as number][key] = (clipParams as IIndexable)[
key
];
}
});
} else {
// Allow creation of empty clips
this.channelClips[idx as number] = null;
}
}
/**
* @param {Object} ClipParams clip parameters
* @return {Function} function that can be used as the callback in Tone.Sequence https://tonejs.github.io/docs/Sequence
*/
getSeqFn(params: ClipParams): SeqFn {
if (this.external) {
return (time: string, el: string) => {
if (el === 'x' || el === 'R') {
const counter = this.clipNoteCount;
if (this.hasLoaded) {
const note = getNote(el, params, counter)[0];
const duration = getDuration(params, counter);
const durSeconds = Tone.Time(duration).toSeconds();
this.playerCb({ note, duration, time, counter });
try {
this.external.triggerAttackRelease?.(note, durSeconds, time);
} catch (e) {
this.eventCb('error', { e }); // Report play errors.
}
}
this.clipNoteCount++;
}
};
} else if (this.instrument instanceof Tone.Player) {
return (time: string, el: string) => {
if (el === 'x' || el === 'R') {
const counter = this.clipNoteCount;
if (this.hasLoaded) {
this.playerCb({ note: '', duration: '', time, counter });
try {
this.instrument.start(time);
} catch (e) {
this.eventCb('error', { e }); // Report play errors.
}
}
this.clipNoteCount++;
}
};
} else if (
this.instrument instanceof Tone.PolySynth ||
this.instrument instanceof Tone.Sampler
) {
return (time: string, el: string) => {
if (el === 'x' || el === 'R') {
const counter = this.clipNoteCount;
if (this.hasLoaded) {
const note = getNote(el, params, counter);
const duration = getDuration(params, counter);
this.playerCb({ note, duration, time, counter });
try {
this.instrument.triggerAttackRelease(note, duration, time);
} catch (e) {
this.eventCb('error', { e }); // Report play errors.
}
}
this.clipNoteCount++;
}
};
} else if (this.instrument instanceof Tone.NoiseSynth) {
return (time: string, el: string) => {
if (el === 'x' || el === 'R') {
const counter = this.clipNoteCount;
if (this.hasLoaded) {
const duration = getDuration(params, counter);
this.playerCb({ note: '', duration, time, counter });
try {
this.instrument.triggerAttackRelease(duration, time);
} catch (e) {
this.eventCb('error', { e }); // Report play errors.
}
}
this.clipNoteCount++;
}
};
} else {
return (time: string, el: string) => {
if (el === 'x' || el === 'R') {
const counter = this.clipNoteCount;
if (this.hasLoaded) {
const note = getNote(el, params, counter)[0];
const duration = getDuration(params, counter);
this.playerCb({ note, duration, time, counter });
try {
this.instrument.triggerAttackRelease(note, duration, time);
} catch (e) {
this.eventCb('error', { e }); // Report play errors.
}
}
this.clipNoteCount++;
}
};
}
}
private eventCb(event: string, params: any): void {
if (typeof this.eventCbFn === 'function') {
params.channel = this;
this.eventCbFn(event, params);
}
}
private playerCb(params: any): void {
if (typeof this.playerCbFn === 'function') {
params.channel = this;
this.playerCbFn(params);
}
}
/**
* Check Tone.js object loaded state and either invoke `resolve` right away, or attach to and wait using Tone onload cb.
* It's an ugly hack that reaches into Tone's internal ._buffers or ._buffer to insert itself into .onload() callback.
* Tone has different ways to pull the onload callback from within to the API, so this implementation is very brittle.
* The sole reason for its existence is to handle async loaded state of Tone instruments that we allow to pass in from outside.
* If that option is eliminated, then this hacky function can be killed (or re-implemented via public onload API)
* @param toneObject Tone.js object (will work with non-Tone objects that have same loaded/onload properties)
* @param resolve onload callback
*/
private checkToneObjLoaded(toneObject: any, resolve: () => void) {
const skipRecursion = toneObject instanceof Tone.Sampler; // Sampler has a Map of ToneAudioBuffer, and our method to find inner .onload() does not work since there is no single one.
// eslint-disable-next-line no-prototype-builtins
if ('loaded' in toneObject) {
if (toneObject.loaded) {
resolve();
return;
}
if (skipRecursion) {
return;
}
// Try Recursion into inner objects:
let handled = false;
['buffer', '_buffer', '_buffers'].forEach(key => {
if (key in toneObject) {
this.checkToneObjLoaded(toneObject[key], resolve);
handled = true;
}
});
if (handled) {
return;
}
}
// Check object type if it has load/onload (and _buffers or _buffer), then call resolve()
// The list was created for Tone@14.8.0 by grepping and reviewing the source code.
// Known objecs to have:
const hasOnload =
toneObject instanceof Tone.ToneAudioBuffer ||
toneObject instanceof Tone.ToneBufferSource ||
// Falback for "future" objects
('loaded' in toneObject && 'onload' in toneObject);
if (!hasOnload) {
// console.log('resolve() for ch "%o" idx %o onload NOT FOUND', this.name, this.idx);
// This is not a good assumption. E.g. it does not work for Tone.ToneAudioBuffers
resolve();
} else {
const oldOnLoad = toneObject.onload;
toneObject.onload = () => {
if (oldOnLoad && typeof oldOnLoad === 'function') {
toneObject.onload = oldOnLoad;
oldOnLoad();
}
// console.log('resolve() for ch "%o" idx %o', this.name, this.idx);
resolve();
};
}
}
private recreateToneObjectInContext(
toneObject: any, // Tone.PolySynth | Tone.Player | Tone.Sampler | Tone['' | '']
context: any
): Promise<any> {
context = context || Tone.getContext();
// eslint-disable-next-line @typescript-eslint/no-unused-vars
return new Promise<any>((resolve, reject) => {
// Tone.PolySynth | Tone.Player | Tone.Sampler | Tone['' | '']
if (toneObject instanceof Tone.PolySynth) {
const newObj = Tone.PolySynth(Tone[toneObject._dummyVoice.name], {
...toneObject.get(),
context,
});
this.checkToneObjLoaded(newObj, () => resolve(newObj));
} else if (toneObject instanceof Tone.Player) {
const newObj = Tone.Player({
url: toneObject._buffer,
context,
onload: () => this.checkToneObjLoaded(newObj, () => resolve(newObj)),
});
} else if (toneObject instanceof Tone.Sampler) {
const { attack, curve, release, volume } = toneObject.get();
const paramsFromSampler = {
attack,
curve,
release,
volume,
};
const paramsFromBuffers = {
baseUrl: toneObject._buffers.baseUrl,
urls: Object.fromEntries(toneObject._buffers._buffers.entries()),
};
const newObj = Tone.Sampler({
...paramsFromSampler,
...paramsFromBuffers,
context,
onload: () => this.checkToneObjLoaded(newObj, () => resolve(newObj)),
});
} else {
const newObj = Tone[toneObject.name]({
...toneObject.get(),
context,
onload: () => this.checkToneObjLoaded(newObj, () => resolve(newObj)),
});
this.checkToneObjLoaded(newObj, () => resolve(newObj));
}
});
}
private initOutputProducer(
context: any,
params: ChannelParams
): Promise<void> {
context = context || Tone.getContext();
return new Promise<void>((resolve, reject) => {
/*
* 1. The params object can be used to pass a sample (sound source) OR a synth(Synth/FMSynth/AMSynth etc) or samples.
* Scribbletune will then create a Tone.js Player or Tone.js Instrument or Tone.js Sampler respectively
* 2. It can also be used to pass a Tone.js Player object or instrument that was created elsewhere
* (mostly by Scribbletune itself in the channel creation method)
**/
if (params.synth) {
if (params.instrument) {
throw new Error(
'Either synth or instrument can be provided, but not both.'
);
}
if ((params.synth as SynthParams).synth) {
const synthName = (params.synth as SynthParams).synth;
// const presetName = (params.synth as SynthParams).presetName; // Unused here
const preset = (params.synth as SynthParams).preset || {};
this.instrument = new Tone[synthName]({
...preset,
context,
// Use onload for cases when synthName calls out Tone.Sample/Player/Sampler.
// It could be a universal way to load Tone.js instruments.
onload: () => this.checkToneObjLoaded(this.instrument, resolve),
// This onload is ignored in all synths. Therefore we call checkToneObjLoaded() again below.
// It is safe to call resolve() multiple times for Promise<void>
});
this.checkToneObjLoaded(this.instrument, resolve);
} else {
this.instrument = params.synth; // TODO: This is dangerous by-reference assignment.
console.warn(
'The "synth" parameter with instrument will be deprecated in the future. Please use the "instrument" parameter instead.'
);
// params.synth describing the Tone[params.synth.synth] is allowed.
this.checkToneObjLoaded(this.instrument, resolve);
}
} else if (typeof params.instrument === 'string') {
this.instrument = new Tone[params.instrument]({ context });
this.checkToneObjLoaded(this.instrument, resolve);
} else if (params.instrument) {
this.instrument = params.instrument; // TODO: This is dangerous by-reference assignment. Tone.instrument has context that holds all other instruments. Client side params get polluted with circular references. If params come from e.g. react-ApolloClient data, Apollo tools crash on circular references.
this.checkToneObjLoaded(this.instrument, resolve);
} else if (params.sample || params.buffer) {
this.instrument = new Tone.Player({
url: params.sample || params.buffer,
context,
onload: () => this.checkToneObjLoaded(this.instrument, resolve),
});
} else if (params.samples) {
this.instrument = new Tone.Sampler({
urls: params.samples,
context,
onload: () => this.checkToneObjLoaded(this.instrument, resolve),
});
} else if (params.sampler) {
this.instrument = params.sampler; // TODO: This is dangerous by-reference assignment.
this.checkToneObjLoaded(this.instrument, resolve);
} else if (params.player) {
this.instrument = params.player; // TODO: This is dangerous by-reference assignment.
this.checkToneObjLoaded(this.instrument, resolve);
} else if (params.external) {
this.external = { ...params.external }; // Sanitize object by shallow clone
this.instrument = {
context,
volume: { value: 0 },
};
// Do not call! this.checkToneObjLoaded(this.instrument, resolve);
if (params.external.init) {
return params.external
.init(context.rawContext)
.then(() => {
resolve();
})
.catch((e: any) => {
reject(
new Error(
`${e.message} loading external output module of channel idx ${
this.idx
}, ${this.name ?? '(no name)'}`
)
);
});
} else {
resolve();
}
} else {
throw new Error(
'One of required synth|instrument|sample|sampler|samples|buffer|player|external is not provided!'
);
}
if (!this.instrument) {
throw new Error('Failed instantiating instrument from given params.');
}
});
}
private initInstrument(context: any, params: ChannelParams): Promise<void> {
context = context || Tone.getContext();
if (!params.external && this.instrument?.context !== context) {
return this.recreateToneObjectInContext(this.instrument, context).then(
newObj => {
this.instrument = newObj;
}
);
} else {
// Nothing to do
// eslint-disable-next-line @typescript-eslint/no-unused-vars
return new Promise<void>((resolve, reject) => {
resolve();
});
}
}
private adjustInstrument(context: any, params: ChannelParams): Promise<void> {
context = context || Tone.getContext();
// eslint-disable-next-line @typescript-eslint/no-unused-vars
return new Promise<void>((resolve, reject) => {
if (params.volume) {
// this.instrument.volume.value = params.volume;
this.setVolume(params.volume);
}
resolve();
});
}
private initEffects(context: any, params: ChannelParams): Promise<void> {
context = context || Tone.getContext();
const createEffect = (effect: any): Promise<any> => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
return new Promise<any>((resolve, reject) => {
if (typeof effect === 'string') {
resolve(new Tone[effect]({ context }));
} else if (effect.context !== context) {
return this.recreateToneObjectInContext(effect, context);
} else {
resolve(effect);
}
}).then(effectOut => {
return effectOut.toDestination();
});
};
const startEffect = (eff: any) => {
return typeof eff.start === 'function' ? eff.start() : eff;
};
const toArray = (someVal: any): any[] => {
if (!someVal) {
return [];
}
if (Array.isArray(someVal)) {
return someVal;
}
return [someVal];
};
const effectsIn = toArray(params.effects);
if (params.external) {
if (effectsIn.length !== 0) {
throw new Error('Effects cannot be used with external output');
}
return Promise.resolve();
}
// effects = params.effects.map(createEffect).map(startEffect);
return Promise.all(effectsIn.map(createEffect))
.then(results => results.map(startEffect))
.then(effects => {
this.instrument.chain(...effects).toDestination();
});
}
get clips(): any[] {
return this.channelClips;
}
get activeClipIdx(): number {
return this.activePatternIdx;
}
} | the_stack |
import { mountWithElement, waitImmediate } from '../util'
import { ref } from 'vue'
// TODO: wait for fix https://github.com/vuejs/vue-test-utils-next/pull/84
describe('Input', () => {
it('create', async () => {
let inputFocus = false
const val = ref('val')
const wrapper = mountWithElement({
template: `
<el-input
:minlength="3"
:maxlength="5"
placeholder="请输入内容"
@focus="handleFocus"
v-model="val">
</el-input>
`,
setup() {
const handleFocus = () => {
inputFocus = true
}
return { val, handleFocus }
},
})
let input = wrapper.find<HTMLInputElement>('input')
input.element.focus()
expect(inputFocus).toEqual(true)
expect(input.attributes('placeholder')).toEqual('请输入内容')
expect(input.element.value).toEqual('val')
expect(input.attributes('minlength')).toEqual('3')
expect(input.attributes('maxlength')).toEqual('5')
val.value = 'text'
await waitImmediate()
expect(input.element.value).toEqual('text')
})
it('default to empty', () => {
const wrapper = mountWithElement({
template: '<el-input/>',
})
let input = wrapper.find<HTMLInputElement>('input')
expect(input.element.value).toEqual('')
})
it('disabled', () => {
const wrapper = mountWithElement({
template: `
<el-input disabled>
</el-input>
`,
})
expect(wrapper.find('input').attributes('disabled')).toBeDefined()
})
it('suffixIcon', () => {
const wrapper = mountWithElement({
template: `
<el-input suffix-icon="time"></el-input>
`,
})
const icon = wrapper.find('.el-input__icon')
expect(icon.exists()).toBe(true)
})
it('prefixIcon', () => {
const wrapper = mountWithElement({
template: `
<el-input prefix-icon="time"></el-input>
`,
})
const icon = wrapper.find('.el-input__icon')
expect(icon.exists()).toBe(true)
})
it('size', () => {
const wrapper = mountWithElement({
template: `
<el-input size="large">
</el-input>
`,
})
expect(wrapper.classes('el-input--large')).toEqual(true)
})
it('type', () => {
const wrapper = mountWithElement({
template: `
<el-input type="textarea">
</el-input>
`,
})
expect(wrapper.classes('el-textarea')).toEqual(true)
})
it('rows', () => {
const wrapper = mountWithElement({
template: `
<el-input type="textarea" :rows="3">
</el-input>
`,
})
expect(wrapper.find('.el-textarea__inner').attributes('rows')).toEqual('3')
})
// Github issue #2836
it('resize', async () => {
const resize = ref('none')
const wrapper = mountWithElement({
template: `
<div>
<el-input type="textarea" :resize="resize"></el-input>
</div>
`,
setup() {
return { resize }
},
})
const elInner = wrapper.find<HTMLElement>('.el-textarea__inner').element
expect(elInner.style.resize).toEqual(resize.value)
resize.value = 'horizontal'
await waitImmediate()
expect(elInner.style.resize).toEqual(resize.value)
})
it('autosize', async () => {
let longText =
'sda\ndasd\nddasdsda\ndasd\nddasdsda\ndasd\nddasdsda\ndasd\nddasd'
const textareaValue = ref(longText)
// jsdom doesn't do any actual rendering
// maybe karma should be used
// see: https://stackoverflow.com/questions/47823616/mocking-clientheight-and-scrollheight-in-react-enzyme-for-test?r=SearchResults
jest
.spyOn(Element.prototype, 'scrollHeight', 'get')
.mockImplementation(function (this) {
if (this.value === '') {
return 31
} else if (this.value === longText) {
return 196
} else {
return 0
}
})
const getComputedStyle = window.getComputedStyle
jest
.spyOn(window as any, 'getComputedStyle')
.mockImplementation((ele: HTMLTextAreaElement) => {
if (ele) {
ele.style.paddingBottom = '5px'
ele.style.paddingTop = '5px'
ele.style.boxSizing = 'border-box'
return getComputedStyle(ele)
}
})
const wrapper = mountWithElement({
template: `
<div>
<el-input
ref="limitSize"
type="textarea"
:autosize="{
minRows: 3,
maxRows: 5,
}"
v-model="textareaValue"
>
</el-input>
<el-input
ref="limitlessSize"
type="textarea"
autosize
v-model="textareaValue"
>
</el-input>
</div>
`,
setup() {
return { textareaValue }
},
})
await waitImmediate()
const limitSizeInput = wrapper.findComponent({ ref: 'limitSize' }).vm as any
const limitlessSizeInput = wrapper.findComponent({ ref: 'limitlessSize' })
.vm as any
await waitImmediate()
expect(limitSizeInput.textareaStyle.height).toEqual('117px')
expect(limitlessSizeInput.textareaStyle.height).toEqual('198px')
textareaValue.value = ''
await waitImmediate()
expect(limitSizeInput.textareaStyle.height).toEqual('75px')
expect(limitlessSizeInput.textareaStyle.height).toEqual('33px')
})
it('focus', async () => {
const mockFn = jest.fn()
const wrapper = mountWithElement({
template: `
<el-input @focus="mockFn">
</el-input>
`,
setup() {
return {
mockFn,
}
},
})
wrapper.find('input').element.focus()
expect(mockFn).toBeCalledTimes(1)
})
// TODO: need other component
// it("Input contains Select and append slot", async () => {
// const input = ref(null);
// const el = createVue({
// template: `
// <el-input v-model="value" clearable class="input-with-select" ref="input">
// <el-select v-model="select" slot="prepend" placeholder="请选择">
// <el-option label="餐厅名" value="1"></el-option>
// <el-option label="订单号" value="2"></el-option>
// <el-option label="用户电话" value="3"></el-option>
// </el-select>
// <el-button slot="append" icon="el-icon-search"></el-button>
// </el-input>
// `,
// setup() {
// const value = ref("1234");
// const select = ref("1");
// return {
// input,
// value,
// select,
// };
// },
// });
// input.value.hovering = true;
// await waitImmediate();
// const suffixEl: HTMLElement = el.querySelector(
// ".input-with-select > .el-input__suffix"
// );
// expect(suffixEl).toBeDefined();
// expect(suffixEl.style.transform).toBeTruthy();
// });
// it('validateEvent', async() => {
// const spy = sinon.spy();
// vm = createVue({
// template: `
// <el-form :model="model" :rules="rules">
// <el-form-item prop="input">
// <el-input v-model="model.input" :validate-event="false">
// </el-input>
// </el-form-item>
// </el-form>
// `,
// data() {
// const validator = (rule, value, callback) => {
// spy();
// callback();
// };
// return {
// model: {
// input: ''
// },
// rules: {
// input: [
// { validator }
// ]
// }
// };
// }
// }, true);
// vm.model.input = '123';
// await waitImmediate();
// expect(spy.called).to.be.false;
// });
describe('Input Events', () => {
it('event:focus & blur', async () => {
const mockFocus = jest.fn()
const mockBlur = jest.fn()
const wrapper = mountWithElement({
template: `
<el-input
placeholder="请输入内容"
modelValue="input"
@focus="mockFocus"
@blur="mockBlur">
</el-input>
`,
setup() {
return {
mockFocus,
mockBlur,
}
},
})
wrapper.find('input').element.focus()
wrapper.find('input').element.blur()
await waitImmediate()
expect(mockFocus).toBeCalledTimes(1)
expect(mockBlur).toBeCalledTimes(1)
})
it('event:change', async () => {
// NOTE: should be same as native's change behavior
const mockChange = jest.fn()
const wrapper = mountWithElement({
template: `
<el-input
placeholder="请输入内容"
v-model="value"
@change="mockChange">
</el-input>
`,
data() {
const value = ref('')
return {
value,
mockChange,
}
},
})
const inputElm = wrapper.find('input').element
const simulateEvent = (text, event) => {
inputElm.value = text
inputElm.dispatchEvent(new Event(event))
}
// simplified test, component should emit change when native does
simulateEvent('1', 'input')
simulateEvent('2', 'change')
await waitImmediate()
expect(mockChange).toBeCalledTimes(1)
expect(mockChange).toBeCalledWith('2')
})
it('event:clear', async () => {
const wrapper = mountWithElement({
template: `
<el-input
placeholder="请输入内容"
clearable
v-model="value">
</el-input>
`,
setup() {
const value = ref('a')
return {
value,
}
},
})
// focus to show clear button
wrapper.find('input').element.focus()
await waitImmediate()
await wrapper.find('.el-input__clear').trigger('click')
expect(
wrapper.findComponent({ name: 'ElInput' }).emitted()
).toHaveProperty('clear')
})
// it('event:input', async () => {
// const mockInput = jest.fn()
// const value = ref('a')
// const el = createVue({
// template: `
// <el-input
// placeholder="请输入内容"
// clearable
// v-model="value"
// @input="mockInput">
// </el-input>
// `,
// setup() {
// return {
// value,
// mockInput,
// }
// },
// })
// const nativeInput = el.querySelector('input')
// nativeInput.value = '1'
// triggerEvent(nativeInput, 'compositionstart')
// triggerEvent(nativeInput, 'input')
// await waitImmediate()
// nativeInput.value = '2'
// triggerEvent(nativeInput, 'compositionupdate')
// triggerEvent(nativeInput, 'input')
// await waitImmediate()
// triggerEvent(nativeInput, 'compositionend')
// await waitImmediate()
// // input event does not fire during composition
// expect(mockInput).toBeCalledTimes(1)
// // TODO: to know for what
// // native input value is controlled
// // expect(value.value).toEqual('a')
// // expect(nativeInput.value).toEqual('a')
// })
// })
// describe('Input Methods', () => {
// it('method:select', async () => {
// const testContent = 'test'
// const inputComp = ref(null)
// const el = createVue({
// template: `
// <el-input
// ref="inputComp"
// v-model="value"
// />
// `,
// setup() {
// const value = ref(testContent)
// return {
// value,
// inputComp,
// }
// },
// })
// await waitImmediate()
// let input = el.querySelector('input')
// expect(input.selectionStart).toEqual(testContent.length)
// expect(input.selectionEnd).toEqual(testContent.length)
// inputComp.value.select()
// await waitImmediate()
// expect(input.selectionStart).toEqual(0)
// expect(input.selectionEnd).toEqual(testContent.length)
// })
// })
// it('sets value on textarea / input type change', async () => {
// const type = ref('text')
// const val = ref('123')
// const el = createVue({
// template: `
// <el-input :type="type" v-model="val" />
// `,
// setup() {
// return {
// type,
// val,
// }
// },
// })
// expect(el.querySelector('input').value).toEqual('123')
// type.value = 'textarea'
// await waitImmediate()
// expect(el.querySelector('textarea').value).toEqual('123')
// type.value = 'password'
// await waitImmediate()
// expect(el.querySelector('input').value).toEqual('123')
// })
// it('limit input and show word count', async () => {
// const show = ref(false)
// const value4 = ref('exceed')
// const inputText = ref(null)
// const inputTextarea = ref(null)
// const inputPassword = ref(null)
// const inputInitialExceed = ref(null)
// createVue({
// template: `
// <div>
// <el-input
// ref="inputText"
// type="text"
// v-model="value1"
// maxlength="10"
// :show-word-limit="show">
// </el-input>
// <el-input
// ref="inputTextarea"
// type="textarea"
// v-model="value2"
// maxlength="10"
// show-word-limit>
// </el-input>
// <el-input
// ref="inputPassword"
// type="password"
// v-model="value3"
// maxlength="10"
// show-word-limit>
// </el-input>
// <el-input
// ref="inputInitialExceed"
// type="text"
// v-model="value4"
// maxlength="2"
// show-word-limit>
// </el-input>
// </div>
// `,
// setup() {
// return {
// value1: '',
// value2: '',
// value3: '',
// value4,
// show,
// inputText,
// inputTextarea,
// inputPassword,
// inputInitialExceed,
// }
// },
// })
// await waitImmediate()
// const elText = inputText.value.$el
// const elTextarea = inputTextarea.value.$el
// const elPassword = inputPassword.value.$el
// const InitialExceed = inputInitialExceed.value.$el
// expect(elText.querySelectorAll('.el-input__count').length).toEqual(0)
// expect(elTextarea.querySelectorAll('.el-input__count').length).toEqual(1)
// expect(elPassword.querySelectorAll('.el-input__count').length).toEqual(0)
// expect(InitialExceed.classList.contains('is-exceed')).toEqual(true)
// show.value = true
// await waitImmediate()
// expect(elText.querySelectorAll('.el-input__count').length).toEqual(1)
// value4.value = '1'
// await waitImmediate()
// expect(elText.classList.contains('is-exceed')).toEqual(false)
})
}) | the_stack |
import _ from 'lodash';
import React, { ReactNode } from 'react';
import { Route } from 'react-router-dom';
import { RiBookLine, RiFlagLine, RiSettingsLine, RiGroupLine, RiStackLine, RiCodeSSlashLine } from 'react-icons/ri';
import { IRouteItem } from '@leaa/dashboard/src/interfaces';
import { ALLOW_PERMISSION } from '@leaa/dashboard/src/constants';
import { isDebugMode } from '@leaa/dashboard/src/utils/debug.util';
import { lazy } from './_lazy';
// TIPS: permission: 'ALLOW_PERMISSION' will be always display
export const UUID_REGX = '[\\w]{8}-[\\w]{4}-[\\w]{4}-[\\w]{4}-[\\w]{12}';
export const masterRouteList: IRouteItem[] = [
// ---- Home ----
//
{
name: 'Home',
namei18n: '_route:home',
permission: ALLOW_PERMISSION,
path: '/',
LazyComponent: lazy(() => import(/* webpackChunkName: 'Home' */ '../pages/Home/Home/Home')),
exact: true,
},
//
// -------- [Content Group] --------
//
{
name: 'Content Group',
namei18n: '_route:contentGroup',
permission: 'article.list-read | tag.list-read',
path: '_content-group',
icon: <RiBookLine />,
children: [
// ---- Article ----
{
name: 'Create Article',
namei18n: '_route:createArticle',
permission: 'article.item-create',
path: '/articles/create',
LazyComponent: lazy(() =>
import(/* webpackChunkName: 'ArticleCreate' */ '../pages/Article/ArticleCreate/ArticleCreate'),
),
exact: true,
isCreate: true,
},
{
name: 'Edit Article',
namei18n: '_route:editArticle',
permission: 'article.item-read',
path: `/articles/:id(${UUID_REGX})`,
LazyComponent: lazy(() =>
import(/* webpackChunkName: 'ArticleEdit' */ '../pages/Article/ArticleEdit/ArticleEdit'),
),
exact: true,
},
{
name: 'Article',
namei18n: '_route:article',
permission: 'article.list-read',
path: '/articles',
LazyComponent: lazy(() =>
import(/* webpackChunkName: 'ArticleList' */ '../pages/Article/ArticleList/ArticleList'),
),
canCreate: true,
exact: true,
},
// ---- Tag ----
{
name: 'Create Tag',
namei18n: '_route:createTag',
permission: 'tag.item-create',
path: '/tags/create',
LazyComponent: lazy(() => import(/* webpackChunkName: 'TagCreate' */ '../pages/Tag/TagCreate/TagCreate')),
exact: true,
isCreate: true,
},
{
name: 'Edit Tag',
namei18n: '_route:editTag',
permission: 'tag.item-read',
path: `/tags/:id(${UUID_REGX})`,
LazyComponent: lazy(() => import(/* webpackChunkName: 'TagEdit' */ '../pages/Tag/TagEdit/TagEdit')),
exact: true,
},
{
name: 'Tag',
namei18n: '_route:tag',
permission: 'tag.list-read',
path: '/tags',
LazyComponent: lazy(() => import(/* webpackChunkName: 'TagList' */ '../pages/Tag/TagList/TagList')),
canCreate: true,
exact: true,
},
//
// ---- Category ----
//
{
name: 'Create Category',
namei18n: '_route:createCategory',
permission: 'category.item-create',
path: '/categories/create',
LazyComponent: lazy(() =>
import(/* webpackChunkName: 'CategoryCreate' */ '../pages/Category/CategoryCreate/CategoryCreate'),
),
exact: true,
isCreate: true,
},
{
name: 'Edit Category',
namei18n: '_route:editCategory',
permission: 'category.item-read',
path: `/categories/:id(${UUID_REGX})`,
LazyComponent: lazy(() =>
import(/* webpackChunkName: 'CategoryEdit' */ '../pages/Category/CategoryEdit/CategoryEdit'),
),
exact: true,
},
{
name: 'Category',
namei18n: '_route:category',
permission: 'category.list-read',
path: '/categories',
LazyComponent: lazy(() =>
import(/* webpackChunkName: 'CategoryList' */ '../pages/Category/CategoryList/CategoryList'),
),
canCreate: true,
exact: true,
},
],
},
//
// -------- [Marketing Group] --------
//
{
name: 'Marketing Group',
namei18n: '_route:marketingGroup',
permission: 'coupon.list-read | ax.list-read | promo.list-read',
path: '_marketing-group',
icon: <RiFlagLine />,
children: [
// ---- Ax ----
{
name: 'Create Ax',
namei18n: '_route:createAx',
permission: 'ax.item-create',
path: '/axs/create',
LazyComponent: lazy(() => import(/* webpackChunkName: 'AxCreate' */ '../pages/Ax/AxCreate/AxCreate')),
exact: true,
isCreate: true,
},
{
name: 'Edit Ax',
namei18n: '_route:editAx',
permission: 'ax.item-read',
path: `/axs/:id(${UUID_REGX})`,
LazyComponent: lazy(() => import(/* webpackChunkName: 'AxEdit' */ '../pages/Ax/AxEdit/AxEdit')),
exact: true,
},
{
name: 'Ax',
namei18n: '_route:ax',
permission: 'ax.list-read',
path: '/axs',
LazyComponent: lazy(() => import(/* webpackChunkName: 'AxList' */ '../pages/Ax/AxList/AxList')),
canCreate: true,
exact: true,
},
],
},
// -------- [User Group] --------
{
name: 'User Group',
namei18n: '_route:userGroup',
permission: 'user.list-read | role.list-read | permission.list-read',
path: '_user-group',
icon: <RiGroupLine />,
children: [
// ---- User ----
{
name: 'Create User',
namei18n: '_route:createUser',
permission: 'user.item-create',
path: '/users/create',
LazyComponent: lazy(() => import(/* webpackChunkName: 'UserCreate' */ '../pages/User/UserCreate/UserCreate')),
exact: true,
isCreate: true,
},
{
name: 'Edit User',
namei18n: '_route:editUser',
permission: 'user.item-read',
path: `/users/:id(${UUID_REGX})`,
LazyComponent: lazy(() => import(/* webpackChunkName: 'UserEdit' */ '../pages/User/UserEdit/UserEdit')),
exact: true,
},
{
name: 'User',
namei18n: '_route:user',
permission: 'user.list-read',
path: '/users',
LazyComponent: lazy(() => import(/* webpackChunkName: 'UserList' */ '../pages/User/UserList/UserList')),
canCreate: true,
exact: true,
},
// ---- Role ----
{
name: 'Create Role',
namei18n: '_route:createRole',
permission: 'role.item-create',
path: '/roles/create',
LazyComponent: lazy(() => import(/* webpackChunkName: 'RoleCreate' */ '../pages/Role/RoleCreate/RoleCreate')),
exact: true,
isCreate: true,
},
{
name: 'Edit Role',
namei18n: '_route:editRole',
permission: 'role.item-read',
path: `/roles/:id(${UUID_REGX})`,
LazyComponent: lazy(() => import(/* webpackChunkName: 'RoleEdit' */ '../pages/Role/RoleEdit/RoleEdit')),
exact: true,
},
{
name: 'Role',
namei18n: '_route:role',
permission: 'role.list-read',
path: '/roles',
LazyComponent: lazy(() => import(/* webpackChunkName: 'RoleList' */ '../pages/Role/RoleList/RoleList')),
canCreate: true,
exact: true,
},
// ---- Permission ----
{
name: 'Create Permission',
namei18n: '_route:createPermission',
permission: 'permission.item-create',
path: '/permissions/create',
LazyComponent: lazy(() =>
import(/* webpackChunkName: 'PermissionCreate' */ '../pages/Permission/PermissionCreate/PermissionCreate'),
),
exact: true,
isCreate: true,
},
{
name: 'Edit Permission',
namei18n: '_route:editPermission',
permission: 'permission.item-read',
path: `/permissions/:id(${UUID_REGX})`,
LazyComponent: lazy(() =>
import(/* webpackChunkName: 'PermissionEdit' */ '../pages/Permission/PermissionEdit/PermissionEdit'),
),
exact: true,
},
{
name: 'Permission',
namei18n: '_route:permission',
permission: 'permission.list-read',
path: '/permissions',
LazyComponent: lazy(() =>
import(/* webpackChunkName: 'PermissionList' */ '../pages/Permission/PermissionList/PermissionList'),
),
canCreate: true,
exact: true,
},
],
},
//
// -------- [Data Group] --------
//
{
name: 'Data Group',
namei18n: '_route:dataGroup',
permission: 'address.list-read',
path: '_data-group',
icon: <RiStackLine />,
children: [
// ---- Oauth ----
{
name: 'Oauth',
namei18n: '_route:oauth',
permission: 'oauth.list-read',
path: '/oauths',
LazyComponent: lazy(() => import(/* webpackChunkName: 'OauthList' */ '../pages/Oauth/OauthList/OauthList')),
canCreate: false,
exact: true,
},
// ---- Action ----
{
name: 'Action',
namei18n: '_route:action',
permission: 'action.list-read',
path: '/actions',
LazyComponent: lazy(() => import(/* webpackChunkName: 'ActionList' */ '../pages/Action/ActionList/ActionList')),
// canCreate: true,
exact: true,
},
{
name: 'Edit Action',
namei18n: '_route:editAction',
permission: 'action.item-read',
path: '/actions/:id(\\d+)',
LazyComponent: lazy(() => import(/* webpackChunkName: 'ActionEdit' */ '../pages/Action/ActionEdit/ActionEdit')),
exact: true,
},
// ---- Attachment ----
{
name: 'Attachment',
namei18n: '_route:attachment',
permission: 'attachment.list-read',
path: '/attachments',
LazyComponent: lazy(() =>
import(/* webpackChunkName: 'AttachmentList' */ '../pages/Attachment/AttachmentList/AttachmentList'),
),
canCreate: true,
exact: true,
},
{
name: 'Create Attachment',
namei18n: '_route:createAttachment',
permission: 'attachment.item-create',
path: '/attachments/create',
LazyComponent: lazy(() =>
import(/* webpackChunkName: 'AttachmentCreate' */ '../pages/Attachment/AttachmentCreate/AttachmentCreate'),
),
exact: true,
isCreate: true,
},
{
name: 'Edit Attachment',
namei18n: '_route:editAttachment',
permission: 'attachment.item-read',
path: `/attachments/:id(${UUID_REGX})`,
LazyComponent: lazy(() =>
import(/* webpackChunkName: 'AttachmentEdit' */ '../pages/Attachment/AttachmentEdit/AttachmentEdit'),
),
exact: true,
},
],
},
//
// ---- Setting ----
//
{
name: 'Setting',
namei18n: '_route:setting',
permission: 'setting.list-read',
path: '/settings',
icon: <RiSettingsLine />,
LazyComponent: lazy(() => import(/* webpackChunkName: 'SettingList' */ '../pages/Setting/SettingList/SettingList')),
exact: true,
},
];
if (isDebugMode()) {
masterRouteList.push(
//
// -------- [Debug Group] --------
//
{
name: 'Debug Group',
namei18n: '_route:debug',
permission: 'lab.root',
path: '_debug-group',
icon: <RiCodeSSlashLine />,
children: [
{
name: 'Test Any',
namei18n: '_route:testAny',
permission: ALLOW_PERMISSION,
path: '/test-any',
LazyComponent: lazy(() => import(/* webpackChunkName: 'TestAny' */ '../pages/Test/TestAny/TestAny')),
exact: true,
},
{
name: 'Test Attachment',
namei18n: '_route:testAttachment',
permission: ALLOW_PERMISSION,
path: '/test-attachment',
LazyComponent: lazy(() =>
import(/* webpackChunkName: 'TestAttachment' */ '../pages/Test/TestAttachment/TestAttachment'),
),
exact: true,
},
{
name: 'Test I18n',
namei18n: '_route:testI18n',
permission: ALLOW_PERMISSION,
path: '/test-i18n',
LazyComponent: lazy(() => import(/* webpackChunkName: 'TestI18n' */ '../pages/Test/TestI18n/TestI18n')),
exact: true,
},
],
},
);
}
const routerDom: ReactNode[] = [];
const parseRoutes = (routeList: IRouteItem[]) => {
routeList.forEach((route) => {
if (route.children) {
parseRoutes(route.children);
}
routerDom.push(
<Route
{...route}
key={route.children ? `group-${route.name}` : route?.path}
// eslint-disable-next-line react/no-children-prop
children={(props) => <route.LazyComponent {...props} route={route} />}
/>,
);
});
return routerDom;
};
const flateRoutes: IRouteItem[] = [];
const parseFlatRoutes = (routeList: IRouteItem[], groupName?: string) => {
routeList.forEach((item) => {
const nextItem = _.omit(item, 'LazyComponent');
if (nextItem.children) parseFlatRoutes(nextItem.children, nextItem.path);
// loop for children groupName
if (groupName) nextItem.groupName = groupName;
flateRoutes.push(nextItem);
});
return flateRoutes;
};
export const masterRoute = parseRoutes(masterRouteList);
export const flateMasterRoutes: IRouteItem[] = parseFlatRoutes(masterRouteList); | the_stack |
namespace pxt.usb {
export class USBError extends Error {
constructor(msg: string) {
super(msg)
this.message = msg
}
}
// http://www.linux-usb.org/usb.ids
export const enum VID {
ATMEL = 0x03EB,
ARDUINO = 0x2341,
ADAFRUIT = 0x239A,
NXP = 0x0d28, // aka Freescale, KL26 etc
}
const controlTransferGetReport = 0x01;
const controlTransferSetReport = 0x09;
const controlTransferOutReport = 0x200;
const controlTransferInReport = 0x100;
export interface USBDeviceFilter {
vendorId?: number;
productId?: number;
classCode?: number;
subclassCode?: number;
protocolCode?: number;
serialNumber?: string;
}
// this is for HF2
export let filters: USBDeviceFilter[] = [{
classCode: 255,
subclassCode: 42,
}
]
let isHF2 = true
export function setFilters(f: USBDeviceFilter[]) {
isHF2 = false
filters = f
}
export type USBEndpointType = "bulk" | "interrupt" | "isochronous";
export type USBRequestType = "standard" | "class" | "vendor"
export type USBRecipient = "device" | "interface" | "endpoint" | "other"
export type USBTransferStatus = "ok" | "stall" | "babble";
export type USBDirection = "in" | "out";
export type BufferSource = Uint8Array;
export interface USBConfiguration {
configurationValue: number;
configurationName: string;
interfaces: USBInterface[];
};
export interface USBInterface {
interfaceNumber: number;
alternate: USBAlternateInterface;
alternates: USBAlternateInterface[];
claimed: boolean;
};
export interface USBAlternateInterface {
alternateSetting: number;
interfaceClass: number;
interfaceSubclass: number;
interfaceProtocol: number;
interfaceName: string;
endpoints: USBEndpoint[];
};
export interface USBEndpoint {
endpointNumber: number;
direction: USBDirection;
type: USBEndpointType;
packetSize: number;
}
export interface USBControlTransferParameters {
requestType: USBRequestType;
recipient: USBRecipient;
request: number;
value: number;
index: number;
}
export interface USBInTransferResult {
data: { buffer: ArrayBuffer; };
status: USBTransferStatus;
}
export interface USBOutTransferResult {
bytesWritten: number;
status: USBTransferStatus;
}
export interface USBIsochronousInTransferPacket {
data: DataView;
status: USBTransferStatus;
}
export interface USBIsochronousInTransferResult {
data: DataView;
packets: USBIsochronousInTransferPacket[];
}
export interface USBIsochronousOutTransferPacket {
bytesWritten: number;
status: USBTransferStatus;
}
export interface USBIsochronousOutTransferResult {
packets: USBIsochronousOutTransferPacket[];
}
export interface USBDevice {
vendorId: number; // VID.*
productId: number; // 589
manufacturerName: string; // "Arduino"
productName: string; // "Arduino Zero"
serialNumber: string; // ""
deviceClass: number; // 0xEF - misc
deviceSubclass: number; // 2
deviceProtocol: number; // 1
deviceVersionMajor: number; // 0x42
deviceVersionMinor: number; // 0x00
deviceVersionSubminor: number; // 0x01
usbVersionMajor: number; // 2
usbVersionMinor: number; // 1
usbVersionSubminor: number; // 0
configurations: USBConfiguration[];
opened: boolean;
open(): Promise<void>;
close(): Promise<void>;
selectConfiguration(configurationValue: number): Promise<void>;
claimInterface(interfaceNumber: number): Promise<void>;
releaseInterface(interfaceNumber: number): Promise<void>;
selectAlternateInterface(interfaceNumber: number, alternateSetting: number): Promise<void>;
controlTransferIn(setup: USBControlTransferParameters, length: number): Promise<USBInTransferResult>;
controlTransferOut(setup: USBControlTransferParameters, data?: BufferSource): Promise<USBOutTransferResult>;
clearHalt(direction: USBDirection, endpointNumber: number): Promise<void>;
transferIn(endpointNumber: number, length: number): Promise<USBInTransferResult>;
transferOut(endpointNumber: number, data: BufferSource): Promise<USBOutTransferResult>;
isochronousTransferIn(endpointNumber: number, packetLengths: number[]): Promise<USBIsochronousInTransferResult>;
isochronousTransferOut(endpointNumber: number, data: BufferSource, packetLengths: number[]): Promise<USBIsochronousOutTransferResult>;
reset(): Promise<void>;
}
class WebUSBHID implements pxt.packetio.PacketIO {
lastKnownDeviceSerialNumber: string;
dev: USBDevice;
ready = false;
connecting = false;
iface: USBInterface;
altIface: USBAlternateInterface;
epIn: USBEndpoint;
epOut: USBEndpoint;
readLoopStarted = false;
onDeviceConnectionChanged = (connect: boolean) => { };
onConnectionChanged = () => { };
onData = (v: Uint8Array) => { };
onError = (e: Error) => { };
onEvent = (v: Uint8Array) => { };
enabled = false;
constructor() {
this.handleUSBConnected = this.handleUSBConnected.bind(this);
this.handleUSBDisconnected = this.handleUSBDisconnected.bind(this);
}
enable(): void {
if (this.enabled) return;
this.enabled = true;
this.log("registering webusb events");
(navigator as any).usb.addEventListener('disconnect', this.handleUSBDisconnected, false);
(navigator as any).usb.addEventListener('connect', this.handleUSBConnected, false);
}
disable() {
if (!this.enabled) return;
this.enabled = false;
this.log(`unregistering webusb events`);
(navigator as any).usb.removeEventListener('disconnect', this.handleUSBDisconnected);
(navigator as any).usb.removeEventListener('connect', this.handleUSBConnected);
}
disposeAsync(): Promise<void> {
this.disable();
return Promise.resolve();
}
private handleUSBDisconnected(event: any) {
this.log("device disconnected")
if (event.device == this.dev) {
this.log("clear device")
this.clearDev();
if (this.onDeviceConnectionChanged)
this.onDeviceConnectionChanged(false);
}
}
private handleUSBConnected(event: any) {
const newdev = event.device as USBDevice;
this.log(`device connected ${newdev.serialNumber}`)
if (!this.dev && !this.connecting) {
this.log("attach device")
if (this.onDeviceConnectionChanged)
this.onDeviceConnectionChanged(true);
}
}
private clearDev() {
if (this.dev) {
this.dev = null
this.epIn = null
this.epOut = null
if (this.onConnectionChanged)
this.onConnectionChanged();
}
}
error(msg: string) {
throw new USBError(U.lf("USB error on device {0} ({1})", this.dev.productName, msg))
}
log(msg: string) {
pxt.debug("webusb: " + msg)
}
disconnectAsync() {
this.ready = false
if (!this.dev) return Promise.resolve()
this.log("close device")
return this.dev.close()
.catch(e => {
// just ignore errors closing, most likely device just disconnected
})
.then(() => {
this.clearDev()
return U.delay(500)
})
}
reconnectAsync() {
this.log("reconnect")
this.setConnecting(true);
return this.disconnectAsync()
.then(tryGetDevicesAsync)
.then(devs => this.connectAsync(devs))
.finally(() => this.setConnecting(false));
}
private setConnecting(v: boolean) {
if (v != this.connecting) {
this.connecting = v;
if (this.onConnectionChanged)
this.onConnectionChanged();
}
}
isConnecting(): boolean {
return this.connecting;
}
isConnected(): boolean {
return !!this.dev && this.ready;
}
private async connectAsync(devs: USBDevice[]) {
this.log(`trying to connect (${devs.length} devices)`)
// no devices...
if (devs.length == 0) {
const e = new Error("Device not found.");
(e as any).type = "devicenotfound";
throw e;
}
this.setConnecting(true);
try {
// move last known device in front
// if we have a race with another tab when reconnecting, wait a bit if device unknown
if (this.lastKnownDeviceSerialNumber) {
const lastDev = devs.find(d => d.serialNumber === this.lastKnownDeviceSerialNumber);
if (lastDev) {
this.log(`last known device spotted`);
devs.splice(devs.indexOf(lastDev), 1);
devs.unshift(lastDev);
} else {
// give another frame a chance to grab the device
this.log(`delay for last known device`)
await U.delay(2000);
}
}
// try to connect to one of the devices
for (let i = 0; i < devs.length; ++i) {
const dev = devs[i];
this.dev = dev;
this.log(`connect device: ${dev.manufacturerName} ${dev.productName}`)
this.log(`serial number: ${dev.serialNumber} ${this.lastKnownDeviceSerialNumber === dev.serialNumber ? "(last known device)" : ""} `);
try {
await this.initAsync();
// success, stop trying
return;
} catch (e) {
this.dev = undefined; // clean state
this.log(`connection failed, ${e.message}`);
// try next
}
}
// failed to connect, all devices are locked or broken
const e = new Error(U.lf("Device in use or not found."));
(e as any).type = "devicelocked";
throw e;
} finally {
this.setConnecting(false);
}
}
sendPacketAsync(pkt: Uint8Array) {
if (!this.dev)
return Promise.reject(new Error("Disconnected"))
Util.assert(pkt.length <= 64)
if (!this.epOut) {
return this.dev.controlTransferOut({
requestType: "class",
recipient: "interface",
request: controlTransferSetReport,
value: controlTransferOutReport,
index: this.iface.interfaceNumber
}, pkt).then(res => {
if (res.status != "ok")
this.error("USB CTRL OUT transfer failed")
})
}
return this.dev.transferOut(this.epOut.endpointNumber, pkt)
.then(res => {
if (res.status != "ok")
this.error("USB OUT transfer failed")
})
}
private readLoop() {
if (this.readLoopStarted)
return
this.readLoopStarted = true
this.log("start read loop")
let loop = (): void => {
if (!this.ready)
U.delay(300).then(loop)
else
this.recvPacketAsync()
.then(buf => {
if (buf[0]) {
// we've got data; retry reading immedietly after processing it
this.onData(buf)
loop()
} else {
// throttle down if no data coming
U.delay(500).then(loop)
}
}, err => {
if (this.dev)
this.onError(err)
U.delay(300).then(loop)
})
}
loop()
}
recvPacketAsync(): Promise<Uint8Array> {
let final = (res: USBInTransferResult) => {
if (res.status != "ok")
this.error("USB IN transfer failed")
let arr = new Uint8Array(res.data.buffer)
if (arr.length == 0)
return this.recvPacketAsync()
return arr
}
if (!this.dev)
return Promise.reject(new Error("Disconnected"))
if (!this.epIn) {
return this.dev.controlTransferIn({
requestType: "class",
recipient: "interface",
request: controlTransferGetReport,
value: controlTransferInReport,
index: this.iface.interfaceNumber
}, 64).then(final)
}
return this.dev.transferIn(this.epIn.endpointNumber, 64)
.then(final)
}
initAsync(): Promise<void> {
if (!this.dev)
return Promise.reject(new Error("Disconnected"))
let dev = this.dev
this.log("open device")
return dev.open()
// assume one configuration; no one really does more
.then(() => {
this.log("select configuration")
return dev.selectConfiguration(1)
})
.then(() => {
let matchesFilters = (iface: USBInterface) => {
let a0 = iface.alternates[0]
for (let f of filters) {
if (f.classCode == null || a0.interfaceClass === f.classCode) {
if (f.subclassCode == null || a0.interfaceSubclass === f.subclassCode) {
if (f.protocolCode == null || a0.interfaceProtocol === f.protocolCode) {
if (a0.endpoints.length == 0)
return true
if (a0.endpoints.length == 2 &&
a0.endpoints.every(e => e.packetSize == 64))
return true
}
}
}
}
return false
}
this.log("got " + dev.configurations[0].interfaces.length + " interfaces")
const matching = dev.configurations[0].interfaces.filter(matchesFilters)
let iface = matching[matching.length - 1]
this.log(`${matching.length} matching interfaces; picking ${iface ? "#" + iface.interfaceNumber : "n/a"}`)
if (!iface)
this.error("cannot find supported USB interface")
this.altIface = iface.alternates[0]
this.iface = iface
if (this.altIface.endpoints.length) {
this.log("using dedicated endpoints")
this.epIn = this.altIface.endpoints.filter(e => e.direction == "in")[0]
this.epOut = this.altIface.endpoints.filter(e => e.direction == "out")[0]
Util.assert(this.epIn.packetSize == 64);
Util.assert(this.epOut.packetSize == 64);
} else {
this.log("using ctrl pipe")
}
this.log("claim interface")
return dev.claimInterface(iface.interfaceNumber)
})
.then(() => {
this.log("device ready")
this.lastKnownDeviceSerialNumber = this.dev.serialNumber;
this.ready = true;
if (isHF2)
this.readLoop();
if (this.onConnectionChanged)
this.onConnectionChanged();
})
}
}
export function pairAsync(): Promise<boolean> {
return ((navigator as any).usb.requestDevice({
filters: filters
}) as Promise<USBDevice>)
.then(dev => !!dev)
.catch(e => {
// user cancelled
if (e.name == "NotFoundError")
return undefined;
throw e;
})
}
async function tryGetDevicesAsync(): Promise<USBDevice[]> {
log(`webusb: get devices`)
try {
const devs = await ((navigator as any).usb.getDevices() as Promise<USBDevice[]>);
return devs || []
}
catch (e) {
reportException(e)
return [];
}
}
let _hid: WebUSBHID;
export function mkWebUSBHIDPacketIOAsync(): Promise<pxt.packetio.PacketIO> {
pxt.debug(`packetio: mk webusb io`)
if (!_hid)
_hid = new WebUSBHID();
_hid.enable();
return Promise.resolve(_hid);
}
export let isEnabled = false
export function setEnabled(v: boolean) {
if (!isAvailable()) v = false
isEnabled = v
}
let _available: boolean = undefined;
export async function checkAvailableAsync() {
if (_available !== undefined) return;
pxt.debug(`webusb: checking availability`)
// not supported by editor, cut short
if (!pxt.appTarget?.compile?.webUSB) {
_available = false;
return;
}
if (pxt.BrowserUtils.isElectron() || pxt.BrowserUtils.isWinRT()) {
pxt.debug(`webusb: off, electron or winrt`)
pxt.tickEvent('webusb.off', { 'reason': 'electronwinrt' })
_available = false;
return;
}
const _usb = (navigator as any).usb;
if (!_usb) {
pxt.debug(`webusb: off, not impl`)
pxt.tickEvent('webusb.off', { 'reason': 'notimpl' })
_available = false
return
}
// Windows versions:
// 5.1 - XP, 6.0 - Vista, 6.1 - Win7, 6.2 - Win8, 6.3 - Win8.1, 10.0 - Win10
// If on Windows, and Windows is older 8.1, don't enable WebUSB,
// as it requires signed INF files.
let m = /Windows NT (\d+\.\d+)/.exec(navigator.userAgent)
if (m && parseFloat(m[1]) < 6.3) {
pxt.debug(`webusb: off, older windows version`)
pxt.tickEvent('webusb.off', { 'reason': 'oldwindows' })
_available = false;
return;
}
// check security
try {
// iframes must specify allow="usb" in order to support WebUSB
await _usb.getDevices()
} catch (e) {
pxt.debug(`webusb: off, security exception`)
pxt.tickEvent('webusb.off', { 'reason': 'security' })
_available = false;
return;
}
// yay!
_available = true;
return
}
export function isAvailable() {
if (_available === undefined) {
console.error(`checkAvailableAsync not called`)
checkAvailableAsync()
}
return !!_available;
}
} | the_stack |
import {inject} from 'aurelia-framework';
@inject(Element)
export class BlurImageCustomAttribute {
element;
constructor(element){
this.element = element;
}
valueChanged(newImage){
if(newImage.complete){
drawBlur(this.element, newImage);
} else{
newImage.onload = () => drawBlur(this.element, newImage);
}
}
}
/*
This Snippet is using a modified Stack Blur js lib for blurring the header images.
*/
/*
StackBlur - a fast almost Gaussian Blur For Canvas
Version: 0.5
Author: Mario Klingemann
Contact: mario@quasimondo.com
Website: http://www.quasimondo.com/StackBlurForCanvas
Twitter: @quasimondo
In case you find this class useful - especially in commercial projects -
I am not totally unhappy for a small donation to my PayPal account
mario@quasimondo.de
Or support me on flattr:
https://flattr.com/thing/72791/StackBlur-a-fast-almost-Gaussian-Blur-Effect-for-CanvasJavascript
Copyright (c) 2010 Mario Klingemann
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
var mul_table = [
512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,
454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,
482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,
437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,
497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,
320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,
446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,
329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,
505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,
399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,
324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,
268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,
451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,
385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,
332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,
289,287,285,282,280,278,275,273,271,269,267,265,263,261,259];
var shg_table = [
9, 11, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 17,
17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19,
19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20,
20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24 ];
var BLUR_RADIUS = 40;
function stackBlurCanvasRGBA( canvas, top_x, top_y, width, height, radius )
{
if ( isNaN(radius) || radius < 1 ) return;
radius |= 0;
var context = canvas.getContext("2d");
var imageData;
try {
imageData = context.getImageData( top_x, top_y, width, height );
} catch(e) {
throw new Error("unable to access image data: " + e);
}
var pixels = imageData.data;
var x, y, i, p, yp, yi, yw, r_sum, g_sum, b_sum, a_sum,
r_out_sum, g_out_sum, b_out_sum, a_out_sum,
r_in_sum, g_in_sum, b_in_sum, a_in_sum,
pr, pg, pb, pa, rbs;
var div = radius + radius + 1;
var w4 = width << 2;
var widthMinus1 = width - 1;
var heightMinus1 = height - 1;
var radiusPlus1 = radius + 1;
var sumFactor = radiusPlus1 * ( radiusPlus1 + 1 ) / 2;
var stackStart = new BlurStack();
var stack = stackStart;
for ( i = 1; i < div; i++ )
{
stack = stack.next = new BlurStack();
if ( i == radiusPlus1 ) var stackEnd = stack;
}
stack.next = stackStart;
var stackIn = null;
var stackOut = null;
yw = yi = 0;
var mul_sum = mul_table[radius];
var shg_sum = shg_table[radius];
for ( y = 0; y < height; y++ )
{
r_in_sum = g_in_sum = b_in_sum = a_in_sum = r_sum = g_sum = b_sum = a_sum = 0;
r_out_sum = radiusPlus1 * ( pr = pixels[yi] );
g_out_sum = radiusPlus1 * ( pg = pixels[yi+1] );
b_out_sum = radiusPlus1 * ( pb = pixels[yi+2] );
a_out_sum = radiusPlus1 * ( pa = pixels[yi+3] );
r_sum += sumFactor * pr;
g_sum += sumFactor * pg;
b_sum += sumFactor * pb;
a_sum += sumFactor * pa;
stack = stackStart;
for( i = 0; i < radiusPlus1; i++ )
{
stack.r = pr;
stack.g = pg;
stack.b = pb;
stack.a = pa;
stack = stack.next;
}
for( i = 1; i < radiusPlus1; i++ )
{
p = yi + (( widthMinus1 < i ? widthMinus1 : i ) << 2 );
r_sum += ( stack.r = ( pr = pixels[p])) * ( rbs = radiusPlus1 - i );
g_sum += ( stack.g = ( pg = pixels[p+1])) * rbs;
b_sum += ( stack.b = ( pb = pixels[p+2])) * rbs;
a_sum += ( stack.a = ( pa = pixels[p+3])) * rbs;
r_in_sum += pr;
g_in_sum += pg;
b_in_sum += pb;
a_in_sum += pa;
stack = stack.next;
}
stackIn = stackStart;
stackOut = stackEnd;
for ( x = 0; x < width; x++ )
{
pixels[yi+3] = pa = (a_sum * mul_sum) >> shg_sum;
if ( pa != 0 )
{
pa = 255 / pa;
pixels[yi] = ((r_sum * mul_sum) >> shg_sum) * pa;
pixels[yi+1] = ((g_sum * mul_sum) >> shg_sum) * pa;
pixels[yi+2] = ((b_sum * mul_sum) >> shg_sum) * pa;
} else {
pixels[yi] = pixels[yi+1] = pixels[yi+2] = 0;
}
r_sum -= r_out_sum;
g_sum -= g_out_sum;
b_sum -= b_out_sum;
a_sum -= a_out_sum;
r_out_sum -= stackIn.r;
g_out_sum -= stackIn.g;
b_out_sum -= stackIn.b;
a_out_sum -= stackIn.a;
p = ( yw + ( ( p = x + radius + 1 ) < widthMinus1 ? p : widthMinus1 ) ) << 2;
r_in_sum += ( stackIn.r = pixels[p]);
g_in_sum += ( stackIn.g = pixels[p+1]);
b_in_sum += ( stackIn.b = pixels[p+2]);
a_in_sum += ( stackIn.a = pixels[p+3]);
r_sum += r_in_sum;
g_sum += g_in_sum;
b_sum += b_in_sum;
a_sum += a_in_sum;
stackIn = stackIn.next;
r_out_sum += ( pr = stackOut.r );
g_out_sum += ( pg = stackOut.g );
b_out_sum += ( pb = stackOut.b );
a_out_sum += ( pa = stackOut.a );
r_in_sum -= pr;
g_in_sum -= pg;
b_in_sum -= pb;
a_in_sum -= pa;
stackOut = stackOut.next;
yi += 4;
}
yw += width;
}
for ( x = 0; x < width; x++ )
{
g_in_sum = b_in_sum = a_in_sum = r_in_sum = g_sum = b_sum = a_sum = r_sum = 0;
yi = x << 2;
r_out_sum = radiusPlus1 * ( pr = pixels[yi]);
g_out_sum = radiusPlus1 * ( pg = pixels[yi+1]);
b_out_sum = radiusPlus1 * ( pb = pixels[yi+2]);
a_out_sum = radiusPlus1 * ( pa = pixels[yi+3]);
r_sum += sumFactor * pr;
g_sum += sumFactor * pg;
b_sum += sumFactor * pb;
a_sum += sumFactor * pa;
stack = stackStart;
for( i = 0; i < radiusPlus1; i++ )
{
stack.r = pr;
stack.g = pg;
stack.b = pb;
stack.a = pa;
stack = stack.next;
}
yp = width;
for( i = 1; i <= radius; i++ )
{
yi = ( yp + x ) << 2;
r_sum += ( stack.r = ( pr = pixels[yi])) * ( rbs = radiusPlus1 - i );
g_sum += ( stack.g = ( pg = pixels[yi+1])) * rbs;
b_sum += ( stack.b = ( pb = pixels[yi+2])) * rbs;
a_sum += ( stack.a = ( pa = pixels[yi+3])) * rbs;
r_in_sum += pr;
g_in_sum += pg;
b_in_sum += pb;
a_in_sum += pa;
stack = stack.next;
if( i < heightMinus1 )
{
yp += width;
}
}
yi = x;
stackIn = stackStart;
stackOut = stackEnd;
for ( y = 0; y < height; y++ )
{
p = yi << 2;
pixels[p+3] = pa = (a_sum * mul_sum) >> shg_sum;
if ( pa > 0 )
{
pa = 255 / pa;
pixels[p] = ((r_sum * mul_sum) >> shg_sum ) * pa;
pixels[p+1] = ((g_sum * mul_sum) >> shg_sum ) * pa;
pixels[p+2] = ((b_sum * mul_sum) >> shg_sum ) * pa;
} else {
pixels[p] = pixels[p+1] = pixels[p+2] = 0;
}
r_sum -= r_out_sum;
g_sum -= g_out_sum;
b_sum -= b_out_sum;
a_sum -= a_out_sum;
r_out_sum -= stackIn.r;
g_out_sum -= stackIn.g;
b_out_sum -= stackIn.b;
a_out_sum -= stackIn.a;
p = ( x + (( ( p = y + radiusPlus1) < heightMinus1 ? p : heightMinus1 ) * width )) << 2;
r_sum += ( r_in_sum += ( stackIn.r = pixels[p]));
g_sum += ( g_in_sum += ( stackIn.g = pixels[p+1]));
b_sum += ( b_in_sum += ( stackIn.b = pixels[p+2]));
a_sum += ( a_in_sum += ( stackIn.a = pixels[p+3]));
stackIn = stackIn.next;
r_out_sum += ( pr = stackOut.r );
g_out_sum += ( pg = stackOut.g );
b_out_sum += ( pb = stackOut.b );
a_out_sum += ( pa = stackOut.a );
r_in_sum -= pr;
g_in_sum -= pg;
b_in_sum -= pb;
a_in_sum -= pa;
stackOut = stackOut.next;
yi += width;
}
}
context.putImageData( imageData, top_x, top_y );
}
function BlurStack()
{
this.r = 0;
this.g = 0;
this.b = 0;
this.a = 0;
this.next = null;
}
function drawBlur(canvas, image) {
var w = canvas.width;
var h = canvas.height;
var canvasContext = canvas.getContext('2d');
canvasContext.drawImage(image, 0, 0, w, h);
stackBlurCanvasRGBA(canvas, 0, 0, w, h, BLUR_RADIUS);
}; | the_stack |
import type { ComponentPublicInstance, PropType } from 'vue';
import {
computed,
defineComponent,
nextTick,
ref,
toRefs,
watch,
watchEffect,
} from 'vue';
import { getPrefixCls } from '../_utils/global-config';
import {
isArray,
isFunction,
isNull,
isNumber,
isObject,
isUndefined,
} from '../_utils/is';
import { getKeyFromValue, isGroupOptionInfo, isValidOption } from './utils';
import Trigger, { TriggerProps } from '../trigger';
import SelectView from '../_components/select-view/select-view';
import { Size } from '../_utils/constant';
import { Data, EmitType } from '../_utils/types';
import SelectDropdown from './select-dropdown.vue';
import Option from './option.vue';
import OptGroup from './optgroup.vue';
import {
SelectOptionData,
SelectOptionInfo,
SelectOptionGroupInfo,
OptionValueWithKey,
SelectFieldNames,
SelectOptionGroup,
} from './interface';
import VirtualList from '../_components/virtual-list/virtual-list.vue';
import { VirtualListProps } from '../_components/virtual-list/interface';
import { useSelect } from './hooks/use-select';
import { TagData } from '../input-tag';
import { useTrigger } from '../_hooks/use-trigger';
import { useFormItem } from '../_hooks/use-form-item';
import { debounce } from '../_utils/debounce';
import { SelectViewValue } from '../_components/select-view/interface';
export default defineComponent({
name: 'Select',
components: {
Trigger,
SelectView,
},
inheritAttrs: false,
props: {
/**
* @zh 是否开启多选模式(多选模式默认开启搜索)
* @en Whether to open multi-select mode (The search is turned on by default in the multi-select mode)
*/
multiple: {
type: Boolean,
default: false,
},
/**
* @zh 绑定值
* @en Value
*/
modelValue: {
type: [String, Number, Object, Array] as PropType<
| string
| number
| Record<string, any>
| (string | number | Record<string, any>)[]
>,
},
/**
* @zh 默认值(非受控模式)
* @en Default value (uncontrolled mode)
* @defaultValue '' \| []
*/
defaultValue: {
type: [String, Number, Object, Array] as PropType<
| string
| number
| Record<string, unknown>
| (string | number | Record<string, unknown>)[]
>,
default: (props: Data) => (isUndefined(props.multiple) ? '' : []),
},
/**
* @zh 输入框的值
* @en The value of the input
* @vModel
*/
inputValue: {
type: String,
},
/**
* @zh 输入框的默认值(非受控模式)
* @en The default value of the input (uncontrolled mode)
*/
defaultInputValue: {
type: String,
default: '',
},
/**
* @zh 选择框的大小
* @en The size of the select
* @values 'mini','small','medium','large'
* @defaultValue 'medium'
*/
size: {
type: String as PropType<Size>,
},
/**
* @zh 占位符
* @en Placeholder
*/
placeholder: String,
/**
* @zh 是否为加载中状态
* @en Whether it is loading state
*/
loading: {
type: Boolean,
default: false,
},
/**
* @zh 是否禁用
* @en Whether to disable
*/
disabled: {
type: Boolean,
default: false,
},
/**
* @zh 是否为错误状态
* @en Whether it is an error state
*/
error: {
type: Boolean,
default: false,
},
/**
* @zh 是否允许清空
* @en Whether to allow clear
*/
allowClear: {
type: Boolean,
default: false,
},
/**
* @zh 是否允许搜索
* @en Whether to allow searching
* @defaultValue false (single) \| true (multiple)
*/
allowSearch: {
type: [Boolean, Object] as PropType<
boolean | { retainInputValue?: boolean }
>,
default: (props: Data) => Boolean(props.multiple),
},
/**
* @zh 是否允许创建
* @en Whether to allow creation
*/
allowCreate: {
type: Boolean,
default: false,
},
/**
* @zh 多选模式下,最多显示的标签数量。0 表示不限制
* @en In multi-select mode, the maximum number of labels displayed. 0 means unlimited
*/
maxTagCount: {
type: Number,
default: 0,
},
/**
* @zh 弹出框的挂载容器
* @en Mount container for popup
*/
popupContainer: {
type: [String, Object] as PropType<string | HTMLElement>,
},
/**
* @zh 是否显示输入框的边框
* @en Whether to display the border of the input box
*/
bordered: {
type: Boolean,
default: true,
},
defaultActiveFirstOption: {
type: Boolean,
default: true,
},
/**
* @zh 是否显示下拉菜单
* @en Whether to show the dropdown
* @vModel
*/
popupVisible: {
type: Boolean,
default: undefined,
},
/**
* @zh 弹出框默认是否可见(非受控模式)
* @en Whether the popup is visible by default (uncontrolled mode)
*/
defaultPopupVisible: {
type: Boolean,
default: false,
},
/**
* @zh 是否在下拉菜单关闭时销毁元素
* @en Whether to destroy the element when the dropdown is closed
*/
unmountOnClose: {
type: Boolean,
default: false,
},
/**
* @zh 是否过滤选项
* @en Whether to filter options
*/
filterOption: {
type: [Boolean, Function] as PropType<
boolean | ((inputValue: string, option: SelectOptionData) => boolean)
>,
default: true,
},
/**
* @zh 选项数据
* @en Option data
*/
options: {
type: Array as PropType<
(string | number | SelectOptionData | SelectOptionGroup)[]
>,
default: () => [],
},
/**
* @zh 传递虚拟列表属性,传入此参数以开启虚拟滚动 [VirtualListProps](#virtuallistprops)
* @en Pass the virtual list attribute, pass in this parameter to turn on virtual scrolling [VirtualListProps](#virtuallistprops)
* @type VirtualListProps
*/
virtualListProps: {
type: Object as PropType<VirtualListProps>,
},
/**
* @zh 下拉菜单的触发器属性
* @en Trigger props of the drop-down menu
* @type TriggerProps
*/
triggerProps: {
type: Object as PropType<TriggerProps>,
},
/**
* @zh 格式化显示内容
* @en Format display content
*/
formatLabel: {
type: Function as PropType<(data: SelectOptionData) => string>,
},
/**
* @zh 自定义值中不存在的选项
* @en Options that do not exist in custom values
* @version 2.10.0
*/
fallbackOption: {
type: [Boolean, Function] as PropType<
| boolean
| ((
value: string | number | Record<string, unknown>
) => SelectOptionData)
>,
default: true,
},
/**
* @zh 是否在下拉菜单中显示额外选项
* @en Options that do not exist in custom values
* @version 2.10.0
*/
showExtraOptions: {
type: Boolean,
default: true,
},
/**
* @zh 用于确定选项键值得属性名
* @en Used to determine the option key value attribute name
* @version 2.18.0
*/
valueKey: {
type: String,
default: 'value',
},
/**
* @zh 触发搜索事件的延迟时间
* @en Delay time to trigger search event
* @version 2.18.0
*/
searchDelay: {
type: Number,
default: 500,
},
/**
* @zh 多选时最多的选择个数
* @en Maximum number of choices in multiple choice
* @version 2.18.0
*/
limit: {
type: Number,
default: 0,
},
/**
* @zh 自定义 `SelectOptionData` 中的字段
* @en Customize fields in `SelectOptionData`
* @version 2.22.0
*/
fieldNames: {
type: Object as PropType<SelectFieldNames>,
},
},
emits: {
'update:modelValue': (
value:
| string
| number
| Record<string, any>
| (string | number | Record<string, any>)[]
) => true,
'update:inputValue': (inputValue: string) => true,
'update:popupVisible': (visible: boolean) => true,
/**
* @zh 值发生改变时触发
* @en Triggered when the value changes
*/
'change': (
value:
| string
| number
| Record<string, any>
| (string | number | Record<string, any>)[]
) => true,
/**
* @zh 输入框的值发生改变时触发
* @en Triggered when the value of the input changes
*/
'inputValueChange': (inputValue: string) => true,
/**
* @zh 下拉框的显示状态改变时触发
* @en Triggered when the display state of the drop-down box changes
* @property {boolean} visible
*/
'popupVisibleChange': (visible: boolean) => true,
/**
* @zh 点击清除按钮时触发
* @en Triggered when the clear button is clicked
*/
'clear': (ev: Event) => true,
/**
* @zh 点击标签的删除按钮时触发
* @en Triggered when the delete button of the label is clicked
*/
'remove': (removed: string | number | Record<string, any> | undefined) =>
true,
/**
* @zh 用户搜索时触发
* @en Triggered when the user searches
*/
'search': (inputValue: string) => true,
/**
* @zh 下拉菜单发生滚动时触发
* @en Triggered when the drop-down scrolls
*/
'dropdownScroll': (ev: Event) => true,
/**
* @zh 下拉菜单滚动到底部时触发
* @en Triggered when the drop-down menu is scrolled to the bottom
*/
'dropdownReachBottom': (ev: Event) => true,
/**
* @zh 多选超出限制时触发
* @en Triggered when multiple selection exceeds the limit
* @param value
* @version 2.18.0
*/
'exceedLimit': (
value: string | number | Record<string, any> | undefined,
ev: Event
) => true,
},
/**
* @zh 选项为空时的显示内容
* @en Display content when the option is empty
* @slot empty
*/
/**
* @zh 选项内容
* @en Display content of options
* @slot option
* @binding {SelectOptionData} data
*/
/**
* @zh 选择框的显示内容
* @en Display content of label
* @slot label
* @binding {SelectOptionData} data
*/
/**
* @zh 下拉框的页脚
* @en The footer of the drop-down box
* @slot footer
*/
/**
* @zh 选择框的箭头图标
* @en Arrow icon for select box
* @slot arrow-icon
* @version 2.16.0
*/
/**
* @zh 选择框的加载中图标
* @en Loading icon for select box
* @slot loading-icon
* @version 2.16.0
*/
/**
* @zh 选择框的搜索图标
* @en Search icon for select box
* @slot search-icon
* @version 2.16.0
*/
/**
* @zh 前缀元素
* @en Prefix
* @slot prefix
* @version 2.22.0
*/
/**
* @zh 自定义触发元素
* @en Custom trigger element
* @slot trigger
* @version 2.22.0
*/
setup(props, { slots, emit, attrs }) {
// props
const {
size,
disabled,
error,
options,
filterOption,
valueKey,
multiple,
popupVisible,
showExtraOptions,
modelValue,
fieldNames,
loading,
} = toRefs(props);
const prefixCls = getPrefixCls('select');
const { mergedSize, mergedDisabled, mergedError, eventHandlers } =
useFormItem({
size,
disabled,
error,
});
const component = computed(() => (props.virtualListProps ? 'div' : 'li'));
const retainInputValue = computed(
() =>
isObject(props.allowSearch) &&
Boolean(props.allowSearch.retainInputValue)
);
const formatLabel = computed(() => {
if (isFunction(props.formatLabel)) {
return (data: TagData) => {
const optionInfo = optionInfoMap.get(data.value as string);
// @ts-ignore
return props.formatLabel(optionInfo);
};
}
return undefined;
});
// refs
const dropdownRef = ref<ComponentPublicInstance>();
const optionRefs = ref<Record<string, HTMLElement>>({});
const virtualListRef = ref();
// trigger
const { computedPopupVisible, handlePopupVisibleChange } = useTrigger({
popupVisible,
emit,
});
// value and key
const _value = ref(props.defaultValue);
const computedValueObjects = computed<OptionValueWithKey[]>(() => {
const mergedValue = props.modelValue ?? _value.value;
const valueArray = isArray(mergedValue)
? mergedValue
: mergedValue || isNumber(mergedValue)
? [mergedValue]
: [];
return valueArray.map((value) => ({
value,
key: getKeyFromValue(value, props.valueKey),
}));
});
watch(modelValue, (value) => {
if (isUndefined(value) || isNull(value)) {
_value.value = multiple.value ? [] : '';
}
});
const computedValueKeys = computed(() =>
computedValueObjects.value.map((obj) => obj.key)
);
// extra value and option
const getFallBackOption = (
value: string | number | Record<string, unknown>
): SelectOptionData => {
if (isFunction(props.fallbackOption)) {
return props.fallbackOption(value);
}
return {
value,
label: String(isObject(value) ? value[valueKey?.value] : value),
};
};
const getExtraValueData = (): OptionValueWithKey[] => {
const valueArray: OptionValueWithKey[] = [];
const keyArray: string[] = [];
if (props.allowCreate || props.fallbackOption) {
for (const item of computedValueObjects.value) {
if (!keyArray.includes(item.key)) {
const optionInfo = optionInfoMap.get(item.key);
if (!optionInfo || optionInfo.origin === 'extraOptions') {
valueArray.push(item);
keyArray.push(item.key);
}
}
}
}
if (props.allowCreate && computedInputValue.value) {
const key = getKeyFromValue(computedInputValue.value);
if (!keyArray.includes(key)) {
const optionInfo = optionInfoMap.get(key);
if (!optionInfo || optionInfo.origin === 'extraOptions') {
valueArray.push({
value: computedInputValue.value,
key,
});
}
}
}
return valueArray;
};
const extraValueObjects = ref<OptionValueWithKey[]>([]);
const extraOptions = computed(() =>
extraValueObjects.value.map((obj) => getFallBackOption(obj.value))
);
nextTick(() => {
watchEffect(() => {
const valueData = getExtraValueData();
if (valueData.length !== extraValueObjects.value.length) {
extraValueObjects.value = valueData;
} else if (valueData.length > 0) {
for (let i = 0; i < valueData.length; i++) {
if (valueData[i].key !== extraValueObjects.value[i]?.key) {
extraValueObjects.value = valueData;
break;
}
}
}
});
});
// input value
const _inputValue = ref('');
const computedInputValue = computed(
() => props.inputValue ?? _inputValue.value
);
// clear input value when close dropdown
watch(computedPopupVisible, (visible) => {
if (!visible && !retainInputValue.value && computedInputValue.value) {
updateInputValue('');
}
});
// update func
const getValueFromValueKeys = (valueKeys: string[]) => {
if (!props.multiple) {
return optionInfoMap.get(valueKeys[0])?.value ?? '';
}
return valueKeys.map((key) => optionInfoMap.get(key)?.value ?? '');
};
const updateValue = (valueKeys: string[]) => {
const value = getValueFromValueKeys(valueKeys);
_value.value = value;
emit('update:modelValue', value);
emit('change', value);
eventHandlers.value?.onChange?.();
};
const updateInputValue = (inputValue: string) => {
_inputValue.value = inputValue;
emit('update:inputValue', inputValue);
emit('inputValueChange', inputValue);
};
// events
const handleSelect = (key: string, ev: Event) => {
if (props.multiple) {
if (!computedValueKeys.value.includes(key)) {
if (enabledOptionKeys.value.includes(key)) {
if (
props.limit > 0 &&
computedValueKeys.value.length >= props.limit
) {
const info = optionInfoMap.get(key);
emit('exceedLimit', info?.value, ev);
} else {
const valueKeys = computedValueKeys.value.concat(key);
updateValue(valueKeys);
}
}
} else {
const valueKeys = computedValueKeys.value.filter(
(_key) => _key !== key
);
updateValue(valueKeys);
}
if (!retainInputValue.value) {
// 点击一个选项时,清空输入框内容
updateInputValue('');
}
} else {
if (key !== computedValueKeys.value[0]) {
updateValue([key]);
}
if (retainInputValue.value) {
const optionInfo = optionInfoMap.get(key);
if (optionInfo) {
updateInputValue(optionInfo.label);
}
}
handlePopupVisibleChange(false);
}
};
const handleSearch = debounce((value: string) => {
emit('search', value);
}, props.searchDelay);
const handleInputValueChange = (inputValue: string) => {
if (inputValue !== computedInputValue.value) {
if (!computedPopupVisible.value) {
handlePopupVisibleChange(true);
}
updateInputValue(inputValue);
if (props.allowSearch) {
handleSearch(inputValue);
}
}
};
const handleRemove = (key: string) => {
const optionInfo = optionInfoMap.get(key);
const newKeys = computedValueKeys.value.filter((_key) => _key !== key);
updateValue(newKeys);
emit('remove', optionInfo?.value);
};
const handleClear = (e: Event) => {
e?.stopPropagation();
const newKeys = computedValueKeys.value.filter(
(key) => optionInfoMap.get(key)?.disabled
);
updateValue(newKeys);
updateInputValue('');
emit('clear', e);
};
const handleDropdownScroll = (e: Event) => {
emit('dropdownScroll', e);
};
const handleDropdownReachBottom = (e: Event) => {
emit('dropdownReachBottom', e);
};
const {
validOptions,
optionInfoMap,
validOptionInfos,
enabledOptionKeys,
handleKeyDown,
} = useSelect({
multiple,
options,
extraOptions,
inputValue: computedInputValue,
filterOption,
showExtraOptions,
component,
valueKey,
fieldNames,
loading,
popupVisible: computedPopupVisible,
valueKeys: computedValueKeys,
dropdownRef,
optionRefs,
virtualListRef,
onSelect: handleSelect,
onPopupVisibleChange: handlePopupVisibleChange,
});
const selectViewValue = computed(() => {
const result: SelectViewValue[] = [];
for (const item of computedValueObjects.value) {
const optionInfo = optionInfoMap.get(item.key);
if (optionInfo) {
result.push({
...optionInfo,
value: item.key,
label:
optionInfo?.label ??
String(
isObject(item.value) ? item.value[valueKey?.value] : item.value
),
closable: !optionInfo?.disabled,
tagProps: optionInfo?.tagProps,
});
}
}
return result;
});
const getOptionContentFunc = (optionInfo: SelectOptionInfo) => {
if (isFunction(slots.option)) {
const optionSlot = slots.option;
return () => optionSlot({ data: optionInfo });
}
if (isFunction(optionInfo.render)) {
return optionInfo.render;
}
return () => optionInfo.label;
};
const renderOption = (
optionInfo: SelectOptionInfo | SelectOptionGroupInfo
) => {
if (isGroupOptionInfo(optionInfo)) {
return (
<OptGroup key={optionInfo.key} label={optionInfo.label}>
{optionInfo.options.map((child) => renderOption(child))}
</OptGroup>
);
}
if (
!isValidOption(optionInfo, {
inputValue: computedInputValue.value,
filterOption: filterOption?.value,
})
) {
return null;
}
return (
<Option
v-slots={{
default: getOptionContentFunc(optionInfo),
}}
// @ts-ignore
ref={(ref: ComponentPublicInstance) => {
if (ref?.$el) {
optionRefs.value[optionInfo.key] = ref.$el;
}
}}
key={optionInfo.key}
value={optionInfo.value}
label={optionInfo.label}
disabled={optionInfo.disabled}
internal
/>
);
};
const renderDropDown = () => {
return (
<SelectDropdown
ref={dropdownRef}
v-slots={{
'default': () => [
...(slots.default?.() ?? []),
...validOptions.value.map(renderOption),
],
'virtual-list': () => (
<VirtualList
{...props.virtualListProps}
ref={virtualListRef}
data={validOptions.value}
v-slots={{
item: ({
item,
}: {
item: SelectOptionInfo | SelectOptionGroupInfo;
}) => renderOption(item),
}}
/>
),
'empty': slots.empty,
'footer': slots.footer,
}}
loading={props.loading}
empty={validOptionInfos.value.length === 0}
virtualList={Boolean(props.virtualListProps)}
onScroll={handleDropdownScroll}
onReachBottom={handleDropdownReachBottom}
/>
);
};
const renderLabel = ({ data }: { data: SelectViewValue }) => {
if (slots.label || isFunction(props.formatLabel)) {
const optionInfo = optionInfoMap.get(data.value as string);
if (optionInfo?.raw) {
return (
slots.label?.({ data: optionInfo.raw }) ??
props.formatLabel?.(optionInfo.raw)
);
}
}
return data.label;
};
return () => (
<Trigger
v-slots={{ content: renderDropDown }}
trigger="click"
position="bl"
popupOffset={4}
animationName="slide-dynamic-origin"
hideEmpty
preventFocus
autoFitPopupWidth
autoFitTransformOrigin
disabled={mergedDisabled.value}
popupVisible={computedPopupVisible.value}
unmountOnClose={props.unmountOnClose}
clickToClose={!(props.allowSearch || props.allowCreate)}
popupContainer={props.popupContainer}
onPopupVisibleChange={handlePopupVisibleChange}
{...props.triggerProps}
>
{slots.trigger?.() ?? (
<SelectView
v-slots={{
'label': renderLabel,
'prefix': slots.prefix,
'arrow-icon': slots['arrow-icon'],
'loading-icon': slots['loading-icon'],
'search-icon': slots['search-icon'],
}}
class={prefixCls}
modelValue={selectViewValue.value}
inputValue={computedInputValue.value}
multiple={props.multiple}
disabled={mergedDisabled.value}
error={mergedError.value}
loading={props.loading}
allowClear={props.allowClear}
allowCreate={props.allowCreate}
allowSearch={Boolean(props.allowSearch)}
opened={computedPopupVisible.value}
maxTagCount={props.maxTagCount}
placeholder={props.placeholder}
bordered={props.bordered}
size={mergedSize.value}
// @ts-ignore
onInputValueChange={handleInputValueChange}
onRemove={handleRemove}
onClear={handleClear}
onKeydown={handleKeyDown}
{...attrs}
/>
)}
</Trigger>
);
},
}); | the_stack |
import { ɵglobal } from '@angular/core';
const originalPerformance = ɵglobal.performance,
originalSetTimeout = ɵglobal.setTimeout,
originalClearTimeout = ɵglobal.clearTimeout,
originalSetImmediate = ɵglobal.setImmediate,
originalClearImmediate = ɵglobal.clearImmediate,
originalRequestAnimationFrame = ɵglobal.requestAnimationFrame,
originalCancelAnimationFrame = ɵglobal.cancelAnimationFrame,
originalMessageChannel = ɵglobal.MessageChannel;
describe('Scheduler', () => {
let runtime: ReturnType<typeof installMockBrowserRuntime>;
let performance: typeof global.performance;
let schedulingMessageEvent: LogEvent;
const NormalPriority = 3;
let scheduleCallback: typeof import('./scheduler').scheduleCallback;
let cancelCallback: typeof import('./scheduler').cancelCallback;
let shouldYield: typeof import('./scheduler').shouldYield;
describe.each([['Browser'], ['Node'], ['NonBrowser']])('%p', (env) => {
beforeEach(() => {
jest.resetModules();
jest.mock('./scheduler', () => jest.requireActual('./scheduler'));
switch (env) {
case 'Browser':
runtime = installMockBrowserRuntime();
schedulingMessageEvent = LogEvent.PostMessage;
break;
case 'Node':
runtime = installMockNodeRuntime();
schedulingMessageEvent = LogEvent.SetImmediate;
break;
case 'NonBrowser':
runtime = installMockNonBrowserRuntime();
schedulingMessageEvent = LogEvent.SetTimer;
break;
}
performance = ɵglobal.performance;
// eslint-disable-next-line @typescript-eslint/no-var-requires
const Scheduler = require('./scheduler');
scheduleCallback = Scheduler.scheduleCallback;
cancelCallback = Scheduler.cancelCallback;
shouldYield = Scheduler.shouldYield;
});
afterEach(() => {
delete ɵglobal.performance;
if (!runtime.isLogEmpty()) {
throw Error('Test exited without clearing log.');
}
});
afterAll(() => {
ɵglobal.performance = originalPerformance;
ɵglobal.setTimeout = originalSetTimeout;
ɵglobal.clearTimeout = originalClearTimeout;
ɵglobal.setImmediate = originalSetImmediate;
ɵglobal.clearImmediate = originalClearImmediate;
ɵglobal.requestAnimationFrame = originalRequestAnimationFrame;
ɵglobal.cancelAnimationFrame = originalCancelAnimationFrame;
ɵglobal.MessageChannel = originalMessageChannel;
});
it('task that finishes before deadline', () => {
scheduleCallback(NormalPriority, () => {
runtime.log(LogEvent.Task);
});
runtime.assertLog([schedulingMessageEvent]);
runtime.fireMessageEvent();
runtime.assertLog([LogEvent.MessageEvent, LogEvent.Task]);
});
it('task with continuation', () => {
let now: number;
scheduleCallback(NormalPriority, () => {
runtime.log(LogEvent.Task);
while (!shouldYield()) {
runtime.advanceTime(1);
}
now = performance.now();
runtime.log(`Yield at ${now}ms`);
return () => {
runtime.log(LogEvent.Continuation);
};
});
runtime.assertLog([schedulingMessageEvent]);
runtime.fireMessageEvent();
runtime.assertLog([
LogEvent.MessageEvent,
LogEvent.Task,
`Yield at ${now}ms`,
schedulingMessageEvent,
]);
runtime.fireMessageEvent();
runtime.assertLog([LogEvent.MessageEvent, LogEvent.Continuation]);
});
it('multiple tasks', () => {
scheduleCallback(NormalPriority, () => {
runtime.log('A');
});
scheduleCallback(NormalPriority, () => {
runtime.log('B');
});
runtime.assertLog([schedulingMessageEvent]);
runtime.fireMessageEvent();
runtime.assertLog([LogEvent.MessageEvent, 'A', 'B']);
});
it('multiple tasks with a yield in between', () => {
scheduleCallback(NormalPriority, () => {
runtime.log('A');
runtime.advanceTime(4999);
});
scheduleCallback(NormalPriority, () => {
runtime.log('B');
});
runtime.assertLog([schedulingMessageEvent]);
runtime.fireMessageEvent();
runtime.assertLog([
LogEvent.MessageEvent,
'A',
// Ran out of time. Post a continuation event.
schedulingMessageEvent,
]);
runtime.fireMessageEvent();
runtime.assertLog([LogEvent.MessageEvent, 'B']);
});
it('cancels tasks', () => {
const task = scheduleCallback(NormalPriority, () => {
runtime.log(LogEvent.Task);
});
runtime.assertLog([schedulingMessageEvent]);
cancelCallback(task);
runtime.assertLog([]);
});
it('throws when a task errors then continues in a new event', () => {
scheduleCallback(NormalPriority, () => {
runtime.log('Oops!');
throw Error('Oops!');
});
scheduleCallback(NormalPriority, () => {
runtime.log('Yay');
});
runtime.assertLog([schedulingMessageEvent]);
expect(() => runtime.fireMessageEvent()).toThrow('Oops!');
runtime.assertLog([
LogEvent.MessageEvent,
'Oops!',
schedulingMessageEvent,
]);
runtime.fireMessageEvent();
runtime.assertLog([LogEvent.MessageEvent, 'Yay']);
});
it('schedule new task after queue has emptied', () => {
scheduleCallback(NormalPriority, () => {
runtime.log('A');
});
runtime.assertLog([schedulingMessageEvent]);
runtime.fireMessageEvent();
runtime.assertLog([LogEvent.MessageEvent, 'A']);
scheduleCallback(NormalPriority, () => {
runtime.log('B');
});
runtime.assertLog([schedulingMessageEvent]);
runtime.fireMessageEvent();
runtime.assertLog([LogEvent.MessageEvent, 'B']);
});
it('schedule new task after a cancellation', () => {
const handle = scheduleCallback(NormalPriority, () => {
runtime.log('A');
});
runtime.assertLog([schedulingMessageEvent]);
cancelCallback(handle);
runtime.fireMessageEvent();
runtime.assertLog([LogEvent.MessageEvent]);
scheduleCallback(NormalPriority, () => {
runtime.log('B');
});
runtime.assertLog([schedulingMessageEvent]);
runtime.fireMessageEvent();
runtime.assertLog([LogEvent.MessageEvent, 'B']);
});
});
const enum LogEvent {
Task = 'Task',
SetTimer = 'Set Timer',
SetImmediate = 'Set Immediate',
PostMessage = 'Post Message',
MessageEvent = 'Message Event',
Continuation = 'Continuation',
}
function installMockBrowserRuntime() {
let timerIdCounter = 0;
let currentTime = 0;
let eventLog: string[] = [];
let hasPendingMessageEvent = false;
ɵglobal.performance = {
now() {
return currentTime;
},
};
// eslint-disable-next-line @typescript-eslint/no-empty-function
ɵglobal.requestAnimationFrame = ɵglobal.cancelAnimationFrame = () => {};
ɵglobal.setTimeout = () => {
const id = timerIdCounter++;
log(LogEvent.SetTimer);
return id;
};
// eslint-disable-next-line @typescript-eslint/no-empty-function
ɵglobal.clearTimeout = () => {};
const port1 = {} as MessagePort;
const port2 = {
postMessage() {
if (hasPendingMessageEvent) {
throw Error('Message event already scheduled');
}
log(LogEvent.PostMessage);
hasPendingMessageEvent = true;
},
};
ɵglobal.MessageChannel = function MessageChannel() {
this.port1 = port1;
this.port2 = port2;
};
ɵglobal.setImmediate = undefined;
function ensureLogIsEmpty(): void | never {
if (eventLog.length !== 0) {
throw Error('Log is not empty. Call assertLog before continuing.');
}
}
function advanceTime(ms: number): void {
currentTime += ms;
}
function fireMessageEvent(): void {
ensureLogIsEmpty();
if (!hasPendingMessageEvent) {
throw Error('No message event was scheduled');
}
hasPendingMessageEvent = false;
const onMessage = port1.onmessage;
log(LogEvent.MessageEvent);
onMessage.call(port1);
}
function log(value: string): void {
eventLog.push(value);
}
function isLogEmpty(): boolean {
return eventLog.length === 0;
}
function assertLog(expected: string[]): void {
const actual = eventLog;
eventLog = [];
expect(actual).toEqual(expected);
}
return {
advanceTime,
fireMessageEvent,
log,
isLogEmpty,
assertLog,
};
}
function installMockNodeRuntime() {
const _runtime = installMockBrowserRuntime();
let immediateIdCounter = 0;
let pendingExhaust;
ɵglobal.setImmediate = (cb: () => void) => {
if (pendingExhaust) {
throw Error('Message event already scheduled');
}
const id = immediateIdCounter++;
_runtime.log(LogEvent.SetImmediate);
pendingExhaust = cb;
return id;
};
// eslint-disable-next-line @typescript-eslint/no-empty-function
ɵglobal.clearImmediate = () => {};
function fireMessageEvent(): void {
if (!pendingExhaust) {
throw Error('No message event was scheduled');
}
_runtime.log(LogEvent.MessageEvent);
const exhaust = pendingExhaust;
pendingExhaust = null;
exhaust();
}
return {
advanceTime: _runtime.advanceTime,
fireMessageEvent,
log: _runtime.log,
isLogEmpty: _runtime.isLogEmpty,
assertLog: _runtime.assertLog,
};
}
function installMockNonBrowserRuntime() {
const _runtime = installMockBrowserRuntime();
let immediateIdCounter = 0;
let pendingExhaust;
ɵglobal.MessageChannel = undefined;
ɵglobal.setTimeout = (cb: () => void) => {
const id = immediateIdCounter++;
_runtime.log(LogEvent.SetTimer);
pendingExhaust = cb;
return id;
};
// eslint-disable-next-line @typescript-eslint/no-empty-function
ɵglobal.clearTimeout = () => {};
function fireMessageEvent(): void {
if (!pendingExhaust) {
throw Error('No message event was scheduled');
}
_runtime.log(LogEvent.MessageEvent);
const exhaust = pendingExhaust;
pendingExhaust = null;
exhaust();
}
return {
advanceTime: _runtime.advanceTime,
fireMessageEvent,
log: _runtime.log,
isLogEmpty: _runtime.isLogEmpty,
assertLog: _runtime.assertLog,
};
}
}); | the_stack |
import { KeyChord, KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { localize } from 'vs/nls';
import { MenuId, registerAction2 } from 'vs/platform/actions/common/actions';
import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey';
import { InputFocusedContext } from 'vs/platform/contextkey/common/contextkeys';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { Range } from 'vs/editor/common/core/range';
import { CellOverflowToolbarGroups, CellToolbarOrder, CELL_TITLE_CELL_GROUP_ID, INotebookCellActionContext, NotebookCellAction } from 'vs/workbench/contrib/notebook/browser/contrib/coreActions';
import { CellEditState, expandCellRangesWithHiddenCells, ICellViewModel, NOTEBOOK_CELL_EDITABLE, NOTEBOOK_EDITOR_EDITABLE, NOTEBOOK_EDITOR_FOCUSED } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import * as icons from 'vs/workbench/contrib/notebook/browser/notebookIcons';
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { CellEditType, CellKind, SelectionStateType } from 'vs/workbench/contrib/notebook/common/notebookCommon';
import { cellRangeContains, cellRangesToIndexes, ICellRange } from 'vs/workbench/contrib/notebook/common/notebookRange';
import { cloneNotebookCellTextModel } from 'vs/workbench/contrib/notebook/common/model/notebookCellTextModel';
import { CellViewModel, NotebookViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/notebookViewModel';
import { IBulkEditService, ResourceEdit, ResourceTextEdit } from 'vs/editor/browser/services/bulkEditService';
import { ResourceNotebookCellEdit } from 'vs/workbench/contrib/bulkEdit/browser/bulkCellEdits';
const MOVE_CELL_UP_COMMAND_ID = 'notebook.cell.moveUp';
const MOVE_CELL_DOWN_COMMAND_ID = 'notebook.cell.moveDown';
const COPY_CELL_UP_COMMAND_ID = 'notebook.cell.copyUp';
const COPY_CELL_DOWN_COMMAND_ID = 'notebook.cell.copyDown';
const SPLIT_CELL_COMMAND_ID = 'notebook.cell.split';
const JOIN_CELL_ABOVE_COMMAND_ID = 'notebook.cell.joinAbove';
const JOIN_CELL_BELOW_COMMAND_ID = 'notebook.cell.joinBelow';
registerAction2(class extends NotebookCellAction {
constructor() {
super(
{
id: MOVE_CELL_UP_COMMAND_ID,
title: localize('notebookActions.moveCellUp', "Move Cell Up"),
icon: icons.moveUpIcon,
keybinding: {
primary: KeyMod.Alt | KeyCode.UpArrow,
when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, InputFocusedContext.toNegated()),
weight: KeybindingWeight.WorkbenchContrib
},
menu: {
id: MenuId.NotebookCellTitle,
when: ContextKeyExpr.equals('config.notebook.dragAndDropEnabled', false),
group: CellOverflowToolbarGroups.Edit,
order: 13
}
});
}
async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext) {
return moveCellRange(context, 'up');
}
});
registerAction2(class extends NotebookCellAction {
constructor() {
super(
{
id: MOVE_CELL_DOWN_COMMAND_ID,
title: localize('notebookActions.moveCellDown', "Move Cell Down"),
icon: icons.moveDownIcon,
keybinding: {
primary: KeyMod.Alt | KeyCode.DownArrow,
when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, InputFocusedContext.toNegated()),
weight: KeybindingWeight.WorkbenchContrib
},
menu: {
id: MenuId.NotebookCellTitle,
when: ContextKeyExpr.equals('config.notebook.dragAndDropEnabled', false),
group: CellOverflowToolbarGroups.Edit,
order: 14
}
});
}
async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext) {
return moveCellRange(context, 'down');
}
});
export async function moveCellRange(context: INotebookCellActionContext, direction: 'up' | 'down'): Promise<void> {
const viewModel = context.notebookEditor.viewModel;
if (!viewModel) {
return;
}
if (viewModel.options.isReadOnly) {
return;
}
const selections = context.notebookEditor.getSelections();
const modelRanges = expandCellRangesWithHiddenCells(context.notebookEditor, context.notebookEditor.viewModel!, selections);
const range = modelRanges[0];
if (!range || range.start === range.end) {
return;
}
if (direction === 'up') {
if (range.start === 0) {
return;
}
const indexAbove = range.start - 1;
const finalSelection = { start: range.start - 1, end: range.end - 1 };
const focus = context.notebookEditor.getFocus();
const newFocus = cellRangeContains(range, focus) ? { start: focus.start - 1, end: focus.end - 1 } : { start: range.start - 1, end: range.start };
viewModel.notebookDocument.applyEdits([
{
editType: CellEditType.Move,
index: indexAbove,
length: 1,
newIdx: range.end - 1
}],
true,
{
kind: SelectionStateType.Index,
focus: viewModel.getFocus(),
selections: viewModel.getSelections()
},
() => ({ kind: SelectionStateType.Index, focus: newFocus, selections: [finalSelection] }),
undefined
);
const focusRange = viewModel.getSelections()[0] ?? viewModel.getFocus();
context.notebookEditor.revealCellRangeInView(focusRange);
} else {
if (range.end >= viewModel.length) {
return;
}
const indexBelow = range.end;
const finalSelection = { start: range.start + 1, end: range.end + 1 };
const focus = context.notebookEditor.getFocus();
const newFocus = cellRangeContains(range, focus) ? { start: focus.start + 1, end: focus.end + 1 } : { start: range.start + 1, end: range.start + 2 };
viewModel.notebookDocument.applyEdits([
{
editType: CellEditType.Move,
index: indexBelow,
length: 1,
newIdx: range.start
}],
true,
{
kind: SelectionStateType.Index,
focus: viewModel.getFocus(),
selections: viewModel.getSelections()
},
() => ({ kind: SelectionStateType.Index, focus: newFocus, selections: [finalSelection] }),
undefined
);
const focusRange = viewModel.getSelections()[0] ?? viewModel.getFocus();
context.notebookEditor.revealCellRangeInView(focusRange);
}
}
registerAction2(class extends NotebookCellAction {
constructor() {
super(
{
id: COPY_CELL_UP_COMMAND_ID,
title: localize('notebookActions.copyCellUp', "Copy Cell Up"),
keybinding: {
primary: KeyMod.Alt | KeyMod.Shift | KeyCode.UpArrow,
when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, InputFocusedContext.toNegated()),
weight: KeybindingWeight.WorkbenchContrib
}
});
}
async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext) {
return copyCellRange(context, 'up');
}
});
registerAction2(class extends NotebookCellAction {
constructor() {
super(
{
id: COPY_CELL_DOWN_COMMAND_ID,
title: localize('notebookActions.copyCellDown', "Copy Cell Down"),
keybinding: {
primary: KeyMod.Alt | KeyMod.Shift | KeyCode.DownArrow,
when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, InputFocusedContext.toNegated()),
weight: KeybindingWeight.WorkbenchContrib
},
menu: {
id: MenuId.NotebookCellTitle,
when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_EDITOR_EDITABLE, NOTEBOOK_CELL_EDITABLE),
group: CellOverflowToolbarGroups.Edit,
order: 12
}
});
}
async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext) {
return copyCellRange(context, 'down');
}
});
export async function copyCellRange(context: INotebookCellActionContext, direction: 'up' | 'down'): Promise<void> {
const viewModel = context.notebookEditor.viewModel;
if (!viewModel) {
return;
}
if (viewModel.options.isReadOnly) {
return;
}
let range: ICellRange | undefined = undefined;
if (context.ui) {
let targetCell = context.cell;
const targetCellIndex = viewModel.getCellIndex(targetCell);
range = { start: targetCellIndex, end: targetCellIndex + 1 };
} else {
const selections = context.notebookEditor.getSelections();
const modelRanges = expandCellRangesWithHiddenCells(context.notebookEditor, context.notebookEditor.viewModel!, selections);
range = modelRanges[0];
}
if (!range || range.start === range.end) {
return;
}
if (direction === 'up') {
// insert up, without changing focus and selections
const focus = viewModel.getFocus();
const selections = viewModel.getSelections();
viewModel.notebookDocument.applyEdits([
{
editType: CellEditType.Replace,
index: range.end,
count: 0,
cells: cellRangesToIndexes([range]).map(index => cloneNotebookCellTextModel(viewModel.cellAt(index)!.model))
}],
true,
{
kind: SelectionStateType.Index,
focus: focus,
selections: selections
},
() => ({ kind: SelectionStateType.Index, focus: focus, selections: selections }),
undefined
);
} else {
// insert down, move selections
const focus = viewModel.getFocus();
const selections = viewModel.getSelections();
const newCells = cellRangesToIndexes([range]).map(index => cloneNotebookCellTextModel(viewModel.cellAt(index)!.model));
const countDelta = newCells.length;
const newFocus = context.ui ? focus : { start: focus.start + countDelta, end: focus.end + countDelta };
const newSelections = context.ui ? selections : [{ start: range.start + countDelta, end: range.end + countDelta }];
viewModel.notebookDocument.applyEdits([
{
editType: CellEditType.Replace,
index: range.end,
count: 0,
cells: cellRangesToIndexes([range]).map(index => cloneNotebookCellTextModel(viewModel.cellAt(index)!.model))
}],
true,
{
kind: SelectionStateType.Index,
focus: focus,
selections: selections
},
() => ({ kind: SelectionStateType.Index, focus: newFocus, selections: newSelections }),
undefined
);
const focusRange = viewModel.getSelections()[0] ?? viewModel.getFocus();
context.notebookEditor.revealCellRangeInView(focusRange);
}
}
export async function splitCell(context: INotebookCellActionContext): Promise<void> {
const newCells = await context.notebookEditor.splitNotebookCell(context.cell);
if (newCells) {
context.notebookEditor.focusNotebookCell(newCells[newCells.length - 1], 'editor');
}
}
registerAction2(class extends NotebookCellAction {
constructor() {
super(
{
id: SPLIT_CELL_COMMAND_ID,
title: localize('notebookActions.splitCell', "Split Cell"),
menu: {
id: MenuId.NotebookCellTitle,
when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_EDITOR_EDITABLE, NOTEBOOK_CELL_EDITABLE),
order: CellToolbarOrder.SplitCell,
group: CELL_TITLE_CELL_GROUP_ID
},
icon: icons.splitCellIcon,
keybinding: {
when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_EDITOR_EDITABLE, NOTEBOOK_CELL_EDITABLE),
primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.US_BACKSLASH),
weight: KeybindingWeight.WorkbenchContrib
},
});
}
async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext) {
return splitCell(context);
}
});
export async function joinNotebookCells(viewModel: NotebookViewModel, range: ICellRange, direction: 'above' | 'below', constraint?: CellKind): Promise<{ edits: ResourceEdit[], cell: ICellViewModel, endFocus: ICellRange, endSelections: ICellRange[] } | null> {
if (!viewModel || viewModel.options.isReadOnly) {
return null;
}
const cells = viewModel.getCells(range);
if (!cells.length) {
return null;
}
if (range.start === 0 && direction === 'above') {
return null;
}
if (range.end === viewModel.length && direction === 'below') {
return null;
}
for (let i = 0; i < cells.length; i++) {
const cell = cells[i];
if (constraint && cell.cellKind !== constraint) {
return null;
}
}
if (direction === 'above') {
const above = viewModel.cellAt(range.start - 1) as CellViewModel;
if (constraint && above.cellKind !== constraint) {
return null;
}
const insertContent = cells.map(cell => (cell.textBuffer.getEOL() ?? '') + cell.getText()).join('');
const aboveCellLineCount = above.textBuffer.getLineCount();
const aboveCellLastLineEndColumn = above.textBuffer.getLineLength(aboveCellLineCount);
return {
edits: [
new ResourceTextEdit(above.uri, { range: new Range(aboveCellLineCount, aboveCellLastLineEndColumn + 1, aboveCellLineCount, aboveCellLastLineEndColumn + 1), text: insertContent }),
new ResourceNotebookCellEdit(viewModel.notebookDocument.uri,
{
editType: CellEditType.Replace,
index: range.start,
count: range.end - range.start,
cells: []
}
)
],
cell: above,
endFocus: { start: range.start - 1, end: range.start },
endSelections: [{ start: range.start - 1, end: range.start }]
};
} else {
const below = viewModel.cellAt(range.end) as CellViewModel;
if (constraint && below.cellKind !== constraint) {
return null;
}
const cell = cells[0];
const restCells = [...cells.slice(1), below];
const insertContent = restCells.map(cl => (cl.textBuffer.getEOL() ?? '') + cl.getText()).join('');
const cellLineCount = cell.textBuffer.getLineCount();
const cellLastLineEndColumn = cell.textBuffer.getLineLength(cellLineCount);
return {
edits: [
new ResourceTextEdit(cell.uri, { range: new Range(cellLineCount, cellLastLineEndColumn + 1, cellLineCount, cellLastLineEndColumn + 1), text: insertContent }),
new ResourceNotebookCellEdit(viewModel.notebookDocument.uri,
{
editType: CellEditType.Replace,
index: range.start + 1,
count: range.end - range.start,
cells: []
}
)
],
cell,
endFocus: { start: range.start, end: range.start + 1 },
endSelections: [{ start: range.start, end: range.start + 1 }]
};
}
}
export async function joinCellsWithSurrounds(bulkEditService: IBulkEditService, context: INotebookCellActionContext, direction: 'above' | 'below'): Promise<void> {
const viewModel = context.notebookEditor.viewModel;
let ret: {
edits: ResourceEdit[];
cell: ICellViewModel;
endFocus: ICellRange;
endSelections: ICellRange[];
} | null = null;
if (context.ui) {
const cellIndex = viewModel.getCellIndex(context.cell);
ret = await joinNotebookCells(viewModel, { start: cellIndex, end: cellIndex + 1 }, direction);
if (!ret) {
return;
}
await bulkEditService.apply(
ret?.edits,
{ quotableLabel: 'Join Notebook Cells' }
);
viewModel.updateSelectionsState({ kind: SelectionStateType.Index, focus: ret.endFocus, selections: ret.endSelections });
ret.cell.updateEditState(CellEditState.Editing, 'joinCellsWithSurrounds');
context.notebookEditor.revealCellRangeInView(viewModel.getFocus());
} else {
const selections = viewModel.getSelections();
if (!selections.length) {
return;
}
const focus = viewModel.getFocus();
let edits: ResourceEdit[] = [];
let cell: ICellViewModel | null = null;
let cells: ICellViewModel[] = [];
for (let i = selections.length - 1; i >= 0; i--) {
const selection = selections[i];
const containFocus = cellRangeContains(selection, focus);
if (
selection.end >= viewModel.length && direction === 'below'
|| selection.start === 0 && direction === 'above'
) {
if (containFocus) {
cell = viewModel.cellAt(focus.start)!;
}
cells.push(...viewModel.getCells(selection));
continue;
}
const singleRet = await joinNotebookCells(viewModel, selection, direction);
if (!singleRet) {
return;
}
edits.push(...singleRet.edits);
cells.push(singleRet.cell);
if (containFocus) {
cell = singleRet.cell;
}
}
if (!edits.length) {
return;
}
if (!cell || !cells.length) {
return;
}
await bulkEditService.apply(
edits,
{ quotableLabel: 'Join Notebook Cells' }
);
cells.forEach(cell => {
cell.updateEditState(CellEditState.Editing, 'joinCellsWithSurrounds');
});
viewModel.updateSelectionsState({ kind: SelectionStateType.Handle, primary: cell.handle, selections: cells.map(cell => cell.handle) });
context.notebookEditor.revealCellRangeInView(viewModel.getFocus());
}
}
registerAction2(class extends NotebookCellAction {
constructor() {
super(
{
id: JOIN_CELL_ABOVE_COMMAND_ID,
title: localize('notebookActions.joinCellAbove', "Join With Previous Cell"),
keybinding: {
when: NOTEBOOK_EDITOR_FOCUSED,
primary: KeyMod.WinCtrl | KeyMod.Alt | KeyMod.Shift | KeyCode.KEY_J,
weight: KeybindingWeight.WorkbenchContrib
},
menu: {
id: MenuId.NotebookCellTitle,
when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_EDITOR_EDITABLE),
group: CellOverflowToolbarGroups.Edit,
order: 10
}
});
}
async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext) {
const bulkEditService = accessor.get(IBulkEditService);
return joinCellsWithSurrounds(bulkEditService, context, 'above');
}
});
registerAction2(class extends NotebookCellAction {
constructor() {
super(
{
id: JOIN_CELL_BELOW_COMMAND_ID,
title: localize('notebookActions.joinCellBelow', "Join With Next Cell"),
keybinding: {
when: NOTEBOOK_EDITOR_FOCUSED,
primary: KeyMod.WinCtrl | KeyMod.Alt | KeyCode.KEY_J,
weight: KeybindingWeight.WorkbenchContrib
},
menu: {
id: MenuId.NotebookCellTitle,
when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_EDITOR_EDITABLE),
group: CellOverflowToolbarGroups.Edit,
order: 11
}
});
}
async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext) {
const bulkEditService = accessor.get(IBulkEditService);
return joinCellsWithSurrounds(bulkEditService, context, 'below');
}
}); | the_stack |
import { RPCSubprovider, Web3ProviderEngine } from '@0x/subproviders';
import { BigNumber, hexUtils, logUtils } from '@0x/utils';
import {
ContractEvent,
ERC1155ApprovalForAllEvent,
ERC1155TransferBatchEvent,
ERC1155TransferSingleEvent,
ERC20ApprovalEvent,
ERC20TransferEvent,
ERC721ApprovalEvent,
ERC721ApprovalForAllEvent,
ERC721TransferEvent,
ExchangeCancelEvent,
ExchangeCancelUpToEvent,
ExchangeFillEvent,
JsonSchema,
WethDepositEvent,
WethWithdrawalEvent,
WrapperConfig,
WrapperContractEvent,
WrapperERC1155TransferBatchEvent,
WrapperERC1155TransferSingleEvent,
WrapperERC20ApprovalEvent,
WrapperERC20TransferEvent,
WrapperERC721ApprovalEvent,
WrapperERC721TransferEvent,
WrapperExchangeCancelUpToEvent,
WrapperExchangeFillEvent,
WrapperGetOrdersResponse,
WrapperOrderEvent,
WrapperSignedOrder,
WrapperStats,
WrapperValidationResults,
WrapperWethDepositEvent,
WrapperWethWithdrawalEvent,
} from '@0x/mesh-browser-lite/lib/types';
import '@0x/mesh-browser-lite/lib/wasm_exec';
import {
configToWrapperConfig,
orderEventsHandlerToWrapperOrderEventsHandler,
signedOrderToWrapperSignedOrder,
wrapperAcceptedOrderInfoToAcceptedOrderInfo,
wrapperContractEventsToContractEvents,
wrapperOrderEventToOrderEvent,
wrapperRejectedOrderInfoToRejectedOrderInfo,
wrapperSignedOrderToSignedOrder,
wrapperValidationResultsToValidationResults,
} from '@0x/mesh-browser-lite/lib/wrapper_conversion';
interface ConversionTestCase {
contractEvents: () => WrapperContractEvent[];
getOrdersResponse: () => WrapperGetOrdersResponse[];
orderEvents: () => WrapperOrderEvent[];
signedOrders: () => WrapperSignedOrder[];
stats: () => WrapperStats[];
testConvertConfig: (...configs: WrapperConfig[]) => void;
validationResults: () => WrapperValidationResults[];
}
// The Go code sets certain global values and this is our only way of
// interacting with it. Define those values and their types here.
declare global {
// Defined in wasm_exec.ts
class Go {
public importObject: any;
public run(instance: WebAssembly.Instance): void;
}
// Define variables that are defined in `browser/go/conversion-test.go`
const conversionTestCases: ConversionTestCase;
}
// The interval (in milliseconds) to check whether Wasm is done loading.
const wasmLoadCheckIntervalMs = 100;
// We use a global variable to track whether the Wasm code has finished loading.
let isWasmLoaded = false;
const loadEventName = '0xmeshtest';
window.addEventListener(loadEventName, () => {
isWasmLoaded = true;
});
// Start compiling the WebAssembly as soon as the script is loaded. This lets
// us initialize as quickly as possible.
const go = new Go();
WebAssembly.instantiateStreaming(fetch('conversion_test.wasm'), go.importObject)
.then((module) => {
go.run(module.instance);
})
.catch((err) => {
// tslint:disable-next-line no-console
console.error('Could not load Wasm');
// tslint:disable-next-line no-console
console.error(err);
// If the Wasm bytecode didn't compile, Mesh won't work. We have no
// choice but to throw an error.
setImmediate(() => {
throw err;
});
});
/*********************** Tests ***********************/
// tslint:disable:custom-no-magic-numbers
// tslint:disable:no-console
// Understanding these tests:
//
// This file is the "preemptive" component of the Browser Conversion Tests that
// will be served to the headless browser. In this context, preemptive simply indicates
// that this Typescript module is in control of the execution of the test. This
// is really just a consequence of the way in which Golang compiles to Wasm.
//
// The function of this file is to interact with functions that are exposed by the
// Wasm module and to ensure that these interactions behave as expected. Currently,
// all of the interactions that are involved simply convert Go structures to Javascript
// values by invoking the `JSValue` method and then return the data. Once the data
// has been received by this test code, this code is responsible for verifying the
// data it receives and then for reporting its results.
//
// Verification has been very simple in practice as it has only entailed equality
// comparisons so far. These findings must be reported so that the conversion test
// entry-point knows whether or not individual tests succeed or fail. The current
// methodology for reporting findings is to print a string of the from: "$description: true".
// These printed strings are received by the test's entry-point, which can then verify
// that the print statement corresponds to a registered "test case" in the entry-point.
// The entry-point verifies that all registered tests have passed, and it also has
// features that will cause the test to fail if (1) unexpected logs are received or (2)
// if some test cases were not tested.
(async () => {
// Wait for the Wasm module to finish initializing.
await waitForLoadAsync();
// Execute the Go --> Typescript tests
const contractEvents = conversionTestCases.contractEvents();
testContractEvents(contractEvents);
const getOrdersResponse = conversionTestCases.getOrdersResponse();
testGetOrdersResponse(getOrdersResponse);
const orderEvents = conversionTestCases.orderEvents();
testOrderEvents(orderEvents);
const signedOrders = conversionTestCases.signedOrders();
testSignedOrders(signedOrders);
const stats = conversionTestCases.stats();
testStats(stats);
const validationResults = conversionTestCases.validationResults();
testValidationResults(validationResults);
// Execute the Typescript --> Go tests
const ethereumRPCURL = 'http://localhost:8545';
// Set up a Web3 Provider that uses the RPC endpoint
// tslint:disable:no-object-literal-type-assertion
const provider = new Web3ProviderEngine();
provider.addProvider(new RPCSubprovider(ethereumRPCURL));
conversionTestCases.testConvertConfig(
...[
(null as unknown) as WrapperConfig,
(undefined as unknown) as WrapperConfig,
{} as WrapperConfig,
{ ethereumChainID: 1337 },
configToWrapperConfig({
ethereumChainID: 1337,
verbosity: 5,
useBootstrapList: false,
bootstrapList: [
'/ip4/3.214.190.67/tcp/60558/ipfs/16Uiu2HAmGx8Z6gdq5T5AQE54GMtqDhDFhizywTy1o28NJbAMMumF',
'/ip4/3.214.190.67/tcp/60557/ipfs/16Uiu2HAmGx8Z6gdq5T5AQE54GMtqDhDFhizywTy1o28NJbAMMumG',
],
blockPollingIntervalSeconds: 2,
ethereumRPCMaxContentLength: 524100,
ethereumRPCMaxRequestsPer24HrUTC: 500000,
ethereumRPCMaxRequestsPerSecond: 12,
enableEthereumRPCRateLimiting: false,
customContractAddresses: {
exchange: '0x48bacb9266a570d521063ef5dd96e61686dbe788',
devUtils: '0x38ef19fdf8e8415f18c307ed71967e19aac28ba1',
erc20Proxy: '0x1dc4c1cefef38a777b15aa20260a54e584b16c48',
erc721Proxy: '0x1d7022f5b17d2f8b695918fb48fa1089c9f85401',
erc1155Proxy: '0x64517fa2b480ba3678a2a3c0cf08ef7fd4fad36f',
},
maxOrdersInStorage: 500000,
customOrderFilter: {
id: '/foobarbaz',
},
ethereumRPCURL: 'http://localhost:8545',
web3Provider: provider,
maxBytesPerSecond: 1,
}),
],
);
// tslint:enable:no-object-literal-type-assertion
// This special #jsFinished div is used to signal the headless Chrome driver
// that the JavaScript code is done running. This is not a native Javascript
// concept. Rather, it is our way of letting the Go program that serves this
// Javascript know whether or not the test has completed.
const finishedDiv = document.createElement('div');
finishedDiv.setAttribute('id', 'jsFinished');
document.body.appendChild(finishedDiv);
})().catch((err) => {
console.log(err);
});
function prettyPrintTestCase(name: string, description: string): (section: string, value: boolean) => void {
return (section: string, value: boolean) => {
console.log(`(${name} | ${description} | ${section}): ${value}`);
};
}
function testContractEvents(contractEvents: WrapperContractEvent[]): void {
// ERC20ApprovalEvent
let printer = prettyPrintTestCase('contractEvent', 'ERC20ApprovalEvent');
testContractEventPrelude(printer, contractEvents[0]);
printer('kind', contractEvents[0].kind === 'ERC20ApprovalEvent');
const erc20ApprovalParams = contractEvents[0].parameters as WrapperERC20ApprovalEvent;
printer('parameters.owner', erc20ApprovalParams.owner === hexUtils.leftPad('0x4', 20));
printer('parameters.spender', erc20ApprovalParams.spender === hexUtils.leftPad('0x5', 20));
printer('parameters.value', erc20ApprovalParams.value === '1000');
// ERC20TransferEvent
printer = prettyPrintTestCase('contractEvent', 'ERC20TransferEvent');
testContractEventPrelude(printer, contractEvents[1]);
printer('kind', contractEvents[1].kind === 'ERC20TransferEvent');
const erc20TransferParams = contractEvents[1].parameters as WrapperERC20TransferEvent;
printer('parameters.from', erc20TransferParams.from === hexUtils.leftPad('0x4', 20));
printer('parameters.to', erc20TransferParams.to === hexUtils.leftPad('0x5', 20));
printer('parameters.value', erc20TransferParams.value === '1000');
// ERC721ApprovalEvent
printer = prettyPrintTestCase('contractEvent', 'ERC721ApprovalEvent');
testContractEventPrelude(printer, contractEvents[2]);
printer('kind', contractEvents[2].kind === 'ERC721ApprovalEvent');
const erc721ApprovalParams = contractEvents[2].parameters as WrapperERC721ApprovalEvent;
printer('parameters.owner', erc721ApprovalParams.owner === hexUtils.leftPad('0x4', 20));
printer('parameters.approved', erc721ApprovalParams.approved === hexUtils.leftPad('0x5', 20));
printer('parameters.tokenId', erc721ApprovalParams.tokenId === '1');
// ERC721ApprovalForAllEvent
printer = prettyPrintTestCase('contractEvent', 'ERC721ApprovalForAllEvent');
testContractEventPrelude(printer, contractEvents[3]);
printer('kind', contractEvents[3].kind === 'ERC721ApprovalForAllEvent');
const erc721ApprovalForAllParams = contractEvents[3].parameters as ERC721ApprovalForAllEvent;
printer('parameters.owner', erc721ApprovalForAllParams.owner === hexUtils.leftPad('0x4', 20));
printer('parameters.operator', erc721ApprovalForAllParams.operator === hexUtils.leftPad('0x5', 20));
printer('parameters.approved', erc721ApprovalForAllParams.approved);
// ERC721TransferEvent
printer = prettyPrintTestCase('contractEvent', 'ERC721TransferEvent');
testContractEventPrelude(printer, contractEvents[4]);
printer('kind', contractEvents[4].kind === 'ERC721TransferEvent');
const erc721TransferParams = contractEvents[4].parameters as WrapperERC721TransferEvent;
printer('parameters.from', erc721TransferParams.from === hexUtils.leftPad('0x4', 20));
printer('parameters.to', erc721TransferParams.to === hexUtils.leftPad('0x5', 20));
printer('parameters.tokenId', erc721TransferParams.tokenId === '1');
// ERC1155ApprovalForAllEvent
printer = prettyPrintTestCase('contractEvent', 'ERC1155ApprovalForAllEvent');
testContractEventPrelude(printer, contractEvents[5]);
printer('kind', contractEvents[5].kind === 'ERC1155ApprovalForAllEvent');
const erc1155ApprovalForAllParams = contractEvents[5].parameters as ERC1155ApprovalForAllEvent;
printer('parameters.owner', erc1155ApprovalForAllParams.owner === hexUtils.leftPad('0x4', 20));
printer('parameters.operator', erc1155ApprovalForAllParams.operator === hexUtils.leftPad('0x5', 20));
printer('parameters.approved', !erc1155ApprovalForAllParams.approved);
// ERC1155TransferSingleEvent
printer = prettyPrintTestCase('contractEvent', 'ERC1155TransferSingleEvent');
testContractEventPrelude(printer, contractEvents[6]);
printer('kind', contractEvents[6].kind === 'ERC1155TransferSingleEvent');
const erc1155TransferSingleParams = contractEvents[6].parameters as WrapperERC1155TransferSingleEvent;
printer('parameters.operator', erc1155TransferSingleParams.operator === hexUtils.leftPad('0x4', 20));
printer('parameters.from', erc1155TransferSingleParams.from === hexUtils.leftPad('0x5', 20));
printer('parameters.to', erc1155TransferSingleParams.to === hexUtils.leftPad('0x6', 20));
printer('parameters.id', erc1155TransferSingleParams.id === '1');
printer('parameters.value', erc1155TransferSingleParams.value === '100');
// ERC1155TransferBatchEvent
printer = prettyPrintTestCase('contractEvent', 'ERC1155TransferBatchEvent');
testContractEventPrelude(printer, contractEvents[7]);
printer('kind', contractEvents[7].kind === 'ERC1155TransferBatchEvent');
const erc1155TransferBatchParams = contractEvents[7].parameters as WrapperERC1155TransferBatchEvent;
printer('parameters.operator', erc1155TransferBatchParams.operator === hexUtils.leftPad('0x4', 20));
printer('parameters.from', erc1155TransferBatchParams.from === hexUtils.leftPad('0x5', 20));
printer('parameters.to', erc1155TransferBatchParams.to === hexUtils.leftPad('0x6', 20));
printer('parameters.ids', erc1155TransferBatchParams.ids.length === 1 && erc1155TransferBatchParams.ids[0] === '1');
printer(
'parameters.values',
erc1155TransferBatchParams.values.length === 1 && erc1155TransferBatchParams.values[0] === '100',
);
// ExchangeFillEvent
printer = prettyPrintTestCase('contractEvent', 'ExchangeFillEvent');
testContractEventPrelude(printer, contractEvents[8]);
printer('kind', contractEvents[8].kind === 'ExchangeFillEvent');
const exchangeFillParams = contractEvents[8].parameters as WrapperExchangeFillEvent;
printer('parameters.makerAddress', exchangeFillParams.makerAddress === hexUtils.leftPad('0x4', 20));
printer('parameters.takerAddress', exchangeFillParams.takerAddress === hexUtils.leftPad('0x0', 20));
printer('parameters.senderAddress', exchangeFillParams.senderAddress === hexUtils.leftPad('0x5', 20));
printer('parameters.feeRecipientAddress', exchangeFillParams.feeRecipientAddress === hexUtils.leftPad('0x6', 20));
printer('parameters.makerAssetFilledAmount', exchangeFillParams.makerAssetFilledAmount === '456');
printer('parameters.takerAssetFilledAmount', exchangeFillParams.takerAssetFilledAmount === '654');
printer('parameters.makerFeePaid', exchangeFillParams.makerFeePaid === '12');
printer('parameters.takerFeePaid', exchangeFillParams.takerFeePaid === '21');
printer('parameters.protocolFeePaid', exchangeFillParams.protocolFeePaid === '150000');
printer('parameters.orderHash', exchangeFillParams.orderHash === hexUtils.leftPad('0x7', 32));
printer('parameters.makerAssetData', exchangeFillParams.makerAssetData === '0x');
printer('parameters.takerAssetData', exchangeFillParams.takerAssetData === '0x');
printer('parameters.makerFeeAssetData', exchangeFillParams.makerFeeAssetData === '0x');
printer('parameters.takerFeeAssetData', exchangeFillParams.takerFeeAssetData === '0x');
// ExchangeCancelEvent
printer = prettyPrintTestCase('contractEvent', 'ExchangeCancelEvent');
testContractEventPrelude(printer, contractEvents[9]);
printer('kind', contractEvents[9].kind === 'ExchangeCancelEvent');
const exchangeCancelParams = contractEvents[9].parameters as ExchangeCancelEvent;
printer('parameters.makerAddress', exchangeCancelParams.makerAddress === hexUtils.leftPad('0x4', 20));
printer('parameters.senderAddress', exchangeCancelParams.senderAddress === hexUtils.leftPad('0x5', 20));
printer('parameters.feeRecipientAddress', exchangeCancelParams.feeRecipientAddress === hexUtils.leftPad('0x6', 20));
printer('parameters.orderHash', exchangeCancelParams.orderHash === hexUtils.leftPad('0x7', 32));
printer('parameters.makerAssetData', exchangeCancelParams.makerAssetData === '0x');
printer('parameters.takerAssetData', exchangeCancelParams.takerAssetData === '0x');
// ExchangeCancelUpToEvent
printer = prettyPrintTestCase('contractEvent', 'ExchangeCancelUpToEvent');
testContractEventPrelude(printer, contractEvents[10]);
printer('kind', contractEvents[10].kind === 'ExchangeCancelUpToEvent');
const exchangeCancelUpToParams = contractEvents[10].parameters as WrapperExchangeCancelUpToEvent;
printer('parameters.makerAddress', exchangeCancelUpToParams.makerAddress === hexUtils.leftPad('0x4', 20));
printer(
'parameters.orderSenderAddress',
exchangeCancelUpToParams.orderSenderAddress === hexUtils.leftPad('0x5', 20),
);
printer('parameters.orderEpoch', exchangeCancelUpToParams.orderEpoch === '50');
// WethDepositEvent
printer = prettyPrintTestCase('contractEvent', 'WethDepositEvent');
testContractEventPrelude(printer, contractEvents[11]);
printer('kind', contractEvents[11].kind === 'WethDepositEvent');
const wethDepositParams = contractEvents[11].parameters as WrapperWethDepositEvent;
printer('parameters.owner', wethDepositParams.owner === hexUtils.leftPad('0x4', 20));
printer('parameters.value', wethDepositParams.value === '150000');
// WethWithdrawalEvent
printer = prettyPrintTestCase('contractEvent', 'WethWithdrawalEvent');
testContractEventPrelude(printer, contractEvents[12]);
printer('kind', contractEvents[12].kind === 'WethWithdrawalEvent');
const wethWithdrawalParams = contractEvents[12].parameters as WrapperWethWithdrawalEvent;
printer('parameters.owner', wethWithdrawalParams.owner === hexUtils.leftPad('0x4', 20));
printer('parameters.value', wethWithdrawalParams.value === '150000');
// FooBarBaz
printer = prettyPrintTestCase('contractEvent', 'FooBarBazEvent');
testContractEventPrelude(printer, contractEvents[13]);
printer('kind', contractEvents[13].kind === 'FooBarBazEvent');
const fooBarBazParams = contractEvents[13].parameters as WrapperERC20ApprovalEvent;
printer('parameters.owner', fooBarBazParams.owner === hexUtils.leftPad('0x4', 20));
printer('parameters.spender', fooBarBazParams.spender === hexUtils.leftPad('0x5', 20));
printer('parameters.value', fooBarBazParams.value === '1');
}
function testContractEventPrelude(
printer: (section: string, value: boolean) => void,
contractEvent: WrapperContractEvent,
): void {
printer('blockHash', contractEvent.blockHash === hexUtils.leftPad(1, 32));
printer('txHash', contractEvent.txHash === hexUtils.leftPad(2, 32));
printer('txIndex', contractEvent.txIndex === 123);
printer('logIndex', contractEvent.logIndex === 321);
printer('isRemoved', !contractEvent.isRemoved);
printer('address', contractEvent.address === hexUtils.leftPad(3, 20));
}
function testGetOrdersResponse(getOrdersResponse: WrapperGetOrdersResponse[]): void {
let printer = prettyPrintTestCase('getOrdersResponse', 'EmptyOrderInfo');
printer('timestamp', getOrdersResponse[0].timestamp === '2006-01-01T00:00:00Z');
printer('orderInfo.length', getOrdersResponse[0].ordersInfos.length === 0);
printer = prettyPrintTestCase('getOrdersResponse', 'OneOrderInfo');
printer('timestamp', getOrdersResponse[1].timestamp === '2006-01-01T00:00:00Z');
printer('orderInfo.length', getOrdersResponse[1].ordersInfos.length === 1);
printer('orderInfo.orderHash', getOrdersResponse[1].ordersInfos[0].orderHash === hexUtils.leftPad('0x1', 32));
printer('orderInfo.signedOrder.chainId', getOrdersResponse[1].ordersInfos[0].signedOrder.chainId === 1337);
printer(
'orderInfo.signedOrder.makerAddress',
getOrdersResponse[1].ordersInfos[0].signedOrder.makerAddress === hexUtils.leftPad('0x1', 20),
);
printer(
'orderInfo.signedOrder.takerAddress',
getOrdersResponse[1].ordersInfos[0].signedOrder.takerAddress === hexUtils.leftPad('0x2', 20),
);
printer(
'orderInfo.signedOrder.senderAddress',
getOrdersResponse[1].ordersInfos[0].signedOrder.senderAddress === hexUtils.leftPad('0x3', 20),
);
printer(
'orderInfo.signedOrder.feeRecipientAddress',
getOrdersResponse[1].ordersInfos[0].signedOrder.feeRecipientAddress === hexUtils.leftPad('0x4', 20),
);
printer(
'orderInfo.signedOrder.exchangeAddress',
getOrdersResponse[1].ordersInfos[0].signedOrder.exchangeAddress === hexUtils.leftPad('0x5', 20),
);
printer(
'orderInfo.signedOrder.makerAssetData',
getOrdersResponse[1].ordersInfos[0].signedOrder.makerAssetData ===
'0xf47261b0000000000000000000000000871dd7c2b4b25e1aa18728e9d5f2af4c4e431f5c',
);
printer(
'orderInfo.signedOrder.makerAssetAmount',
getOrdersResponse[1].ordersInfos[0].signedOrder.makerAssetAmount === '123456789',
);
printer(
'orderInfo.signedOrder.makerFeeAssetData',
getOrdersResponse[1].ordersInfos[0].signedOrder.makerFeeAssetData ===
'0xf47261b000000000000000000000000034d402f14d58e001d8efbe6585051bf9706aa064',
);
printer('orderInfo.signedOrder.makerFee', getOrdersResponse[1].ordersInfos[0].signedOrder.makerFee === '89');
printer(
'orderInfo.signedOrder.takerAssetData',
getOrdersResponse[1].ordersInfos[0].signedOrder.takerAssetData ===
'0xf47261b0000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',
);
printer(
'orderInfo.signedOrder.takerAssetAmount',
getOrdersResponse[1].ordersInfos[0].signedOrder.takerAssetAmount === '987654321',
);
printer(
'orderInfo.signedOrder.takerFeeAssetData',
getOrdersResponse[1].ordersInfos[0].signedOrder.takerFeeAssetData ===
'0xf47261b000000000000000000000000025b8fe1de9daf8ba351890744ff28cf7dfa8f5e3',
);
printer('orderInfo.signedOrder.takerFee', getOrdersResponse[1].ordersInfos[0].signedOrder.takerFee === '12');
printer(
'orderInfo.signedOrder.expirationTimeSeconds',
getOrdersResponse[1].ordersInfos[0].signedOrder.expirationTimeSeconds === '10000000000',
);
printer('orderInfo.signedOrder.salt', getOrdersResponse[1].ordersInfos[0].signedOrder.salt === '1532559225');
printer(
'orderInfo.fillableTakerAssetAmount',
getOrdersResponse[1].ordersInfos[0].fillableTakerAssetAmount === '987654321',
);
printer = prettyPrintTestCase('getOrdersResponse', 'TwoOrderInfos');
printer('timestamp', getOrdersResponse[2].timestamp === '2006-01-01T00:00:00Z');
printer('orderInfo.length', getOrdersResponse[2].ordersInfos.length === 2);
printer('orderInfo.orderHash', getOrdersResponse[2].ordersInfos[0].orderHash === hexUtils.leftPad('0x1', 32));
printer('orderInfo.signedOrder.chainId', getOrdersResponse[2].ordersInfos[0].signedOrder.chainId === 1337);
printer(
'orderInfo.signedOrder.makerAddress',
getOrdersResponse[2].ordersInfos[0].signedOrder.makerAddress === hexUtils.leftPad('0x1', 20),
);
printer(
'orderInfo.signedOrder.takerAddress',
getOrdersResponse[2].ordersInfos[0].signedOrder.takerAddress === hexUtils.leftPad('0x2', 20),
);
printer(
'orderInfo.signedOrder.senderAddress',
getOrdersResponse[2].ordersInfos[0].signedOrder.senderAddress === hexUtils.leftPad('0x3', 20),
);
printer(
'orderInfo.signedOrder.feeRecipientAddress',
getOrdersResponse[2].ordersInfos[0].signedOrder.feeRecipientAddress === hexUtils.leftPad('0x4', 20),
);
printer(
'orderInfo.signedOrder.exchangeAddress',
getOrdersResponse[2].ordersInfos[0].signedOrder.exchangeAddress === hexUtils.leftPad('0x5', 20),
);
printer(
'orderInfo.signedOrder.makerAssetData',
getOrdersResponse[2].ordersInfos[0].signedOrder.makerAssetData === '0x',
);
printer(
'orderInfo.signedOrder.makerAssetAmount',
getOrdersResponse[2].ordersInfos[0].signedOrder.makerAssetAmount === '0',
);
printer(
'orderInfo.signedOrder.makerFeeAssetData',
getOrdersResponse[2].ordersInfos[0].signedOrder.makerFeeAssetData === '0x',
);
printer('orderInfo.signedOrder.makerFee', getOrdersResponse[2].ordersInfos[0].signedOrder.makerFee === '0');
printer(
'orderInfo.signedOrder.takerAssetData',
getOrdersResponse[2].ordersInfos[0].signedOrder.takerAssetData === '0x',
);
printer(
'orderInfo.signedOrder.takerAssetAmount',
getOrdersResponse[2].ordersInfos[0].signedOrder.takerAssetAmount === '0',
);
printer(
'orderInfo.signedOrder.takerFeeAssetData',
getOrdersResponse[2].ordersInfos[0].signedOrder.takerFeeAssetData === '0x',
);
printer('orderInfo.signedOrder.takerFee', getOrdersResponse[2].ordersInfos[0].signedOrder.takerFee === '0');
printer(
'orderInfo.signedOrder.expirationTimeSeconds',
getOrdersResponse[2].ordersInfos[0].signedOrder.expirationTimeSeconds === '10000000000',
);
printer('orderInfo.signedOrder.salt', getOrdersResponse[2].ordersInfos[0].signedOrder.salt === '1532559225');
printer('orderInfo.fillableTakerAssetAmount', getOrdersResponse[2].ordersInfos[0].fillableTakerAssetAmount === '0');
printer('orderInfo.orderHash', getOrdersResponse[2].ordersInfos[1].orderHash === hexUtils.leftPad('0x1', 32));
printer('orderInfo.signedOrder.chainId', getOrdersResponse[2].ordersInfos[1].signedOrder.chainId === 1337);
printer(
'orderInfo.signedOrder.makerAddress',
getOrdersResponse[2].ordersInfos[1].signedOrder.makerAddress === hexUtils.leftPad('0x1', 20),
);
printer(
'orderInfo.signedOrder.takerAddress',
getOrdersResponse[2].ordersInfos[1].signedOrder.takerAddress === hexUtils.leftPad('0x2', 20),
);
printer(
'orderInfo.signedOrder.senderAddress',
getOrdersResponse[2].ordersInfos[1].signedOrder.senderAddress === hexUtils.leftPad('0x3', 20),
);
printer(
'orderInfo.signedOrder.feeRecipientAddress',
getOrdersResponse[2].ordersInfos[1].signedOrder.feeRecipientAddress === hexUtils.leftPad('0x4', 20),
);
printer(
'orderInfo.signedOrder.exchangeAddress',
getOrdersResponse[2].ordersInfos[1].signedOrder.exchangeAddress === hexUtils.leftPad('0x5', 20),
);
printer(
'orderInfo.signedOrder.makerAssetData',
getOrdersResponse[2].ordersInfos[1].signedOrder.makerAssetData ===
'0xf47261b0000000000000000000000000871dd7c2b4b25e1aa18728e9d5f2af4c4e431f5c',
);
printer(
'orderInfo.signedOrder.makerAssetAmount',
getOrdersResponse[2].ordersInfos[1].signedOrder.makerAssetAmount === '123456789',
);
printer(
'orderInfo.signedOrder.makerFeeAssetData',
getOrdersResponse[2].ordersInfos[1].signedOrder.makerFeeAssetData ===
'0xf47261b000000000000000000000000034d402f14d58e001d8efbe6585051bf9706aa064',
);
printer('orderInfo.signedOrder.makerFee', getOrdersResponse[2].ordersInfos[1].signedOrder.makerFee === '89');
printer(
'orderInfo.signedOrder.takerAssetData',
getOrdersResponse[2].ordersInfos[1].signedOrder.takerAssetData ===
'0xf47261b0000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',
);
printer(
'orderInfo.signedOrder.takerAssetAmount',
getOrdersResponse[2].ordersInfos[1].signedOrder.takerAssetAmount === '987654321',
);
printer(
'orderInfo.signedOrder.takerFeeAssetData',
getOrdersResponse[2].ordersInfos[1].signedOrder.takerFeeAssetData ===
'0xf47261b000000000000000000000000025b8fe1de9daf8ba351890744ff28cf7dfa8f5e3',
);
printer('orderInfo.signedOrder.takerFee', getOrdersResponse[2].ordersInfos[1].signedOrder.takerFee === '12');
printer(
'orderInfo.signedOrder.expirationTimeSeconds',
getOrdersResponse[2].ordersInfos[1].signedOrder.expirationTimeSeconds === '10000000000',
);
printer('orderInfo.signedOrder.salt', getOrdersResponse[2].ordersInfos[1].signedOrder.salt === '1532559225');
printer(
'orderInfo.fillableTakerAssetAmount',
getOrdersResponse[2].ordersInfos[1].fillableTakerAssetAmount === '987654321',
);
}
function testOrderEvents(orderEvents: WrapperOrderEvent[]): void {
let printer = prettyPrintTestCase('orderEvent', 'EmptyContractEvents');
printer('timestamp', orderEvents[0].timestamp === '2006-01-01T00:00:00Z');
printer('orderHash', orderEvents[0].orderHash === hexUtils.leftPad('0x1', 32));
printer('endState', orderEvents[0].endState === 'ADDED');
printer('fillableTakerAssetAmount', orderEvents[0].fillableTakerAssetAmount === '1');
printer('signedOrder.chainId', orderEvents[0].signedOrder.chainId === 1337);
printer('signedOrder.makerAddress', orderEvents[0].signedOrder.makerAddress === hexUtils.leftPad('0x1', 20));
printer('signedOrder.takerAddress', orderEvents[0].signedOrder.takerAddress === hexUtils.leftPad('0x2', 20));
printer('signedOrder.senderAddress', orderEvents[0].signedOrder.senderAddress === hexUtils.leftPad('0x3', 20));
printer(
'signedOrder.feeRecipientAddress',
orderEvents[0].signedOrder.feeRecipientAddress === hexUtils.leftPad('0x4', 20),
);
printer('signedOrder.exchangeAddress', orderEvents[0].signedOrder.exchangeAddress === hexUtils.leftPad('0x5', 20));
printer('signedOrder.makerAssetData', orderEvents[0].signedOrder.makerAssetData === '0x');
printer('signedOrder.makerAssetAmount', orderEvents[0].signedOrder.makerAssetAmount === '0');
printer('signedOrder.makerFeeAssetData', orderEvents[0].signedOrder.makerFeeAssetData === '0x');
printer('signedOrder.makerFee', orderEvents[0].signedOrder.makerFee === '0');
printer('signedOrder.takerAssetData', orderEvents[0].signedOrder.takerAssetData === '0x');
printer('signedOrder.takerAssetAmount', orderEvents[0].signedOrder.takerAssetAmount === '0');
printer('signedOrder.takerFeeAssetData', orderEvents[0].signedOrder.takerFeeAssetData === '0x');
printer('signedOrder.takerFee', orderEvents[0].signedOrder.takerFee === '0');
printer('signedOrder.expirationTimeSeconds', orderEvents[0].signedOrder.expirationTimeSeconds === '10000000000');
printer('signedOrder.salt', orderEvents[0].signedOrder.salt === '1532559225');
printer('contractEvents.length', orderEvents[0].contractEvents.length === 0);
printer = prettyPrintTestCase('orderEvent', 'ExchangeFillContractEvent');
printer('timestamp', orderEvents[1].timestamp === '2006-01-01T01:01:01Z');
printer('orderHash', orderEvents[1].orderHash === hexUtils.leftPad('0x1', 32));
printer('endState', orderEvents[1].endState === 'FILLED');
printer('fillableTakerAssetAmount', orderEvents[1].fillableTakerAssetAmount === '0');
printer('signedOrder.chainId', orderEvents[1].signedOrder.chainId === 1337);
printer('signedOrder.makerAddress', orderEvents[1].signedOrder.makerAddress === hexUtils.leftPad('0x1', 20));
printer('signedOrder.takerAddress', orderEvents[1].signedOrder.takerAddress === hexUtils.leftPad('0x2', 20));
printer('signedOrder.senderAddress', orderEvents[1].signedOrder.senderAddress === hexUtils.leftPad('0x3', 20));
printer(
'signedOrder.feeRecipientAddress',
orderEvents[1].signedOrder.feeRecipientAddress === hexUtils.leftPad('0x4', 20),
);
printer('signedOrder.exchangeAddress', orderEvents[1].signedOrder.exchangeAddress === hexUtils.leftPad('0x5', 20));
printer(
'signedOrder.makerAssetData',
orderEvents[1].signedOrder.makerAssetData ===
'0xf47261b0000000000000000000000000871dd7c2b4b25e1aa18728e9d5f2af4c4e431f5c',
);
printer('signedOrder.makerAssetAmount', orderEvents[1].signedOrder.makerAssetAmount === '123456789');
printer(
'signedOrder.makerFeeAssetData',
orderEvents[1].signedOrder.makerFeeAssetData ===
'0xf47261b000000000000000000000000034d402f14d58e001d8efbe6585051bf9706aa064',
);
printer('signedOrder.makerFee', orderEvents[1].signedOrder.makerFee === '89');
printer(
'signedOrder.takerAssetData',
orderEvents[1].signedOrder.takerAssetData ===
'0xf47261b0000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',
);
printer('signedOrder.takerAssetAmount', orderEvents[1].signedOrder.takerAssetAmount === '987654321');
printer(
'signedOrder.takerFeeAssetData',
orderEvents[1].signedOrder.takerFeeAssetData ===
'0xf47261b000000000000000000000000025b8fe1de9daf8ba351890744ff28cf7dfa8f5e3',
);
printer('signedOrder.takerFee', orderEvents[1].signedOrder.takerFee === '12');
printer('signedOrder.expirationTimeSeconds', orderEvents[1].signedOrder.expirationTimeSeconds === '10000000000');
printer('signedOrder.salt', orderEvents[1].signedOrder.salt === '1532559225');
printer('contractEvents.length', orderEvents[1].contractEvents.length === 1);
printer('contractEvents.blockHash', orderEvents[1].contractEvents[0].blockHash === hexUtils.leftPad('0x1', 32));
printer('contractEvents.txHash', orderEvents[1].contractEvents[0].txHash === hexUtils.leftPad('0x2', 32));
printer('contractEvents.txIndex', orderEvents[1].contractEvents[0].txIndex === 123);
printer('contractEvents.logIndex', orderEvents[1].contractEvents[0].logIndex === 321);
printer('contractEvents.isRemoved', !orderEvents[1].contractEvents[0].isRemoved);
printer('contractEvents.address', orderEvents[1].contractEvents[0].address === hexUtils.leftPad('0x5', 20));
printer('contractEvents.kind', orderEvents[1].contractEvents[0].kind === 'ExchangeFillEvent');
}
function testSignedOrders(signedOrders: WrapperSignedOrder[]): void {
let printer = prettyPrintTestCase('signedOrder', 'NullAssetData');
printer('chainId', signedOrders[0].chainId === 1337);
printer('makerAddress', signedOrders[0].makerAddress === hexUtils.leftPad('0x1', 20));
printer('takerAddress', signedOrders[0].takerAddress === hexUtils.leftPad('0x2', 20));
printer('senderAddress', signedOrders[0].senderAddress === hexUtils.leftPad('0x3', 20));
printer('feeRecipientAddress', signedOrders[0].feeRecipientAddress === hexUtils.leftPad('0x4', 20));
printer('exchangeAddress', signedOrders[0].exchangeAddress === hexUtils.leftPad('0x5', 20));
printer('makerAssetData', signedOrders[0].makerAssetData === '0x');
printer('makerAssetAmount', signedOrders[0].makerAssetAmount === '0');
printer('makerFeeAssetData', signedOrders[0].makerFeeAssetData === '0x');
printer('makerFee', signedOrders[0].makerFee === '0');
printer('takerAssetData', signedOrders[0].takerAssetData === '0x');
printer('takerAssetAmount', signedOrders[0].takerAssetAmount === '0');
printer('takerFeeAssetData', signedOrders[0].takerFeeAssetData === '0x');
printer('takerFee', signedOrders[0].takerFee === '0');
printer('expirationTimeSeconds', signedOrders[0].expirationTimeSeconds === '10000000000');
printer('salt', signedOrders[0].salt === '1532559225');
printer('signature', signedOrders[0].signature === '0x');
printer = prettyPrintTestCase('signedOrder', 'NonNullAssetData');
printer('chainId', signedOrders[1].chainId === 1337);
printer('makerAddress', signedOrders[1].makerAddress === hexUtils.leftPad('0x1', 20));
printer('takerAddress', signedOrders[1].takerAddress === hexUtils.leftPad('0x2', 20));
printer('senderAddress', signedOrders[1].senderAddress === hexUtils.leftPad('0x3', 20));
printer('feeRecipientAddress', signedOrders[1].feeRecipientAddress === hexUtils.leftPad('0x4', 20));
printer('exchangeAddress', signedOrders[1].exchangeAddress === hexUtils.leftPad('0x5', 20));
printer(
'makerAssetData',
signedOrders[1].makerAssetData === '0xf47261b0000000000000000000000000871dd7c2b4b25e1aa18728e9d5f2af4c4e431f5c',
);
printer('makerAssetAmount', signedOrders[1].makerAssetAmount === '123456789');
printer(
'makerFeeAssetData',
signedOrders[1].makerFeeAssetData ===
'0xf47261b000000000000000000000000034d402f14d58e001d8efbe6585051bf9706aa064',
);
printer('makerFee', signedOrders[1].makerFee === '89');
printer(
'takerAssetData',
signedOrders[1].takerAssetData === '0xf47261b0000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',
);
printer('takerAssetAmount', signedOrders[1].takerAssetAmount === '987654321');
printer(
'takerFeeAssetData',
signedOrders[1].takerFeeAssetData ===
'0xf47261b000000000000000000000000025b8fe1de9daf8ba351890744ff28cf7dfa8f5e3',
);
printer('takerFee', signedOrders[1].takerFee === '12');
printer('expirationTimeSeconds', signedOrders[1].expirationTimeSeconds === '10000000000');
printer('salt', signedOrders[1].salt === '1532559225');
printer(
'signature',
signedOrders[1].signature === '0x012761a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351bc33',
);
}
function testStats(stats: WrapperStats[]): void {
const printer = prettyPrintTestCase('stats', 'RealisticStats');
printer('version', stats[0].version === 'development');
printer('pubSubTopic', stats[0].pubSubTopic === 'someTopic');
printer('rendezvous', stats[0].rendezvous === '/0x-mesh/network/1337/version/2');
printer(
'secondaryRendezvous',
stats[0].secondaryRendezvous.length === 1 &&
stats[0].secondaryRendezvous[0] === '/0x-custom-filter-rendezvous/version/2/chain/1337/schema/someTopic',
);
printer('peerID', stats[0].peerID === '16Uiu2HAmGd949LwaV4KNvK2WDSiMVy7xEmW983VH75CMmefmMpP7');
printer('ethereumChainID', stats[0].ethereumChainID === 1337);
printer('latestBlock | hash', stats[0].latestBlock.hash === hexUtils.leftPad('0x1', 32));
printer('latestBlock | number', stats[0].latestBlock.number === '1500');
printer('numOrders', stats[0].numOrders === 100000);
printer('numPeers', stats[0].numPeers === 200);
printer('numOrdersIncludingRemoved', stats[0].numOrdersIncludingRemoved === 200000);
printer('numPinnedOrders', stats[0].numPinnedOrders === 400);
printer(
'maxExpirationTime',
stats[0].maxExpirationTime === '115792089237316195423570985008687907853269984665640564039457584007913129639935',
);
printer('startOfCurrentUTCDay', stats[0].startOfCurrentUTCDay === '2006-01-01 00:00:00 +0000 UTC');
printer('ethRPCRequestsSentInCurrentUTCDay', stats[0].ethRPCRequestsSentInCurrentUTCDay === 100000);
printer('ethRPCRateLimitExpiredRequests', stats[0].ethRPCRateLimitExpiredRequests === 5000);
}
function testValidationResults(validationResults: WrapperValidationResults[]): void {
let printer = prettyPrintTestCase('validationResults', 'EmptyValidationResults');
printer('accepted.length', validationResults[0].accepted.length === 0);
printer('rejected.length', validationResults[0].rejected.length === 0);
printer = prettyPrintTestCase('validationResults', 'OneAcceptedResult');
printer('accepted.length', validationResults[1].accepted.length === 1);
printer('accepted.orderHash', validationResults[1].accepted[0].orderHash === hexUtils.leftPad('0x1', 32));
printer('accepted.signedOrder.chainId', validationResults[1].accepted[0].signedOrder.chainId === 1337);
printer(
'accepted.signedOrder.makerAddress',
validationResults[1].accepted[0].signedOrder.makerAddress === hexUtils.leftPad('0x1', 20),
);
printer(
'accepted.signedOrder.takerAddress',
validationResults[1].accepted[0].signedOrder.takerAddress === hexUtils.leftPad('0x2', 20),
);
printer(
'accepted.signedOrder.senderAddress',
validationResults[1].accepted[0].signedOrder.senderAddress === hexUtils.leftPad('0x3', 20),
);
printer(
'accepted.signedOrder.feeRecipientAddress',
validationResults[1].accepted[0].signedOrder.feeRecipientAddress === hexUtils.leftPad('0x4', 20),
);
printer(
'accepted.signedOrder.exchangeAddress',
validationResults[1].accepted[0].signedOrder.exchangeAddress === hexUtils.leftPad('0x5', 20),
);
printer(
'accepted.signedOrder.makerAssetData',
validationResults[1].accepted[0].signedOrder.makerAssetData === '0x',
);
printer(
'accepted.signedOrder.makerAssetAmount',
validationResults[1].accepted[0].signedOrder.makerAssetAmount === '0',
);
printer(
'accepted.signedOrder.makerFeeAssetData',
validationResults[1].accepted[0].signedOrder.makerFeeAssetData === '0x',
);
printer('accepted.signedOrder.makerFee', validationResults[1].accepted[0].signedOrder.makerFee === '0');
printer(
'accepted.signedOrder.takerAssetData',
validationResults[1].accepted[0].signedOrder.takerAssetData === '0x',
);
printer(
'accepted.signedOrder.takerAssetAmount',
validationResults[1].accepted[0].signedOrder.takerAssetAmount === '0',
);
printer(
'accepted.signedOrder.takerFeeAssetData',
validationResults[1].accepted[0].signedOrder.takerFeeAssetData === '0x',
);
printer('accepted.signedOrder.takerFee', validationResults[1].accepted[0].signedOrder.takerFee === '0');
printer(
'accepted.signedOrder.expirationTimeSeconds',
validationResults[1].accepted[0].signedOrder.expirationTimeSeconds === '10000000000',
);
printer('accepted.signedOrder.salt', validationResults[1].accepted[0].signedOrder.salt === '1532559225');
printer('accepted.signedOrder.signature', validationResults[1].accepted[0].signedOrder.signature === '0x');
printer('accepted.fillableTakerAssetAmount', validationResults[1].accepted[0].fillableTakerAssetAmount === '0');
printer('accepted.isNew', validationResults[1].accepted[0].isNew);
printer('rejected.length', validationResults[1].rejected.length === 0);
printer = prettyPrintTestCase('validationResults', 'OneRejectedResult');
printer('accepted.length', validationResults[2].accepted.length === 0);
printer('rejected.length', validationResults[2].rejected.length === 1);
printer('rejected.orderHash', validationResults[2].rejected[0].orderHash === hexUtils.leftPad('0x1', 32));
printer('rejected.signedOrder.chainId', validationResults[2].rejected[0].signedOrder.chainId === 1337);
printer(
'rejected.signedOrder.makerAddress',
validationResults[2].rejected[0].signedOrder.makerAddress === hexUtils.leftPad('0x1', 20),
);
printer(
'rejected.signedOrder.takerAddress',
validationResults[2].rejected[0].signedOrder.takerAddress === hexUtils.leftPad('0x2', 20),
);
printer(
'rejected.signedOrder.senderAddress',
validationResults[2].rejected[0].signedOrder.senderAddress === hexUtils.leftPad('0x3', 20),
);
printer(
'rejected.signedOrder.feeRecipientAddress',
validationResults[2].rejected[0].signedOrder.feeRecipientAddress === hexUtils.leftPad('0x4', 20),
);
printer(
'rejected.signedOrder.exchangeAddress',
validationResults[2].rejected[0].signedOrder.exchangeAddress === hexUtils.leftPad('0x5', 20),
);
printer(
'rejected.signedOrder.makerAssetData',
validationResults[2].rejected[0].signedOrder.makerAssetData === '0x',
);
printer(
'rejected.signedOrder.makerAssetAmount',
validationResults[2].rejected[0].signedOrder.makerAssetAmount === '0',
);
printer(
'rejected.signedOrder.makerFeeAssetData',
validationResults[2].rejected[0].signedOrder.makerFeeAssetData === '0x',
);
printer('rejected.signedOrder.makerFee', validationResults[1].accepted[0].signedOrder.makerFee === '0');
printer(
'rejected.signedOrder.takerAssetData',
validationResults[2].rejected[0].signedOrder.takerAssetData === '0x',
);
printer(
'rejected.signedOrder.takerAssetAmount',
validationResults[2].rejected[0].signedOrder.takerAssetAmount === '0',
);
printer(
'rejected.signedOrder.takerFeeAssetData',
validationResults[2].rejected[0].signedOrder.takerFeeAssetData === '0x',
);
printer('rejected.signedOrder.takerFee', validationResults[1].accepted[0].signedOrder.takerFee === '0');
printer(
'rejected.signedOrder.expirationTimeSeconds',
validationResults[2].rejected[0].signedOrder.expirationTimeSeconds === '10000000000',
);
printer('rejected.signedOrder.salt', validationResults[2].rejected[0].signedOrder.salt === '1532559225');
printer('rejected.signedOrder.signature', validationResults[2].rejected[0].signedOrder.signature === '0x');
printer('rejected.kind', validationResults[2].rejected[0].kind === 'ZEROEX_VALIDATION');
printer('rejected.status.code', validationResults[2].rejected[0].status.code === 'OrderHasInvalidMakerAssetData');
printer(
'rejected.status.message',
validationResults[2].rejected[0].status.message ===
'order makerAssetData must encode a supported assetData type',
);
printer = prettyPrintTestCase('validationResults', 'RealisticValidationResults');
// Accepted 1
printer('accepted.length', validationResults[3].accepted.length === 2);
printer('accepted.orderHash', validationResults[3].accepted[0].orderHash === hexUtils.leftPad('0x1', 32));
printer('accepted.signedOrder.chainId', validationResults[3].accepted[0].signedOrder.chainId === 1337);
printer(
'accepted.signedOrder.makerAddress',
validationResults[3].accepted[0].signedOrder.makerAddress === hexUtils.leftPad('0x1', 20),
);
printer(
'accepted.signedOrder.takerAddress',
validationResults[3].accepted[0].signedOrder.takerAddress === hexUtils.leftPad('0x2', 20),
);
printer(
'accepted.signedOrder.senderAddress',
validationResults[3].accepted[0].signedOrder.senderAddress === hexUtils.leftPad('0x3', 20),
);
printer(
'accepted.signedOrder.feeRecipientAddress',
validationResults[3].accepted[0].signedOrder.feeRecipientAddress === hexUtils.leftPad('0x4', 20),
);
printer(
'accepted.signedOrder.exchangeAddress',
validationResults[3].accepted[0].signedOrder.exchangeAddress === hexUtils.leftPad('0x5', 20),
);
printer(
'accepted.signedOrder.makerAssetData',
validationResults[3].accepted[0].signedOrder.makerAssetData === '0x',
);
printer(
'accepted.signedOrder.makerAssetAmount',
validationResults[3].accepted[0].signedOrder.makerAssetAmount === '0',
);
printer(
'accepted.signedOrder.makerFeeAssetData',
validationResults[3].accepted[0].signedOrder.makerFeeAssetData === '0x',
);
printer('accepted.signedOrder.makerFee', validationResults[3].accepted[0].signedOrder.makerFee === '0');
printer(
'accepted.signedOrder.takerAssetData',
validationResults[3].accepted[0].signedOrder.takerAssetData === '0x',
);
printer(
'accepted.signedOrder.takerAssetAmount',
validationResults[3].accepted[0].signedOrder.takerAssetAmount === '0',
);
printer(
'accepted.signedOrder.takerFeeAssetData',
validationResults[3].accepted[0].signedOrder.takerFeeAssetData === '0x',
);
printer('accepted.signedOrder.takerFee', validationResults[3].accepted[0].signedOrder.takerFee === '0');
printer(
'accepted.signedOrder.expirationTimeSeconds',
validationResults[3].accepted[0].signedOrder.expirationTimeSeconds === '10000000000',
);
printer('accepted.signedOrder.salt', validationResults[3].accepted[0].signedOrder.salt === '1532559225');
printer('accepted.signedOrder.signature', validationResults[3].accepted[0].signedOrder.signature === '0x');
printer('accepted.fillableTakerAssetAmount', validationResults[3].accepted[0].fillableTakerAssetAmount === '0');
printer('accepted.isNew', validationResults[3].accepted[0].isNew);
// Accepted 2
printer('accepted.orderHash', validationResults[3].accepted[1].orderHash === hexUtils.leftPad('0x1', 32));
printer('accepted.signedOrder.chainId', validationResults[3].accepted[1].signedOrder.chainId === 1337);
printer(
'accepted.signedOrder.makerAddress',
validationResults[3].accepted[1].signedOrder.makerAddress === hexUtils.leftPad('0x1', 20),
);
printer(
'accepted.signedOrder.takerAddress',
validationResults[3].accepted[1].signedOrder.takerAddress === hexUtils.leftPad('0x2', 20),
);
printer(
'accepted.signedOrder.senderAddress',
validationResults[3].accepted[1].signedOrder.senderAddress === hexUtils.leftPad('0x3', 20),
);
printer(
'accepted.signedOrder.feeRecipientAddress',
validationResults[3].accepted[1].signedOrder.feeRecipientAddress === hexUtils.leftPad('0x4', 20),
);
printer(
'accepted.signedOrder.exchangeAddress',
validationResults[3].accepted[1].signedOrder.exchangeAddress === hexUtils.leftPad('0x5', 20),
);
printer(
'accepted.signedOrder.makerAssetData',
validationResults[3].accepted[1].signedOrder.makerAssetData ===
'0xf47261b0000000000000000000000000871dd7c2b4b25e1aa18728e9d5f2af4c4e431f5c',
);
printer(
'accepted.signedOrder.makerAssetAmount',
validationResults[3].accepted[1].signedOrder.makerAssetAmount === '123456789',
);
printer(
'accepted.signedOrder.makerFeeAssetData',
validationResults[3].accepted[1].signedOrder.makerFeeAssetData ===
'0xf47261b000000000000000000000000034d402f14d58e001d8efbe6585051bf9706aa064',
);
printer('accepted.signedOrder.makerFee', validationResults[3].accepted[1].signedOrder.makerFee === '89');
printer(
'accepted.signedOrder.takerAssetData',
validationResults[3].accepted[1].signedOrder.takerAssetData ===
'0xf47261b0000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',
);
printer(
'accepted.signedOrder.takerAssetAmount',
validationResults[3].accepted[1].signedOrder.takerAssetAmount === '987654321',
);
printer(
'accepted.signedOrder.takerFeeAssetData',
validationResults[3].accepted[1].signedOrder.takerFeeAssetData ===
'0xf47261b000000000000000000000000025b8fe1de9daf8ba351890744ff28cf7dfa8f5e3',
);
printer('accepted.signedOrder.takerFee', validationResults[3].accepted[1].signedOrder.takerFee === '12');
printer(
'accepted.signedOrder.expirationTimeSeconds',
validationResults[3].accepted[1].signedOrder.expirationTimeSeconds === '10000000000',
);
printer('accepted.signedOrder.salt', validationResults[3].accepted[1].signedOrder.salt === '1532559225');
printer(
'accepted.signedOrder.signature',
validationResults[3].accepted[1].signedOrder.signature ===
'0x012761a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351bc33',
);
printer(
'accepted.fillableTakerAssetAmount',
validationResults[3].accepted[1].fillableTakerAssetAmount === '987654321',
);
printer('accepted.isNew', validationResults[3].accepted[1].isNew);
// Rejected 1
printer('rejected.length', validationResults[3].rejected.length === 1);
printer('rejected.orderHash', validationResults[3].rejected[0].orderHash === hexUtils.leftPad('0x1', 32));
printer('rejected.signedOrder.chainId', validationResults[3].rejected[0].signedOrder.chainId === 1337);
printer(
'rejected.signedOrder.makerAddress',
validationResults[3].rejected[0].signedOrder.makerAddress === hexUtils.leftPad('0x1', 20),
);
printer(
'rejected.signedOrder.takerAddress',
validationResults[3].rejected[0].signedOrder.takerAddress === hexUtils.leftPad('0x2', 20),
);
printer(
'rejected.signedOrder.senderAddress',
validationResults[3].rejected[0].signedOrder.senderAddress === hexUtils.leftPad('0x3', 20),
);
printer(
'rejected.signedOrder.feeRecipientAddress',
validationResults[3].rejected[0].signedOrder.feeRecipientAddress === hexUtils.leftPad('0x4', 20),
);
printer(
'rejected.signedOrder.exchangeAddress',
validationResults[3].rejected[0].signedOrder.exchangeAddress === hexUtils.leftPad('0x5', 20),
);
printer(
'rejected.signedOrder.makerAssetData',
validationResults[3].rejected[0].signedOrder.makerAssetData ===
'0xf47261b0000000000000000000000000871dd7c2b4b25e1aa18728e9d5f2af4c4e431f5c',
);
printer(
'rejected.signedOrder.makerAssetAmount',
validationResults[3].rejected[0].signedOrder.makerAssetAmount === '123456789',
);
printer(
'rejected.signedOrder.makerFeeAssetData',
validationResults[3].rejected[0].signedOrder.makerFeeAssetData ===
'0xf47261b000000000000000000000000034d402f14d58e001d8efbe6585051bf9706aa064',
);
printer('rejected.signedOrder.makerFee', validationResults[3].rejected[0].signedOrder.makerFee === '89');
printer(
'rejected.signedOrder.takerAssetData',
validationResults[3].rejected[0].signedOrder.takerAssetData ===
'0xf47261b0000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',
);
printer(
'rejected.signedOrder.takerAssetAmount',
validationResults[3].rejected[0].signedOrder.takerAssetAmount === '987654321',
);
printer(
'rejected.signedOrder.takerFeeAssetData',
validationResults[3].rejected[0].signedOrder.takerFeeAssetData ===
'0xf47261b000000000000000000000000025b8fe1de9daf8ba351890744ff28cf7dfa8f5e3',
);
printer('rejected.signedOrder.takerFee', validationResults[3].rejected[0].signedOrder.takerFee === '12');
printer(
'rejected.signedOrder.expirationTimeSeconds',
validationResults[3].rejected[0].signedOrder.expirationTimeSeconds === '10000000000',
);
printer('rejected.signedOrder.salt', validationResults[3].rejected[0].signedOrder.salt === '1532559225');
printer(
'rejected.signedOrder.signature',
validationResults[3].rejected[0].signedOrder.signature ===
'0x012761a3ed31b43c8780e905a260a35faefcc527be7516aa11c0256729b5b351bc33',
);
printer('rejected.kind', validationResults[3].rejected[0].kind === 'MESH_ERROR');
printer('rejected.status.code', validationResults[3].rejected[0].status.code === 'EthRPCRequestFailed');
printer(
'rejected.status.message',
validationResults[3].rejected[0].status.message === 'network request to Ethereum RPC endpoint failed',
);
}
// tslint:enable:no-console
// tslint:enable:custom-no-magic-numbers
/*********************** Utils ***********************/
async function waitForLoadAsync(): Promise<void> {
// Note: this approach is not CPU efficient but it avoids race
// conditions and has the advantage of returning instantaneously if the
// Wasm code has already loaded.
while (!isWasmLoaded) {
await sleepAsync(wasmLoadCheckIntervalMs);
}
}
async function sleepAsync(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// tslint:disable-line:max-file-line-count | the_stack |
import { ICrmDataProvider } from './ICrmDataProvider';
import { ISPField } from '../data/ISPField';
import { ISPView } from '../data/ISPView';
import { ISPUser } from '../data/ISPUser';
import { ISharePointItem } from '../data/ISharePointItem';
import { IPerson } from '../data/IPerson';
import { IOrganization } from '../data/IOrganization';
import { IOrganizationSet } from './IOrganizationSet';
import OrganizationSet from './OrganizationSet';
import { DataProviderErrorCodes } from './DataError';
import { ITag } from '../data/ITag';
import { ITagSet } from './ITagSet';
import { BaseCrmDataProvider } from './BaseCrmDataProvider';
import { IEvent } from '../utilities/Events';
import { sp } from '../pnp-preset';
import { IWebPartContext } from '@microsoft/sp-webpart-base';
import { IItemAddResult, IItemUpdateResult, IItems } from '@pnp/sp/items';
import { IListInfo } from '@pnp/sp/lists';
import { IFieldInfo } from '@pnp/sp/fields';
export default class SharePointCrmDataProvider extends BaseCrmDataProvider implements ICrmDataProvider {
private _meUserLoginName: string;
private _personFieldListSelect = "$select=Id,Title,FirstName,Company,OrganizationId";
private _organizationFieldListSelect = "$select=Id,Title";
public get meUserLoginName(): string { return this._meUserLoginName; }
public set meUserLoginName(newValue: string) {
this._meUserLoginName = newValue;
}
constructor(context: IWebPartContext) {
super();
sp.setup(context);
sp.configure({
headers: [
['X-ClientTag', 'SPCommunityCrmWebPart']
]
});
this._idCounter = 0;
}
public updateAll(): Promise<boolean> {
return new Promise<boolean>((resolve) => { resolve(true); });
}
private _addPersonItem(person: IPerson): Promise<IItemAddResult> {
return sp.web
.lists.getByTitle('Contacts')
.items.add(person, this._selectedPersonList.ListItemEntityTypeFullName);
}
private _getUsers(filter: string): Promise<ISPUser[]> {
return sp.web.siteUserInfoList
.items.filter(filter).get();
}
private _getPersonItems(filter?: string, orderBy?: string, orderAsc?: boolean, top?: number): Promise<IPerson[]> {
let personItems: IItems = sp.web
.lists.getByTitle('Contacts')
.items.select('Id', 'Title', 'FirstName', 'Company', 'OrganizationId');
if (filter) {
personItems = personItems.filter(filter);
}
if (orderBy) {
personItems = personItems.orderBy(orderBy, orderAsc);
}
if (top) {
personItems = personItems.top(top);
}
return personItems.get();
}
private _fixupItem(item: ISharePointItem) {
// for lookup fields, make sure "FooStringId" matches the value of "FooId" so that updates don't get confused.
for (var key in item) {
if (key.length >= 9 && key.substring(key.length - 8, key.length) == "StringId") {
if (item[key.substring(0, key.length - 8) + "Id"] != null) {
item[key] = item[key.substring(0, key.length - 8) + "Id"].toString();
}
else {
item[key] = null;
}
}
}
}
private _updatePersonItem(item: IPerson): Promise<IItemUpdateResult> {
return sp.web
.lists.getByTitle('Contacts')
.items.getById(item.Id).update(item, '*', this._selectedPersonList.ListItemEntityTypeFullName);
}
public addPersonItem(newPerson: IPerson): Promise<IPerson[]> {
return new Promise<IPerson[]>((resolve: (people: IPerson[]) => void, reject: (error: any) => void): void => {
this
._addPersonItem(newPerson)
.then((): Promise<IPerson[]> => {
return this._getPersonItems(undefined, 'Created', false, 1);
})
.then((people: IPerson[]): void => {
this._onPersonAdded.dispatch(this, newPerson);
resolve(people);
});
});
}
public notifyPersonChanged(person: IPerson) {
this._onPersonChanged.dispatch(this, person);
}
public readUsersByIds(ids: number[]): Promise<ISPUser[]> {
var query = "";
for (var id of ids) {
if (query.length > 0) {
query += " or ";
}
query += "Id eq " + id;
}
return this._getUsers(query);
}
public readUsersByUserName(userName: string): Promise<ISPUser[]> {
return this._getUsers(`substringof('${userName}', Name)`);
}
public readUsersBySearch(search: string): Promise<ISPUser[]> {
return this._getUsers("substringof('" + search + "', Title)");
}
public readPersonItemsBySearch(search: string): Promise<IPerson[]> {
return this._getPersonItems("substringof('" + search + "', Full_x0020_Name)");
}
public readPersonItems(): Promise<IPerson[]> {
return this._getPersonItems(null);
}
public readPersonItemsByOrganizationId(organizationId: number): Promise<IPerson[]> {
return this._getPersonItems("OrganizationId eq " + organizationId);
}
public readPersonItemsByIds(ids: number[]): Promise<IPerson[]> {
var searchQuery = "";
for (var id of ids) {
if (searchQuery.length > 0) {
searchQuery += " or ";
}
searchQuery += "Id eq " + id.toString();
}
return this._getPersonItems(searchQuery);
}
public get onPersonAdded(): IEvent<ICrmDataProvider, IPerson> {
return this._onPersonAdded.asEvent();
}
public get onPersonChanged(): IEvent<ICrmDataProvider, IPerson> {
return this._onPersonChanged.asEvent();
}
public get onPersonRemoved(): IEvent<ICrmDataProvider, IPerson> {
return this._onPersonRemoved.asEvent();
}
public updatePersonItem(itemUpdated: IPerson): Promise<IPerson[]> {
return new Promise<IPerson[]>((resolve: (people: IPerson[]) => void, reject: (error: any) => void): void => {
this
._updatePersonItem(itemUpdated)
.then((): Promise<IPerson[]> => {
return this._getPersonItems(undefined, 'Modified', false, 1);
})
.then((people: IPerson[]): void => {
resolve(people);
});
});
}
public deletePersonItem(itemDeleted: IPerson): Promise<IPerson[]> {
return this.readPersonItems();
}
public get onOrganizationAdded(): IEvent<ICrmDataProvider, IOrganization> {
return this._onOrganizationAdded.asEvent();
}
public get onOrganizationChanged(): IEvent<ICrmDataProvider, IOrganization> {
return this._onOrganizationChanged.asEvent();
}
public get onOrganizationRemoved(): IEvent<ICrmDataProvider, IOrganization> {
return this._onOrganizationRemoved.asEvent();
}
public get onTagAdded(): IEvent<ICrmDataProvider, ITag> {
return this._onTagAdded.asEvent();
}
public get onTagChanged(): IEvent<ICrmDataProvider, ITag> {
return this._onTagChanged.asEvent();
}
public get onTagRemoved(): IEvent<ICrmDataProvider, ITag> {
return this._onTagRemoved.asEvent();
}
private _addTagItem(tag: ITag): Promise<IItemAddResult> {
return sp.web
.lists.getByTitle('Tags')
.items.add(tag, this.selectedTagList.ListItemEntityTypeFullName);
}
public init(): Promise<void> {
return this._loadListData();
}
private _loadListData(): Promise<void> {
const orgListDataPromise = sp.web
.lists.getByTitle('Organizations').select('Id').get()
.then((list: IListInfo): void => {
this._selectedOrganizationList.Id = list.Id;
}, _ => {
this.pushError("The Organization list was not found.", DataProviderErrorCodes.OrganizationListDoesNotExist);
});
const tagsListDataPromise = sp.web
.lists.getByTitle('Tags').select('Id').get()
.then((list: IListInfo): void => {
this._selectedTagList.Id = list.Id;
});
const meUserListDataPromise = sp.web.siteUserInfoList
.items.filter(`substringof('${this.meUserLoginName}', Name)`).get()
.then(items => {
if (items.length > 0) {
this.meUser = items[0];
}
});
const orgListFieldDataPromise = sp.web
.lists.getByTitle('Organizations')
.fields
.filter("Hidden eq false and FieldTypeKind ne 12 and InternalName ne 'AppEditor' and InternalName ne 'AppAuthor'")
.select('ID', 'InternalName', 'Title', 'FieldTypeKind', 'Choices', 'RichText', 'AllowMultipleValues', 'MaxLength', 'LookupList')
.get()
.then((fields: IFieldInfo[]): void => {
this._organizationFieldListSelect = "?$select=";
for (let listField of fields) {
this._organizationFieldListSelect += listField.InternalName + ", ";
}
this._organizationFieldListSelect = this._organizationFieldListSelect.substring(0, this._organizationFieldListSelect.length - 2);
this._selectedOrganizationList.Fields = (fields as any) as ISPField[];
});
const personListFieldDataPromise = sp.web
.lists.getByTitle('Contacts')
.fields
.filter("Hidden eq false and FieldTypeKind ne 12 and InternalName ne 'AppEditor' and InternalName ne 'AppAuthor'")
.select('ID', 'InternalName', 'Title', 'FieldTypeKind', 'Choices', 'RichText', 'AllowMultipleValues', 'MaxLength', 'LookupList')
.get()
.then((fields: IFieldInfo[]): void => {
this._personFieldListSelect = "?$select=";
for (let listField of fields) {
this._personFieldListSelect += listField.InternalName + ", ";
}
this._personFieldListSelect = this._personFieldListSelect.substring(0, this._personFieldListSelect.length - 2);
this._selectedPersonList.Fields = (fields as any) as ISPField[];
});
const promises: Promise<void>[] = [
orgListDataPromise,
tagsListDataPromise,
orgListFieldDataPromise,
meUserListDataPromise,
personListFieldDataPromise
];
return Promise
.all(promises)
.then((): void => {
this.validate();
});
}
private _getOrganizationItems(query: string, orderBy: string, orderAsc?: boolean): Promise<IOrganizationSet> {
let organizationItems: IItems = sp.web
.lists.getByTitle('Organizations')
.items
.select('Id', 'Title');
if (query) {
organizationItems = organizationItems.filter(query);
}
if (orderBy) {
organizationItems = organizationItems.orderBy(orderBy, orderAsc);
}
return organizationItems
.get()
.then((organizations: IOrganization[]) => {
let orgSet = this._ensureOrganizationSet(query + "|" + orderBy);
this.notifyOrganizationsChanged(organizations, orgSet);
return orgSet;
})
.catch(_ => {
this.pushError("Couldn't retrieve lists for the app.", DataProviderErrorCodes.Unknown);
return null;
});
}
private _updateOrganizationItem(item: IOrganization): Promise<IItemUpdateResult> {
return sp.web
.lists.getByTitle('Organizations')
.items.getById(item.Id)
.update(item, '*', this._selectedOrganizationList.ListItemEntityTypeFullName);
}
public addOrganizationItem(newOrganization: IOrganization): Promise<IOrganizationSet> {
this._fixupItem(newOrganization);
return new Promise<IOrganizationSet>((resolve: (organizationSet: IOrganizationSet) => void, reject: (error: any) => void): void => {
this
._addOrganizationItem(newOrganization)
.then((): Promise<IOrganizationSet> => {
return this._getOrganizationItems(null, 'Created', false);
})
.then((organizationSet: OrganizationSet): void => {
resolve(organizationSet);
}, (err: any): void => {
reject(err);
});
});
}
public notifyOrganizationChanged(person: IOrganization) {
this._onOrganizationChanged.dispatch(this, person);
}
public readOrganizationItemsByView(view: ISPView): Promise<IOrganizationSet> {
var query = "";
if (view.query != null) {
query = view.query.getOdataQuery(this.selectedOrganizationList);
}
return this._getOrganizationItems(query, null);
}
public readOrganizationItemsByPriority(priority: number): Promise<IOrganizationSet> {
if (priority > 20) {
return this._getOrganizationItems("Organizational_x0020_Priority gt " + priority + " or Organizational_x0020_Priority eq null", null);
}
else {
return this._getOrganizationItems("Organizational_x0020_Priority eq " + priority, null);
}
}
public readOrganizationItemsBySearch(search: string, tagItemIds: number[]): Promise<IOrganizationSet> {
var tagItemQuery = "";
var searchQuery = "";
if (tagItemIds != null) {
for (var tagItemId of tagItemIds) {
tagItemQuery += " or Tags eq " + tagItemId;
}
}
if (search.length >= 3) {
searchQuery = "substringof('" + search + "', Title)";
}
if (tagItemQuery.length > 0 && searchQuery.length == 0) {
tagItemQuery = tagItemQuery.substring(4, tagItemQuery.length);
}
return this._getOrganizationItems(searchQuery + tagItemQuery, null);
}
public readOrganizationItems(): Promise<IOrganizationSet> {
return this._getOrganizationItems(null, null);
}
public readOrganizationItemsByIds(ids: number[]): Promise<IOrganizationSet> {
var searchQuery = "";
for (var id of ids) {
if (searchQuery.length > 0) {
searchQuery += " or ";
}
searchQuery += "Id eq " + id.toString();
}
return this._getOrganizationItems(searchQuery, null);
}
public readRecentOrganizationItems(): Promise<IOrganizationSet> {
return this._getOrganizationItems(null, "Modified", false);
}
public readMyOrganizationItems(): Promise<IOrganizationSet> {
return this.readOrganizationItems();
}
public updateOrganizationItem(itemUpdated: IOrganization): Promise<IOrganizationSet> {
return new Promise<IOrganizationSet>((resolve: (organizationSet: IOrganizationSet) => void, reject: (error: any) => void): void => {
this
._updateOrganizationItem(itemUpdated)
.then((): Promise<IOrganizationSet> => {
return this._getOrganizationItems(null, "Modified", false);
})
.then((organizationSet: IOrganizationSet): void => {
resolve(organizationSet);
}, (err: any): void => {
reject(err);
});
});
}
public deleteOrganizationItem(itemDeleted: IOrganization): Promise<IOrganizationSet> {
return this.readOrganizationItems();
}
private _getTagItems(query: string, orderBy: string, orderAsc?: boolean): Promise<ITagSet> {
return sp.web
.lists.getByTitle('Tags')
.items
.filter(query)
.orderBy(orderBy, orderAsc)
.select('Id', 'Title', 'Description')
.get()
.then((tags: ITag[]) => {
let tagSet = this._ensureTagSet(query + "|" + orderBy);
this.notifyTagsChanged(tags, tagSet);
return tagSet;
});
}
private _updateTagItem(item: ITag): Promise<IItemUpdateResult> {
return sp.web
.lists.getByTitle('Organizations')
.items.getById(item.Id)
.update(item, this._selectedTagList.ListItemEntityTypeFullName);
}
private _addOrganizationItem(organization: IOrganization): Promise<IItemAddResult> {
return sp.web
.lists.getByTitle('Organizations')
.items.add(organization, this.selectedOrganizationList.ListItemEntityTypeFullName);
}
public addTagItem(newTag: ITag): Promise<ITagSet> {
return new Promise<ITagSet>((resolve: (tagItem: ITagSet) => void, reject: (error: any) => void): void => {
this
._addTagItem(newTag)
.then((): Promise<ITagSet> => {
return this._getTagItems(null, "Created", false);
})
.then((tagSet: ITagSet): void => {
resolve(tagSet);
}, (err: any): void => {
reject(err);
});
});
}
public notifyTagChanged(person: ITag) {
this._onTagChanged.dispatch(this, person);
}
public readTagItemsBySearch(search: string): Promise<ITagSet> {
return this._getTagItems("substringof('" + search + "', Title)", null);
}
public readTagItems(): Promise<ITagSet> {
return this._getTagItems(null, null);
}
public readTagItemsByIds(ids: number[]): Promise<ITagSet> {
var searchQuery = "";
for (var id of ids) {
if (searchQuery.length > 0) {
searchQuery += " or ";
}
searchQuery += "Id eq " + id.toString();
}
return this._getTagItems(searchQuery, null);
}
public readRecentTagItems(): Promise<ITagSet> {
return this._getTagItems(null, "Modified", false);
}
public readMyTagItems(): Promise<ITagSet> {
return this.readTagItems();
}
public updateTagItem(itemUpdated: ITag): Promise<ITagSet> {
return new Promise<ITagSet>((resolve: (tagSet: ITagSet) => void, reject: (error: any) => void): void => {
this
._updateTagItem(itemUpdated)
.then((): Promise<ITagSet> => {
return this._getTagItems(null, "Modified", false);
})
.then((tagSet: ITagSet): void => {
resolve(tagSet);
}, (err: any): void => {
reject(err);
});
});
}
public deleteTagItem(itemDeleted: ITag): Promise<ITagSet> {
return this.readTagItems();
}
} | the_stack |
// Type definitions for socket.io 1.3.5
// Project: http://socket.io/
// Definitions by: PROGRE <https://github.com/progre/>, Damian Connolly <https://github.com/divillysausages/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
///<reference path='../node/node.d.ts' />
declare module 'socket.io' {
var server: SocketIOStatic;
export = server;
}
interface SocketIOStatic {
/**
* Default Server constructor
*/
(): SocketIO.Server;
/**
* Creates a new Server
* @param srv The HTTP server that we're going to bind to
* @param opts An optional parameters object
*/
(srv: any, opts?: SocketIO.ServerOptions): SocketIO.Server;
/**
* Creates a new Server
* @param port A port to bind to, as a number, or a string
* @param An optional parameters object
*/
(port: string|number, opts?: SocketIO.ServerOptions): SocketIO.Server;
/**
* Creates a new Server
* @param A parameters object
*/
(opts: SocketIO.ServerOptions): SocketIO.Server;
/**
* Backwards compatibility
* @see io().listen()
*/
listen: SocketIOStatic;
}
declare module SocketIO {
interface Server {
/**
* A dictionary of all the namespaces currently on this Server
*/
nsps: {[namespace: string]: Namespace};
/**
* The default '/' Namespace
*/
sockets: Namespace;
/**
* Sets the 'json' flag when emitting an event
*/
json: Server;
/**
* Server request verification function, that checks for allowed origins
* @param req The http.IncomingMessage request
* @param fn The callback to be called. It should take one parameter, err,
* which will be null if there was no problem, and one parameter, success,
* of type boolean
*/
checkRequest( req:any, fn:( err: any, success: boolean ) => void ):void;
/**
* Gets whether we're serving the client.js file or not
* @default true
*/
serveClient(): boolean;
/**
* Sets whether we're serving the client.js file or not
* @param v True if we want to serve the file, false otherwise
* @default true
* @return This Server
*/
serveClient( v: boolean ): Server;
/**
* Gets the client serving path
* @default '/socket.io'
*/
path(): string;
/**
* Sets the client serving path
* @param v The path to serve the client file on
* @default '/socket.io'
* @return This Server
*/
path( v: string ): Server;
/**
* Gets the adapter that we're going to use for handling rooms
* @default typeof Adapter
*/
adapter(): any;
/**
* Sets the adapter (class) that we're going to use for handling rooms
* @param v The class for the adapter to create
* @default typeof Adapter
* @return This Server
*/
adapter( v: any ): Server;
/**
* Gets the allowed origins for requests
* @default "*:*"
*/
origins(): string;
/**
* Sets the allowed origins for requests
* @param v The allowed origins, in host:port form
* @default "*:*"
* return This Server
*/
origins( v: string ): Server;
/**
* Attaches socket.io to a server
* @param srv The http.Server that we want to attach to
* @param opts An optional parameters object
* @return This Server
*/
attach( srv: any, opts?: ServerOptions ): Server;
/**
* Attaches socket.io to a port
* @param port The port that we want to attach to
* @param opts An optional parameters object
* @return This Server
*/
attach( port: number, opts?: ServerOptions ): Server;
/**
* @see attach( srv, opts )
*/
listen( srv: any, opts?: ServerOptions ): Server;
/**
* @see attach( port, opts )
*/
listen( port: number, opts?: ServerOptions ): Server;
/**
* Binds socket.io to an engine.io intsance
* @param src The Engine.io (or compatible) server to bind to
* @return This Server
*/
bind( srv: any ): Server;
/**
* Called with each incoming connection
* @param socket The Engine.io Socket
* @return This Server
*/
onconnection( socket: any ): Server;
/**
* Looks up/creates a Namespace
* @param nsp The name of the NameSpace to look up/create. Should start
* with a '/'
* @return The Namespace
*/
of( nsp: string ): Namespace;
/**
* Closes the server connection
*/
close():void;
/**
* The event fired when we get a new connection
* @param event The event being fired: 'connection'
* @param listener A listener that should take one parameter of type Socket
* @return The default '/' Namespace
*/
on( event: 'connection', listener: ( socket: Socket ) => void ): Namespace;
/**
* @see on( 'connection', listener )
*/
on( event: 'connect', listener: ( socket: Socket ) => void ): Namespace;
/**
* Base 'on' method to add a listener for an event
* @param event The event that we want to add a listener for
* @param listener The callback to call when we get the event. The parameters
* for the callback depend on the event
* @return The default '/' Namespace
*/
on( event: string, listener: Function ): Namespace;
/**
* Targets a room when emitting to the default '/' Namespace
* @param room The name of the room that we're targeting
* @return The default '/' Namespace
*/
to( room: string ): Namespace;
/**
* @see to( room )
*/
in( room: string ): Namespace;
/**
* Registers a middleware function, which is a function that gets executed
* for every incoming Socket, on the default '/' Namespace
* @param fn The function to call when we get a new incoming socket. It should
* take one parameter of type Socket, and one callback function to call to
* execute the next middleware function. The callback can take one optional
* parameter, err, if there was an error. Errors passed to middleware callbacks
* are sent as special 'error' packets to clients
* @return The default '/' Namespace
*/
use( fn: ( socket:Socket, fn: ( err?: any ) => void ) =>void ): Namespace;
/**
* Emits an event to the default Namespace
* @param event The event that we want to emit
* @param args Any number of optional arguments to pass with the event. If the
* last argument is a function, it will be called as an ack. The ack should
* take whatever data was sent with the packet
* @return The default '/' Namespace
*/
emit( event: string, ...args: any[]): Namespace;
/**
* Sends a 'message' event
* @see emit( event, ...args )
* @return The default '/' Namespace
*/
send( ...args: any[] ): Namespace;
/**
* @see send( ...args )
*/
write( ...args: any[] ): Namespace;
}
/**
* Options to pass to our server when creating it
*/
interface ServerOptions {
/**
* The path to server the client file to
* @default '/socket.io'
*/
path?: string;
/**
* Should we serve the client file?
* @default true
*/
serveClient?: boolean;
/**
* The adapter to use for handling rooms. NOTE: this should be a class,
* not an object
* @default typeof Adapter
*/
adapter?: Adapter;
/**
* Accepted origins
* @default '*:*'
*/
origins?: string;
/**
* How many milliseconds without a pong packed to consider the connection closed (engine.io)
* @default 60000
*/
pingTimeout?: number;
/**
* How many milliseconds before sending a new ping packet (keep-alive) (engine.io)
* @default 25000
*/
pingInterval?: number;
/**
* How many bytes or characters a message can be when polling, before closing the session
* (to avoid Dos) (engine.io)
* @default 10E7
*/
maxHttpBufferSize?: number;
/**
* A function that receives a given handshake or upgrade request as its first parameter,
* and can decide whether to continue or not. The second argument is a function that needs
* to be called with the decided information: fn( err, success ), where success is a boolean
* value where false means that the request is rejected, and err is an error code (engine.io)
* @default null
*/
allowRequest?: (request:any, callback: (err: number, success: boolean) => void) => void;
/**
* Transports to allow connections to (engine.io)
* @default ['polling','websocket']
*/
transports?: string[];
/**
* Whether to allow transport upgrades (engine.io)
* @default true
*/
allowUpgrades?: boolean;
/**
* parameters of the WebSocket permessage-deflate extension (see ws module).
* Set to false to disable (engine.io)
* @default true
*/
perMessageDeflate?: Object|boolean;
/**
* Parameters of the http compression for the polling transports (see zlib).
* Set to false to disable, or set an object with parameter "threshold:number"
* to only compress data if the byte size is above this value (1024) (engine.io)
* @default true|1024
*/
httpCompression?: Object|boolean;
/**
* Name of the HTTP cookie that contains the client sid to send as part of
* handshake response headers. Set to false to not send one (engine.io)
* @default "io"
*/
cookie?: string|boolean;
}
/**
* The Namespace, sandboxed environments for sockets, each connection
* to a Namespace requires a new Socket
*/
interface Namespace extends NodeJS.EventEmitter {
/**
* The name of the NameSpace
*/
name: string;
/**
* The controller Server for this Namespace
*/
server: Server;
/**
* A list of all the Sockets connected to this Namespace
*/
sockets: Socket[];
/**
* A dictionary of all the Sockets connected to this Namespace, where
* the Socket ID is the key
*/
connected: { [id: string]: Socket };
/**
* The Adapter that we're using to handle dealing with rooms etc
*/
adapter: Adapter;
/**
* Sets the 'json' flag when emitting an event
*/
json: Namespace;
/**
* Registers a middleware function, which is a function that gets executed
* for every incoming Socket
* @param fn The function to call when we get a new incoming socket. It should
* take one parameter of type Socket, and one callback function to call to
* execute the next middleware function. The callback can take one optional
* parameter, err, if there was an error. Errors passed to middleware callbacks
* are sent as special 'error' packets to clients
* @return This Namespace
*/
use( fn: ( socket:Socket, fn: ( err?: any ) => void ) =>void ): Namespace;
/**
* Targets a room when emitting
* @param room The name of the room that we're targeting
* @return This Namespace
*/
to( room: string ): Namespace;
/**
* @see to( room )
*/
in( room: string ): Namespace;
/**
* Sends a 'message' event
* @see emit( event, ...args )
* @return This Namespace
*/
send( ...args: any[] ): Namespace;
/**
* @see send( ...args )
*/
write( ...args: any[] ): Namespace;
/**
* The event fired when we get a new connection
* @param event The event being fired: 'connection'
* @param listener A listener that should take one parameter of type Socket
* @return This Namespace
*/
on( event: 'connection', listener: ( socket: Socket ) => void ): Namespace;
/**
* @see on( 'connection', listener )
*/
on( event: 'connect', listener: ( socket: Socket ) => void ): Namespace;
/**
* Base 'on' method to add a listener for an event
* @param event The event that we want to add a listener for
* @param listener The callback to call when we get the event. The parameters
* for the callback depend on the event
* @ This Namespace
*/
on( event: string, listener: Function ): Namespace;
}
/**
* The socket, which handles our connection for a namespace. NOTE: while
* we technically extend NodeJS.EventEmitter, we're not putting it here
* as we have a problem with the emit() event (as it's overridden with a
* different return)
*/
interface Socket {
/**
* The namespace that this socket is for
*/
nsp: Namespace;
/**
* The Server that our namespace is in
*/
server: Server;
/**
* The Adapter that we use to handle our rooms
*/
adapter: Adapter;
/**
* The unique ID for this Socket. Regenerated at every connection. This is
* also the name of the room that the Socket automatically joins on connection
*/
id: string;
/**
* The http.IncomingMessage request sent with the connection. Useful
* for recovering headers etc
*/
request: any;
/**
* The Client associated with this Socket
*/
client: Client;
/**
* The underlying Engine.io Socket instance
*/
conn: {
/**
* The ID for this socket - matches Client.id
*/
id: string;
/**
* The Engine.io Server for this socket
*/
server: any;
/**
* The ready state for the client. Either 'opening', 'open', 'closing', or 'closed'
*/
readyState: string;
/**
* The remote IP for this connection
*/
remoteAddress: string;
};
/**
* The list of rooms that this Socket is currently in
*/
rooms: string[];
/**
* Is the Socket currently connected?
*/
connected: boolean;
/**
* Is the Socket currently disconnected?
*/
disconnected: boolean;
/**
* The object used when negociating the handshake
*/
handshake: {
/**
* The headers passed along with the request. e.g. 'host',
* 'connection', 'accept', 'referer', 'cookie'
*/
headers: any;
/**
* The current time, as a string
*/
time: string;
/**
* The remote address of the connection request
*/
address: string;
/**
* Is this a cross-domain request?
*/
xdomain: boolean;
/**
* Is this a secure request?
*/
secure: boolean;
/**
* The timestamp for when this was issued
*/
issued: number;
/**
* The request url
*/
url: string;
/**
* Any query string parameters in the request url
*/
query: any;
};
/**
* Sets the 'json' flag when emitting an event
*/
json: Socket;
/**
* Sets the 'volatile' flag when emitting an event. Volatile messages are
* messages that can be dropped because of network issues and the like. Use
* for high-volume/real-time messages where you don't need to receive *all*
* of them
*/
volatile: Socket;
/**
* Sets the 'broadcast' flag when emitting an event. Broadcasting an event
* will send it to all the other sockets in the namespace except for yourself
*/
broadcast: Socket;
/**
* Emits an event to this client. If the 'broadcast' flag was set, this will
* emit to all other clients, except for this one
* @param event The event that we want to emit
* @param args Any number of optional arguments to pass with the event. If the
* last argument is a function, it will be called as an ack. The ack should
* take whatever data was sent with the packet
* @return This Socket
*/
emit( event: string, ...args: any[]): Socket;
/**
* Targets a room when broadcasting
* @param room The name of the room that we're targeting
* @return This Socket
*/
to( room: string ): Socket;
/**
* @see to( room )
*/
in( room: string ): Socket;
/**
* Sends a 'message' event
* @see emit( event, ...args )
*/
send( ...args: any[] ): Socket;
/**
* @see send( ...args )
*/
write( ...args: any[] ): Socket;
/**
* Joins a room. You can join multiple rooms, and by default, on connection,
* you join a room with the same name as your ID
* @param name The name of the room that we want to join
* @param fn An optional callback to call when we've joined the room. It should
* take an optional parameter, err, of a possible error
* @return This Socket
*/
join( name: string, fn?: ( err?: any ) => void ): Socket;
/**
* Leaves a room
* @param name The name of the room to leave
* @param fn An optional callback to call when we've left the room. It should
* take on optional parameter, err, of a possible error
*/
leave( name: string, fn?: Function ): Socket;
/**
* Leaves all the rooms that we've joined
*/
leaveAll(): void;
/**
* Disconnects this Socket
* @param close If true, also closes the underlying connection
* @return This Socket
*/
disconnect( close: boolean ): Socket;
/**
* Adds a listener for a particular event. Calling multiple times will add
* multiple listeners
* @param event The event that we're listening for
* @param fn The function to call when we get the event. Parameters depend on the
* event in question
* @return This Socket
*/
on( event: string, fn: Function ): Socket;
/**
* @see on( event, fn )
*/
addListener( event: string, fn: Function ): Socket;
/**
* Adds a listener for a particular event that will be invoked
* a single time before being automatically removed
* @param event The event that we're listening for
* @param fn The function to call when we get the event. Parameters depend on
* the event in question
* @return This Socket
*/
once( event: string, fn: Function ): Socket;
/**
* Removes a listener for a particular type of event. This will either
* remove a specific listener, or all listeners for this type of event
* @param event The event that we want to remove the listener of
* @param fn The function to remove, or null if we want to remove all functions
* @return This Socket
*/
removeListener( event: string, fn?: Function ): Socket;
/**
* Removes all event listeners on this object
* @return This Socket
*/
removeAllListeners( event?: string ): Socket;
/**
* Sets the maximum number of listeners this instance can have
* @param n The max number of listeners we can add to this emitter
* @return This Socket
*/
setMaxListeners( n: number ): Socket;
/**
* Returns all the callbacks for a particular event
* @param event The event that we're looking for the callbacks of
* @return An array of callback Functions, or an empty array if we don't have any
*/
listeners( event: string ):Function[];
}
/**
* The interface used when dealing with rooms etc
*/
interface Adapter extends NodeJS.EventEmitter {
/**
* The namespace that this adapter is for
*/
nsp: Namespace;
/**
* A dictionary of all the rooms that we have in this namespace, each room
* a dictionary of all the sockets currently in that room
*/
rooms: {[room: string]: {[id: string]: boolean }};
/**
* A dictionary of all the socket ids that we're dealing with, and all
* the rooms that the socket is currently in
*/
sids: {[id: string]: {[room: string]: boolean}};
/**
* Adds a socket to a room. If the room doesn't exist, it's created
* @param id The ID of the socket to add
* @param room The name of the room to add the socket to
* @param callback An optional callback to call when the socket has been
* added. It should take an optional parameter, error, if there was a problem
*/
add( id: string, room: string, callback?: ( err?: any ) => void ): void;
/**
* Removes a socket from a room. If there are no more sockets in the room,
* the room is deleted
* @param id The ID of the socket that we're removing
* @param room The name of the room to remove the socket from
* @param callback An optional callback to call when the socket has been
* removed. It should take on optional parameter, error, if there was a problem
*/
del( id: string, room: string, callback?: ( err?: any ) => void ): void;
/**
* Removes a socket from all the rooms that it's joined
* @param id The ID of the socket that we're removing
*/
delAll( id: string ):void;
/**
* Broadcasts a packet
* @param packet The packet to broadcast
* @param opts Any options to send along:
* - rooms: An optional list of rooms to broadcast to. If empty, the packet is broadcast to all sockets
* - except: A list of Socket IDs to exclude
* - flags: Any flags that we want to send along ('json', 'volatile', 'broadcast')
*/
broadcast( packet: any, opts: { rooms?: string[]; except?: string[]; flags?: {[flag: string]: boolean} } ):void;
}
/**
* The client behind each socket (can have multiple sockets)
*/
interface Client {
/**
* The Server that this client belongs to
*/
server: Server;
/**
* The underlying Engine.io Socket instance
*/
conn: {
/**
* The ID for this socket - matches Client.id
*/
id: string;
/**
* The Engine.io Server for this socket
*/
server: any;
/**
* The ready state for the client. Either 'opening', 'open', 'closing', or 'closed'
*/
readyState: string;
/**
* The remote IP for this connection
*/
remoteAddress: string;
};
/**
* The ID for this client. Regenerated at every connection
*/
id: string;
/**
* The http.IncomingMessage request sent with the connection. Useful
* for recovering headers etc
*/
request: any;
/**
* The list of sockets currently connect via this client (i.e. to different
* namespaces)
*/
sockets: Socket[];
/**
* A dictionary of all the namespaces for this client, with the Socket that
* deals with that namespace
*/
nsps: {[nsp: string]: Socket};
}
} | the_stack |
* drag spec
*/
import { Kanban, KanbanModel } from '../../src/kanban/index';
import { kanbanData } from './common/kanban-data.spec';
import { profile, inMB, getMemoryProfile } from './common/common.spec';
import * as util from './common/util.spec';
Kanban.Inject();
describe('Customer bug module', () => {
beforeAll(() => {
const isDef: (o: any) => boolean = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
// eslint-disable-next-line no-console
console.log('Unsupported environment, window.performance.memory is unavailable');
(this as any).skip(); //Skips test (in Chai)
return;
}
});
xdescribe('EJ2CORE-503 - Cards are hidden on the Kanban after the multiple card drag and drop - default layout', () => {
let kanbanObj: Kanban;
beforeAll((done: DoneFn) => {
const model: KanbanModel = {
columns: [
{ headerText: 'Backlog', keyField: 'Open', allowToggle: true },
{ headerText: 'In Progress', keyField: 'InProgress', allowToggle: true },
{ headerText: 'Testing', keyField: 'Testing', allowToggle: true },
{ headerText: 'Done', keyField: 'Close', allowToggle: true }
],
cardSettings: {
selectionType: 'Multiple'
}
};
kanbanObj = util.createKanban(model, kanbanData, done);
});
afterAll(() => {
util.destroy(kanbanObj);
});
it('Select multiple cards', () => {
const card1: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="1"]').item(0) as HTMLElement;
util.triggerMouseEvent(card1, 'click');
expect(card1.classList.contains('e-selection')).toEqual(true);
const card2: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="3"]').item(0) as HTMLElement;
util.triggerMouseEvent(card2, 'click', null, null, false, true);
const card3: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="4"]').item(0) as HTMLElement;
util.triggerMouseEvent(card3, 'click', null, null, false, true);
expect(card1.classList.contains('e-selection')).toEqual(true);
expect(card2.classList.contains('e-selection')).toEqual(true);
expect(card3.classList.contains('e-selection')).toEqual(true);
});
it('Drag multiple cards', () => {
const draggedElement: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="1"]').item(0) as HTMLElement;
util.triggerMouseEvent(draggedElement, 'mousedown');
util.triggerMouseEvent(draggedElement, 'mousemove', 250, 300);
expect(kanbanObj.element.querySelectorAll('.e-target-dragged-clone').length).toEqual(3);
const card1: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="1"]').item(0) as HTMLElement;
expect(card1.classList.contains('e-kanban-dragged-card')).toEqual(true);
const card2: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="3"]').item(0) as HTMLElement;
expect(card2.classList.contains('e-kanban-dragged-card')).toEqual(true);
const card3: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="4"]').item(0) as HTMLElement;
expect(card3.classList.contains('e-kanban-dragged-card')).toEqual(true);
});
it('Dropped card to columns', () => {
const ele: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="2"]').item(0) as HTMLElement;
util.triggerMouseEvent(ele, 'mouseup', 250, 300);
});
it('After select multiple cards', () => {
const card1: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="1"]').item(0) as HTMLElement;
expect(card1.classList.contains('e-selection')).toEqual(true);
const card2: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="3"]').item(0) as HTMLElement;
const card3: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="4"]').item(0) as HTMLElement;
expect(card1.classList.contains('e-selection')).toEqual(true);
expect(card2.classList.contains('e-selection')).toEqual(true);
expect(card3.classList.contains('e-selection')).toEqual(true);
expect(card1.classList.contains('e-kanban-dragged-card')).toEqual(false);
expect(card2.classList.contains('e-kanban-dragged-card')).toEqual(false);
expect(card3.classList.contains('e-kanban-dragged-card')).toEqual(false);
});
});
xdescribe('EJ2CORE-503 - Cards are hidden on the Kanban after the multiple card drag and drop - swimlane layout', () => {
let kanbanObj: Kanban;
beforeAll((done: DoneFn) => {
const model: KanbanModel = {
columns: [
{ headerText: 'Backlog', keyField: 'Open', allowToggle: true },
{ headerText: 'In Progress', keyField: 'InProgress', allowToggle: true },
{ headerText: 'Testing', keyField: 'Testing', allowToggle: true },
{ headerText: 'Done', keyField: 'Close', allowToggle: true }
],
swimlaneSettings: {
keyField: 'Assignee',
allowDragAndDrop: true
},
cardSettings: {
selectionType: 'Multiple'
}
};
kanbanObj = util.createKanban(model, kanbanData, done);
});
afterAll(() => {
util.destroy(kanbanObj);
});
it('Select multiple cards', () => {
const card1: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="45"]').item(0) as HTMLElement;
util.triggerMouseEvent(card1, 'click');
expect(card1.classList.contains('e-selection')).toEqual(true);
const card2: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="18"]').item(0) as HTMLElement;
util.triggerMouseEvent(card2, 'click', null, null, false, true);
const card3: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="66"]').item(0) as HTMLElement;
util.triggerMouseEvent(card3, 'click', null, null, false, true);
expect(card1.classList.contains('e-selection')).toEqual(true);
expect(card2.classList.contains('e-selection')).toEqual(true);
expect(card3.classList.contains('e-selection')).toEqual(true);
});
it('Drag multiple cards', () => {
const draggedElement: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="66"]').item(0) as HTMLElement;
util.triggerMouseEvent(draggedElement, 'mousedown');
util.triggerMouseEvent(draggedElement, 'mousemove', 250, 170);
expect(kanbanObj.element.querySelectorAll('.e-target-dragged-clone').length).toEqual(3);
const card1: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="45"]').item(0) as HTMLElement;
expect(card1.classList.contains('e-kanban-dragged-card')).toEqual(true);
const card2: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="18"]').item(0) as HTMLElement;
expect(card2.classList.contains('e-kanban-dragged-card')).toEqual(true);
const card3: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="66"]').item(0) as HTMLElement;
expect(card3.classList.contains('e-kanban-dragged-card')).toEqual(true);
});
it('Dropped card to columns', () => {
const ele: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="2"]').item(0) as HTMLElement;
util.triggerMouseEvent(ele, 'mouseup', 250, 150);
});
it('After select multiple cards', () => {
const card1: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="45"]').item(0) as HTMLElement;
expect(card1.classList.contains('e-selection')).toEqual(true);
const card2: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="18"]').item(0) as HTMLElement;
const card3: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="66"]').item(0) as HTMLElement;
expect(card1.classList.contains('e-selection')).toEqual(true);
expect(card2.classList.contains('e-selection')).toEqual(true);
expect(card3.classList.contains('e-selection')).toEqual(true);
expect(card1.classList.contains('e-kanban-dragged-card')).toEqual(false);
expect(card2.classList.contains('e-kanban-dragged-card')).toEqual(false);
expect(card3.classList.contains('e-kanban-dragged-card')).toEqual(false);
});
});
xdescribe('EJ2CORE-503 - Cards are hidden on the Kanban after the single card drag and drop - default layout', () => {
let kanbanObj: Kanban;
beforeAll((done: DoneFn) => {
const model: KanbanModel = {
columns: [
{ headerText: 'Backlog', keyField: 'Open', allowToggle: true },
{ headerText: 'In Progress', keyField: 'InProgress', allowToggle: true },
{ headerText: 'Testing', keyField: 'Testing', allowToggle: true },
{ headerText: 'Done', keyField: 'Close', allowToggle: true }
]
};
kanbanObj = util.createKanban(model, kanbanData, done);
});
afterAll(() => {
util.destroy(kanbanObj);
});
it('Select single card', () => {
const card1: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="1"]').item(0) as HTMLElement;
util.triggerMouseEvent(card1, 'click');
expect(card1.classList.contains('e-selection')).toEqual(true);
});
it('Drag selected card', () => {
const draggedElement: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="1"]').item(0) as HTMLElement;
util.triggerMouseEvent(draggedElement, 'mousedown');
util.triggerMouseEvent(draggedElement, 'mousemove', 250, 300);
expect(kanbanObj.element.querySelectorAll('.e-target-dragged-clone').length).toEqual(1);
const card1: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="1"]').item(0) as HTMLElement;
expect(card1.classList.contains('e-kanban-dragged-card')).toEqual(true);
});
it('Dropped card to columns', () => {
const ele: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="2"]').item(0) as HTMLElement;
util.triggerMouseEvent(ele, 'mouseup', 250, 300);
});
it('After select cards', () => {
const card1: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="1"]').item(0) as HTMLElement;
expect(card1.classList.contains('e-selection')).toEqual(true);
expect(card1.classList.contains('e-kanban-dragged-card')).toEqual(false);
});
});
xdescribe('EJ2CORE-503 - Cards are hidden on the Kanban after the multiple card drag and drop - default layout', () => {
let kanbanObj: Kanban;
beforeAll((done: DoneFn) => {
const model: KanbanModel = {
columns: [
{ headerText: 'Backlog', keyField: 'Open', allowToggle: true },
{ headerText: 'In Progress', keyField: 'InProgress', allowToggle: true },
{ headerText: 'Testing', keyField: 'Testing', allowToggle: true },
{ headerText: 'Done', keyField: 'Close', allowToggle: true }
]
};
kanbanObj = util.createKanban(model, kanbanData, done);
});
afterAll(() => {
util.destroy(kanbanObj);
});
it('Without Select single cards', () => {
const card1: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="1"]').item(0) as HTMLElement;
expect(card1.classList.contains('e-selection')).toEqual(false);
});
it('Drag single cards', () => {
const draggedElement: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="1"]').item(0) as HTMLElement;
util.triggerMouseEvent(draggedElement, 'mousedown');
util.triggerMouseEvent(draggedElement, 'mousemove', 250, 300);
expect(kanbanObj.element.querySelectorAll('.e-target-dragged-clone').length).toEqual(1);
const card1: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="1"]').item(0) as HTMLElement;
expect(card1.classList.contains('e-kanban-dragged-card')).toEqual(true);
});
it('Dropped card to columns', () => {
const ele: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="2"]').item(0) as HTMLElement;
util.triggerMouseEvent(ele, 'mouseup', 250, 300);
});
it('After drag and drop without select cards', () => {
const card1: HTMLElement = kanbanObj.element.querySelectorAll('.e-card[data-id="1"]').item(0) as HTMLElement;
expect(card1.classList.contains('e-selection')).toEqual(false);
expect(card1.classList.contains('e-kanban-dragged-card')).toEqual(false);
});
});
it('memory leak', () => {
profile.sample();
const average: any = inMB(profile.averageChange);
expect(average).toBeLessThan(10); //Check average change in memory samples to not be over 10MB
const memory: any = inMB(getMemoryProfile());
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
});
}); | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { VirtualMachineScaleSets } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { ComputeManagementClient } from "../computeManagementClient";
import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro";
import { LroImpl } from "../lroImpl";
import {
VirtualMachineScaleSet,
VirtualMachineScaleSetsListNextOptionalParams,
VirtualMachineScaleSetsListOptionalParams,
VirtualMachineScaleSetsListAllNextOptionalParams,
VirtualMachineScaleSetsListAllOptionalParams,
VirtualMachineScaleSetSku,
VirtualMachineScaleSetsListSkusNextOptionalParams,
VirtualMachineScaleSetsListSkusOptionalParams,
UpgradeOperationHistoricalStatusInfo,
VirtualMachineScaleSetsGetOSUpgradeHistoryNextOptionalParams,
VirtualMachineScaleSetsGetOSUpgradeHistoryOptionalParams,
VirtualMachineScaleSetsCreateOrUpdateOptionalParams,
VirtualMachineScaleSetsCreateOrUpdateResponse,
VirtualMachineScaleSetUpdate,
VirtualMachineScaleSetsUpdateOptionalParams,
VirtualMachineScaleSetsUpdateResponse,
VirtualMachineScaleSetsDeleteOptionalParams,
VirtualMachineScaleSetsGetOptionalParams,
VirtualMachineScaleSetsGetResponse,
VirtualMachineScaleSetsDeallocateOptionalParams,
VirtualMachineScaleSetVMInstanceRequiredIDs,
VirtualMachineScaleSetsDeleteInstancesOptionalParams,
VirtualMachineScaleSetsGetInstanceViewOptionalParams,
VirtualMachineScaleSetsGetInstanceViewResponse,
VirtualMachineScaleSetsListResponse,
VirtualMachineScaleSetsListAllResponse,
VirtualMachineScaleSetsListSkusResponse,
VirtualMachineScaleSetsGetOSUpgradeHistoryResponse,
VirtualMachineScaleSetsPowerOffOptionalParams,
VirtualMachineScaleSetsRestartOptionalParams,
VirtualMachineScaleSetsStartOptionalParams,
VirtualMachineScaleSetsRedeployOptionalParams,
VirtualMachineScaleSetsPerformMaintenanceOptionalParams,
VirtualMachineScaleSetsUpdateInstancesOptionalParams,
VirtualMachineScaleSetsReimageOptionalParams,
VirtualMachineScaleSetsReimageAllOptionalParams,
VirtualMachineScaleSetsForceRecoveryServiceFabricPlatformUpdateDomainWalkOptionalParams,
VirtualMachineScaleSetsForceRecoveryServiceFabricPlatformUpdateDomainWalkResponse,
VMScaleSetConvertToSinglePlacementGroupInput,
VirtualMachineScaleSetsConvertToSinglePlacementGroupOptionalParams,
OrchestrationServiceStateInput,
VirtualMachineScaleSetsSetOrchestrationServiceStateOptionalParams,
VirtualMachineScaleSetsListNextResponse,
VirtualMachineScaleSetsListAllNextResponse,
VirtualMachineScaleSetsListSkusNextResponse,
VirtualMachineScaleSetsGetOSUpgradeHistoryNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing VirtualMachineScaleSets operations. */
export class VirtualMachineScaleSetsImpl implements VirtualMachineScaleSets {
private readonly client: ComputeManagementClient;
/**
* Initialize a new instance of the class VirtualMachineScaleSets class.
* @param client Reference to the service client
*/
constructor(client: ComputeManagementClient) {
this.client = client;
}
/**
* Gets a list of all VM scale sets under a resource group.
* @param resourceGroupName The name of the resource group.
* @param options The options parameters.
*/
public list(
resourceGroupName: string,
options?: VirtualMachineScaleSetsListOptionalParams
): PagedAsyncIterableIterator<VirtualMachineScaleSet> {
const iter = this.listPagingAll(resourceGroupName, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listPagingPage(resourceGroupName, options);
}
};
}
private async *listPagingPage(
resourceGroupName: string,
options?: VirtualMachineScaleSetsListOptionalParams
): AsyncIterableIterator<VirtualMachineScaleSet[]> {
let result = await this._list(resourceGroupName, options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listNext(
resourceGroupName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listPagingAll(
resourceGroupName: string,
options?: VirtualMachineScaleSetsListOptionalParams
): AsyncIterableIterator<VirtualMachineScaleSet> {
for await (const page of this.listPagingPage(resourceGroupName, options)) {
yield* page;
}
}
/**
* Gets a list of all VM Scale Sets in the subscription, regardless of the associated resource group.
* Use nextLink property in the response to get the next page of VM Scale Sets. Do this till nextLink
* is null to fetch all the VM Scale Sets.
* @param options The options parameters.
*/
public listAll(
options?: VirtualMachineScaleSetsListAllOptionalParams
): PagedAsyncIterableIterator<VirtualMachineScaleSet> {
const iter = this.listAllPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listAllPagingPage(options);
}
};
}
private async *listAllPagingPage(
options?: VirtualMachineScaleSetsListAllOptionalParams
): AsyncIterableIterator<VirtualMachineScaleSet[]> {
let result = await this._listAll(options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listAllNext(continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listAllPagingAll(
options?: VirtualMachineScaleSetsListAllOptionalParams
): AsyncIterableIterator<VirtualMachineScaleSet> {
for await (const page of this.listAllPagingPage(options)) {
yield* page;
}
}
/**
* Gets a list of SKUs available for your VM scale set, including the minimum and maximum VM instances
* allowed for each SKU.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
public listSkus(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsListSkusOptionalParams
): PagedAsyncIterableIterator<VirtualMachineScaleSetSku> {
const iter = this.listSkusPagingAll(
resourceGroupName,
vmScaleSetName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listSkusPagingPage(
resourceGroupName,
vmScaleSetName,
options
);
}
};
}
private async *listSkusPagingPage(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsListSkusOptionalParams
): AsyncIterableIterator<VirtualMachineScaleSetSku[]> {
let result = await this._listSkus(
resourceGroupName,
vmScaleSetName,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listSkusNext(
resourceGroupName,
vmScaleSetName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listSkusPagingAll(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsListSkusOptionalParams
): AsyncIterableIterator<VirtualMachineScaleSetSku> {
for await (const page of this.listSkusPagingPage(
resourceGroupName,
vmScaleSetName,
options
)) {
yield* page;
}
}
/**
* Gets list of OS upgrades on a VM scale set instance.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
public listOSUpgradeHistory(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsGetOSUpgradeHistoryOptionalParams
): PagedAsyncIterableIterator<UpgradeOperationHistoricalStatusInfo> {
const iter = this.getOSUpgradeHistoryPagingAll(
resourceGroupName,
vmScaleSetName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.getOSUpgradeHistoryPagingPage(
resourceGroupName,
vmScaleSetName,
options
);
}
};
}
private async *getOSUpgradeHistoryPagingPage(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsGetOSUpgradeHistoryOptionalParams
): AsyncIterableIterator<UpgradeOperationHistoricalStatusInfo[]> {
let result = await this._getOSUpgradeHistory(
resourceGroupName,
vmScaleSetName,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._getOSUpgradeHistoryNext(
resourceGroupName,
vmScaleSetName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *getOSUpgradeHistoryPagingAll(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsGetOSUpgradeHistoryOptionalParams
): AsyncIterableIterator<UpgradeOperationHistoricalStatusInfo> {
for await (const page of this.getOSUpgradeHistoryPagingPage(
resourceGroupName,
vmScaleSetName,
options
)) {
yield* page;
}
}
/**
* Create or update a VM scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set to create or update.
* @param parameters The scale set object.
* @param options The options parameters.
*/
async beginCreateOrUpdate(
resourceGroupName: string,
vmScaleSetName: string,
parameters: VirtualMachineScaleSet,
options?: VirtualMachineScaleSetsCreateOrUpdateOptionalParams
): Promise<
PollerLike<
PollOperationState<VirtualMachineScaleSetsCreateOrUpdateResponse>,
VirtualMachineScaleSetsCreateOrUpdateResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<VirtualMachineScaleSetsCreateOrUpdateResponse> => {
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, vmScaleSetName, parameters, options },
createOrUpdateOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Create or update a VM scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set to create or update.
* @param parameters The scale set object.
* @param options The options parameters.
*/
async beginCreateOrUpdateAndWait(
resourceGroupName: string,
vmScaleSetName: string,
parameters: VirtualMachineScaleSet,
options?: VirtualMachineScaleSetsCreateOrUpdateOptionalParams
): Promise<VirtualMachineScaleSetsCreateOrUpdateResponse> {
const poller = await this.beginCreateOrUpdate(
resourceGroupName,
vmScaleSetName,
parameters,
options
);
return poller.pollUntilDone();
}
/**
* Update a VM scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set to create or update.
* @param parameters The scale set object.
* @param options The options parameters.
*/
async beginUpdate(
resourceGroupName: string,
vmScaleSetName: string,
parameters: VirtualMachineScaleSetUpdate,
options?: VirtualMachineScaleSetsUpdateOptionalParams
): Promise<
PollerLike<
PollOperationState<VirtualMachineScaleSetsUpdateResponse>,
VirtualMachineScaleSetsUpdateResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<VirtualMachineScaleSetsUpdateResponse> => {
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, vmScaleSetName, parameters, options },
updateOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Update a VM scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set to create or update.
* @param parameters The scale set object.
* @param options The options parameters.
*/
async beginUpdateAndWait(
resourceGroupName: string,
vmScaleSetName: string,
parameters: VirtualMachineScaleSetUpdate,
options?: VirtualMachineScaleSetsUpdateOptionalParams
): Promise<VirtualMachineScaleSetsUpdateResponse> {
const poller = await this.beginUpdate(
resourceGroupName,
vmScaleSetName,
parameters,
options
);
return poller.pollUntilDone();
}
/**
* Deletes a VM scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
async beginDelete(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsDeleteOptionalParams
): 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, vmScaleSetName, options },
deleteOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Deletes a VM scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
async beginDeleteAndWait(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsDeleteOptionalParams
): Promise<void> {
const poller = await this.beginDelete(
resourceGroupName,
vmScaleSetName,
options
);
return poller.pollUntilDone();
}
/**
* Display information about a virtual machine scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsGetOptionalParams
): Promise<VirtualMachineScaleSetsGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, vmScaleSetName, options },
getOperationSpec
);
}
/**
* Deallocates specific virtual machines in a VM scale set. Shuts down the virtual machines and
* releases the compute resources. You are not billed for the compute resources that this virtual
* machine scale set deallocates.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
async beginDeallocate(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsDeallocateOptionalParams
): 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, vmScaleSetName, options },
deallocateOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Deallocates specific virtual machines in a VM scale set. Shuts down the virtual machines and
* releases the compute resources. You are not billed for the compute resources that this virtual
* machine scale set deallocates.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
async beginDeallocateAndWait(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsDeallocateOptionalParams
): Promise<void> {
const poller = await this.beginDeallocate(
resourceGroupName,
vmScaleSetName,
options
);
return poller.pollUntilDone();
}
/**
* Deletes virtual machines in a VM scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param vmInstanceIDs A list of virtual machine instance IDs from the VM scale set.
* @param options The options parameters.
*/
async beginDeleteInstances(
resourceGroupName: string,
vmScaleSetName: string,
vmInstanceIDs: VirtualMachineScaleSetVMInstanceRequiredIDs,
options?: VirtualMachineScaleSetsDeleteInstancesOptionalParams
): 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, vmScaleSetName, vmInstanceIDs, options },
deleteInstancesOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Deletes virtual machines in a VM scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param vmInstanceIDs A list of virtual machine instance IDs from the VM scale set.
* @param options The options parameters.
*/
async beginDeleteInstancesAndWait(
resourceGroupName: string,
vmScaleSetName: string,
vmInstanceIDs: VirtualMachineScaleSetVMInstanceRequiredIDs,
options?: VirtualMachineScaleSetsDeleteInstancesOptionalParams
): Promise<void> {
const poller = await this.beginDeleteInstances(
resourceGroupName,
vmScaleSetName,
vmInstanceIDs,
options
);
return poller.pollUntilDone();
}
/**
* Gets the status of a VM scale set instance.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
getInstanceView(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsGetInstanceViewOptionalParams
): Promise<VirtualMachineScaleSetsGetInstanceViewResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, vmScaleSetName, options },
getInstanceViewOperationSpec
);
}
/**
* Gets a list of all VM scale sets under a resource group.
* @param resourceGroupName The name of the resource group.
* @param options The options parameters.
*/
private _list(
resourceGroupName: string,
options?: VirtualMachineScaleSetsListOptionalParams
): Promise<VirtualMachineScaleSetsListResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, options },
listOperationSpec
);
}
/**
* Gets a list of all VM Scale Sets in the subscription, regardless of the associated resource group.
* Use nextLink property in the response to get the next page of VM Scale Sets. Do this till nextLink
* is null to fetch all the VM Scale Sets.
* @param options The options parameters.
*/
private _listAll(
options?: VirtualMachineScaleSetsListAllOptionalParams
): Promise<VirtualMachineScaleSetsListAllResponse> {
return this.client.sendOperationRequest({ options }, listAllOperationSpec);
}
/**
* Gets a list of SKUs available for your VM scale set, including the minimum and maximum VM instances
* allowed for each SKU.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
private _listSkus(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsListSkusOptionalParams
): Promise<VirtualMachineScaleSetsListSkusResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, vmScaleSetName, options },
listSkusOperationSpec
);
}
/**
* Gets list of OS upgrades on a VM scale set instance.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
private _getOSUpgradeHistory(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsGetOSUpgradeHistoryOptionalParams
): Promise<VirtualMachineScaleSetsGetOSUpgradeHistoryResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, vmScaleSetName, options },
getOSUpgradeHistoryOperationSpec
);
}
/**
* Power off (stop) one or more virtual machines in a VM scale set. Note that resources are still
* attached and you are getting charged for the resources. Instead, use deallocate to release resources
* and avoid charges.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
async beginPowerOff(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsPowerOffOptionalParams
): 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, vmScaleSetName, options },
powerOffOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Power off (stop) one or more virtual machines in a VM scale set. Note that resources are still
* attached and you are getting charged for the resources. Instead, use deallocate to release resources
* and avoid charges.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
async beginPowerOffAndWait(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsPowerOffOptionalParams
): Promise<void> {
const poller = await this.beginPowerOff(
resourceGroupName,
vmScaleSetName,
options
);
return poller.pollUntilDone();
}
/**
* Restarts one or more virtual machines in a VM scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
async beginRestart(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsRestartOptionalParams
): 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, vmScaleSetName, options },
restartOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Restarts one or more virtual machines in a VM scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
async beginRestartAndWait(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsRestartOptionalParams
): Promise<void> {
const poller = await this.beginRestart(
resourceGroupName,
vmScaleSetName,
options
);
return poller.pollUntilDone();
}
/**
* Starts one or more virtual machines in a VM scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
async beginStart(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsStartOptionalParams
): 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, vmScaleSetName, options },
startOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Starts one or more virtual machines in a VM scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
async beginStartAndWait(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsStartOptionalParams
): Promise<void> {
const poller = await this.beginStart(
resourceGroupName,
vmScaleSetName,
options
);
return poller.pollUntilDone();
}
/**
* Shuts down all the virtual machines in the virtual machine scale set, moves them to a new node, and
* powers them back on.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
async beginRedeploy(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsRedeployOptionalParams
): 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, vmScaleSetName, options },
redeployOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Shuts down all the virtual machines in the virtual machine scale set, moves them to a new node, and
* powers them back on.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
async beginRedeployAndWait(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsRedeployOptionalParams
): Promise<void> {
const poller = await this.beginRedeploy(
resourceGroupName,
vmScaleSetName,
options
);
return poller.pollUntilDone();
}
/**
* Perform maintenance on one or more virtual machines in a VM scale set. Operation on instances which
* are not eligible for perform maintenance will be failed. Please refer to best practices for more
* details:
* https://docs.microsoft.com/en-us/azure/virtual-machine-scale-sets/virtual-machine-scale-sets-maintenance-notifications
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
async beginPerformMaintenance(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsPerformMaintenanceOptionalParams
): 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, vmScaleSetName, options },
performMaintenanceOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Perform maintenance on one or more virtual machines in a VM scale set. Operation on instances which
* are not eligible for perform maintenance will be failed. Please refer to best practices for more
* details:
* https://docs.microsoft.com/en-us/azure/virtual-machine-scale-sets/virtual-machine-scale-sets-maintenance-notifications
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
async beginPerformMaintenanceAndWait(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsPerformMaintenanceOptionalParams
): Promise<void> {
const poller = await this.beginPerformMaintenance(
resourceGroupName,
vmScaleSetName,
options
);
return poller.pollUntilDone();
}
/**
* Upgrades one or more virtual machines to the latest SKU set in the VM scale set model.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param vmInstanceIDs A list of virtual machine instance IDs from the VM scale set.
* @param options The options parameters.
*/
async beginUpdateInstances(
resourceGroupName: string,
vmScaleSetName: string,
vmInstanceIDs: VirtualMachineScaleSetVMInstanceRequiredIDs,
options?: VirtualMachineScaleSetsUpdateInstancesOptionalParams
): 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, vmScaleSetName, vmInstanceIDs, options },
updateInstancesOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Upgrades one or more virtual machines to the latest SKU set in the VM scale set model.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param vmInstanceIDs A list of virtual machine instance IDs from the VM scale set.
* @param options The options parameters.
*/
async beginUpdateInstancesAndWait(
resourceGroupName: string,
vmScaleSetName: string,
vmInstanceIDs: VirtualMachineScaleSetVMInstanceRequiredIDs,
options?: VirtualMachineScaleSetsUpdateInstancesOptionalParams
): Promise<void> {
const poller = await this.beginUpdateInstances(
resourceGroupName,
vmScaleSetName,
vmInstanceIDs,
options
);
return poller.pollUntilDone();
}
/**
* Reimages (upgrade the operating system) one or more virtual machines in a VM scale set which don't
* have a ephemeral OS disk, for virtual machines who have a ephemeral OS disk the virtual machine is
* reset to initial state.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
async beginReimage(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsReimageOptionalParams
): 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, vmScaleSetName, options },
reimageOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Reimages (upgrade the operating system) one or more virtual machines in a VM scale set which don't
* have a ephemeral OS disk, for virtual machines who have a ephemeral OS disk the virtual machine is
* reset to initial state.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
async beginReimageAndWait(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsReimageOptionalParams
): Promise<void> {
const poller = await this.beginReimage(
resourceGroupName,
vmScaleSetName,
options
);
return poller.pollUntilDone();
}
/**
* Reimages all the disks ( including data disks ) in the virtual machines in a VM scale set. This
* operation is only supported for managed disks.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
async beginReimageAll(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsReimageAllOptionalParams
): 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, vmScaleSetName, options },
reimageAllOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Reimages all the disks ( including data disks ) in the virtual machines in a VM scale set. This
* operation is only supported for managed disks.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
async beginReimageAllAndWait(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsReimageAllOptionalParams
): Promise<void> {
const poller = await this.beginReimageAll(
resourceGroupName,
vmScaleSetName,
options
);
return poller.pollUntilDone();
}
/**
* Manual platform update domain walk to update virtual machines in a service fabric virtual machine
* scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param platformUpdateDomain The platform update domain for which a manual recovery walk is requested
* @param options The options parameters.
*/
forceRecoveryServiceFabricPlatformUpdateDomainWalk(
resourceGroupName: string,
vmScaleSetName: string,
platformUpdateDomain: number,
options?: VirtualMachineScaleSetsForceRecoveryServiceFabricPlatformUpdateDomainWalkOptionalParams
): Promise<
VirtualMachineScaleSetsForceRecoveryServiceFabricPlatformUpdateDomainWalkResponse
> {
return this.client.sendOperationRequest(
{ resourceGroupName, vmScaleSetName, platformUpdateDomain, options },
forceRecoveryServiceFabricPlatformUpdateDomainWalkOperationSpec
);
}
/**
* Converts SinglePlacementGroup property to false for a existing virtual machine scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the virtual machine scale set to create or update.
* @param parameters The input object for ConvertToSinglePlacementGroup API.
* @param options The options parameters.
*/
convertToSinglePlacementGroup(
resourceGroupName: string,
vmScaleSetName: string,
parameters: VMScaleSetConvertToSinglePlacementGroupInput,
options?: VirtualMachineScaleSetsConvertToSinglePlacementGroupOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, vmScaleSetName, parameters, options },
convertToSinglePlacementGroupOperationSpec
);
}
/**
* Changes ServiceState property for a given service
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the virtual machine scale set to create or update.
* @param parameters The input object for SetOrchestrationServiceState API.
* @param options The options parameters.
*/
async beginSetOrchestrationServiceState(
resourceGroupName: string,
vmScaleSetName: string,
parameters: OrchestrationServiceStateInput,
options?: VirtualMachineScaleSetsSetOrchestrationServiceStateOptionalParams
): 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, vmScaleSetName, parameters, options },
setOrchestrationServiceStateOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Changes ServiceState property for a given service
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the virtual machine scale set to create or update.
* @param parameters The input object for SetOrchestrationServiceState API.
* @param options The options parameters.
*/
async beginSetOrchestrationServiceStateAndWait(
resourceGroupName: string,
vmScaleSetName: string,
parameters: OrchestrationServiceStateInput,
options?: VirtualMachineScaleSetsSetOrchestrationServiceStateOptionalParams
): Promise<void> {
const poller = await this.beginSetOrchestrationServiceState(
resourceGroupName,
vmScaleSetName,
parameters,
options
);
return poller.pollUntilDone();
}
/**
* ListNext
* @param resourceGroupName The name of the resource group.
* @param nextLink The nextLink from the previous successful call to the List method.
* @param options The options parameters.
*/
private _listNext(
resourceGroupName: string,
nextLink: string,
options?: VirtualMachineScaleSetsListNextOptionalParams
): Promise<VirtualMachineScaleSetsListNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, nextLink, options },
listNextOperationSpec
);
}
/**
* ListAllNext
* @param nextLink The nextLink from the previous successful call to the ListAll method.
* @param options The options parameters.
*/
private _listAllNext(
nextLink: string,
options?: VirtualMachineScaleSetsListAllNextOptionalParams
): Promise<VirtualMachineScaleSetsListAllNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
listAllNextOperationSpec
);
}
/**
* ListSkusNext
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param nextLink The nextLink from the previous successful call to the ListSkus method.
* @param options The options parameters.
*/
private _listSkusNext(
resourceGroupName: string,
vmScaleSetName: string,
nextLink: string,
options?: VirtualMachineScaleSetsListSkusNextOptionalParams
): Promise<VirtualMachineScaleSetsListSkusNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, vmScaleSetName, nextLink, options },
listSkusNextOperationSpec
);
}
/**
* GetOSUpgradeHistoryNext
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param nextLink The nextLink from the previous successful call to the GetOSUpgradeHistory method.
* @param options The options parameters.
*/
private _getOSUpgradeHistoryNext(
resourceGroupName: string,
vmScaleSetName: string,
nextLink: string,
options?: VirtualMachineScaleSetsGetOSUpgradeHistoryNextOptionalParams
): Promise<VirtualMachineScaleSetsGetOSUpgradeHistoryNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, vmScaleSetName, nextLink, options },
getOSUpgradeHistoryNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const createOrUpdateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.VirtualMachineScaleSet
},
201: {
bodyMapper: Mappers.VirtualMachineScaleSet
},
202: {
bodyMapper: Mappers.VirtualMachineScaleSet
},
204: {
bodyMapper: Mappers.VirtualMachineScaleSet
}
},
requestBody: Parameters.parameters17,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.vmScaleSetName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const updateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}",
httpMethod: "PATCH",
responses: {
200: {
bodyMapper: Mappers.VirtualMachineScaleSet
},
201: {
bodyMapper: Mappers.VirtualMachineScaleSet
},
202: {
bodyMapper: Mappers.VirtualMachineScaleSet
},
204: {
bodyMapper: Mappers.VirtualMachineScaleSet
}
},
requestBody: Parameters.parameters18,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.vmScaleSetName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}",
httpMethod: "DELETE",
responses: { 200: {}, 201: {}, 202: {}, 204: {} },
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.vmScaleSetName
],
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.VirtualMachineScaleSet
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.vmScaleSetName
],
headerParameters: [Parameters.accept],
serializer
};
const deallocateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/deallocate",
httpMethod: "POST",
responses: { 200: {}, 201: {}, 202: {}, 204: {} },
requestBody: Parameters.vmInstanceIDs,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.vmScaleSetName
],
headerParameters: [Parameters.contentType],
mediaType: "json",
serializer
};
const deleteInstancesOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/delete",
httpMethod: "POST",
responses: { 200: {}, 201: {}, 202: {}, 204: {} },
requestBody: Parameters.vmInstanceIDs1,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.vmScaleSetName
],
headerParameters: [Parameters.contentType],
mediaType: "json",
serializer
};
const getInstanceViewOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/instanceView",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.VirtualMachineScaleSetInstanceView
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.vmScaleSetName
],
headerParameters: [Parameters.accept],
serializer
};
const listOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.VirtualMachineScaleSetListResult
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
};
const listAllOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.Compute/virtualMachineScaleSets",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.VirtualMachineScaleSetListWithLinkResult
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.subscriptionId],
headerParameters: [Parameters.accept],
serializer
};
const listSkusOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/skus",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.VirtualMachineScaleSetListSkusResult
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.vmScaleSetName
],
headerParameters: [Parameters.accept],
serializer
};
const getOSUpgradeHistoryOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/osUpgradeHistory",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.VirtualMachineScaleSetListOSUpgradeHistory
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.vmScaleSetName
],
headerParameters: [Parameters.accept],
serializer
};
const powerOffOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/poweroff",
httpMethod: "POST",
responses: { 200: {}, 201: {}, 202: {}, 204: {} },
requestBody: Parameters.vmInstanceIDs,
queryParameters: [Parameters.apiVersion, Parameters.skipShutdown],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.vmScaleSetName
],
headerParameters: [Parameters.contentType],
mediaType: "json",
serializer
};
const restartOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/restart",
httpMethod: "POST",
responses: { 200: {}, 201: {}, 202: {}, 204: {} },
requestBody: Parameters.vmInstanceIDs,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.vmScaleSetName
],
headerParameters: [Parameters.contentType],
mediaType: "json",
serializer
};
const startOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/start",
httpMethod: "POST",
responses: { 200: {}, 201: {}, 202: {}, 204: {} },
requestBody: Parameters.vmInstanceIDs,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.vmScaleSetName
],
headerParameters: [Parameters.contentType],
mediaType: "json",
serializer
};
const redeployOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/redeploy",
httpMethod: "POST",
responses: { 200: {}, 201: {}, 202: {}, 204: {} },
requestBody: Parameters.vmInstanceIDs,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.vmScaleSetName
],
headerParameters: [Parameters.contentType],
mediaType: "json",
serializer
};
const performMaintenanceOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/performMaintenance",
httpMethod: "POST",
responses: { 200: {}, 201: {}, 202: {}, 204: {} },
requestBody: Parameters.vmInstanceIDs,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.vmScaleSetName
],
headerParameters: [Parameters.contentType],
mediaType: "json",
serializer
};
const updateInstancesOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/manualupgrade",
httpMethod: "POST",
responses: { 200: {}, 201: {}, 202: {}, 204: {} },
requestBody: Parameters.vmInstanceIDs1,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.vmScaleSetName
],
headerParameters: [Parameters.contentType],
mediaType: "json",
serializer
};
const reimageOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/reimage",
httpMethod: "POST",
responses: { 200: {}, 201: {}, 202: {}, 204: {} },
requestBody: Parameters.vmScaleSetReimageInput,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.vmScaleSetName
],
headerParameters: [Parameters.contentType],
mediaType: "json",
serializer
};
const reimageAllOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/reimageall",
httpMethod: "POST",
responses: { 200: {}, 201: {}, 202: {}, 204: {} },
requestBody: Parameters.vmInstanceIDs,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.vmScaleSetName
],
headerParameters: [Parameters.contentType],
mediaType: "json",
serializer
};
const forceRecoveryServiceFabricPlatformUpdateDomainWalkOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/forceRecoveryServiceFabricPlatformUpdateDomainWalk",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.RecoveryWalkResponse
}
},
queryParameters: [Parameters.apiVersion, Parameters.platformUpdateDomain],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.vmScaleSetName
],
headerParameters: [Parameters.accept],
serializer
};
const convertToSinglePlacementGroupOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/convertToSinglePlacementGroup",
httpMethod: "POST",
responses: { 200: {} },
requestBody: Parameters.parameters19,
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.vmScaleSetName
],
headerParameters: [Parameters.contentType],
mediaType: "json",
serializer
};
const setOrchestrationServiceStateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmScaleSetName}/setOrchestrationServiceState",
httpMethod: "POST",
responses: { 200: {}, 201: {}, 202: {}, 204: {} },
requestBody: Parameters.parameters20,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.vmScaleSetName
],
headerParameters: [Parameters.contentType],
mediaType: "json",
serializer
};
const listNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.VirtualMachineScaleSetListResult
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
};
const listAllNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.VirtualMachineScaleSetListWithLinkResult
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
};
const listSkusNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.VirtualMachineScaleSetListSkusResult
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.nextLink,
Parameters.vmScaleSetName
],
headerParameters: [Parameters.accept],
serializer
};
const getOSUpgradeHistoryNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.VirtualMachineScaleSetListOSUpgradeHistory
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.nextLink,
Parameters.vmScaleSetName
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import { join } from 'path';
import { ExtensionContext, window } from 'vscode';
import { CargoInvocationManager } from '../../CargoInvocationManager';
import { ShellProviderManager } from '../../ShellProviderManager';
import { Configuration } from '../configuration/Configuration';
import { CurrentWorkingDirectoryManager }
from '../configuration/current_working_directory_manager';
import { ChildLogger } from '../logging/child_logger';
import { CommandInvocationReason } from './CommandInvocationReason';
import { CrateType } from './CrateType';
import { CommandStartHandleResult, Helper } from './helper';
import { OutputChannelTaskManager } from './output_channel_task_manager';
import { TerminalTaskManager } from './terminal_task_manager';
import { UserDefinedArgs } from './UserDefinedArgs';
export class CargoTaskManager {
private _configuration: Configuration;
private _cargoInvocationManager: CargoInvocationManager;
private _currentWorkingDirectoryManager: CurrentWorkingDirectoryManager;
private _logger: ChildLogger;
private _outputChannelTaskManager: OutputChannelTaskManager;
private _terminalTaskManager: TerminalTaskManager;
public constructor(
context: ExtensionContext,
configuration: Configuration,
cargoInvocationManager: CargoInvocationManager,
currentWorkingDirectoryManager: CurrentWorkingDirectoryManager,
shellProviderManager: ShellProviderManager,
logger: ChildLogger,
stopCommandName: string
) {
this._configuration = configuration;
this._cargoInvocationManager = cargoInvocationManager;
this._currentWorkingDirectoryManager = currentWorkingDirectoryManager;
this._logger = logger;
this._outputChannelTaskManager = new OutputChannelTaskManager(
configuration,
logger.createChildLogger('OutputChannelTaskManager: '),
stopCommandName
);
this._terminalTaskManager = new TerminalTaskManager(
context,
configuration,
shellProviderManager
);
}
public async invokeCargoInit(crateType: CrateType, name: string, workingDirectory: string): Promise<void> {
const args = ['--name', name];
switch (crateType) {
case CrateType.Application:
args.push('--bin');
break;
case CrateType.Library:
args.push('--lib');
break;
default:
throw new Error(`Unhandled crate type=${crateType}`);
}
await this.processRequestToStartTask(
'init',
args,
workingDirectory,
true,
CommandInvocationReason.CommandExecution,
false,
false,
false
);
}
public invokeCargoBuildWithArgs(args: string[], reason: CommandInvocationReason): void {
this.runCargo('build', args, true, reason);
}
public invokeCargoBuildUsingBuildArgs(reason: CommandInvocationReason): void {
this.invokeCargoBuildWithArgs(UserDefinedArgs.getBuildArgs(), reason);
}
public invokeCargoCheckWithArgs(args: string[], reason: CommandInvocationReason): void {
this.runCargo('check', args, true, reason);
}
public invokeCargoCheckUsingCheckArgs(reason: CommandInvocationReason): void {
this.invokeCargoCheckWithArgs(UserDefinedArgs.getCheckArgs(), reason);
}
public invokeCargoClippyWithArgs(args: string[], reason: CommandInvocationReason): void {
this.runCargo('clippy', args, true, reason);
}
public invokeCargoClippyUsingClippyArgs(reason: CommandInvocationReason): void {
this.invokeCargoClippyWithArgs(UserDefinedArgs.getClippyArgs(), reason);
}
public invokeCargoDocWithArgs(args: string[], reason: CommandInvocationReason): void {
this.runCargo('doc', args, true, reason);
}
public invokeCargoDocUsingDocArgs(reason: CommandInvocationReason): void {
this.invokeCargoDocWithArgs(UserDefinedArgs.getDocArgs(), reason);
}
public async invokeCargoNew(projectName: string, isBin: boolean, workingDirectory: string): Promise<void> {
const args = [projectName, isBin ? '--bin' : '--lib'];
await this.processRequestToStartTask(
'new',
args,
workingDirectory,
true,
CommandInvocationReason.CommandExecution,
false,
false,
false
);
}
public invokeCargoRunWithArgs(args: string[], reason: CommandInvocationReason): void {
this.runCargo('run', args, true, reason);
}
public invokeCargoRunUsingRunArgs(reason: CommandInvocationReason): void {
this.invokeCargoRunWithArgs(UserDefinedArgs.getRunArgs(), reason);
}
public invokeCargoTestWithArgs(args: string[], reason: CommandInvocationReason): void {
this.runCargo('test', args, true, reason);
}
public invokeCargoTestUsingTestArgs(reason: CommandInvocationReason): void {
this.invokeCargoTestWithArgs(UserDefinedArgs.getTestArgs(), reason);
}
public invokeCargo(command: string, args: string[]): void {
this.runCargo(command, args, true, CommandInvocationReason.CommandExecution);
}
public stopTask(): void {
if (this._outputChannelTaskManager.hasRunningTask()) {
this._outputChannelTaskManager.stopRunningTask();
}
}
private async processRequestToStartTask(
command: string,
args: string[],
workingDirectory: string,
isStoppingRunningTaskAllowed: boolean,
reason: CommandInvocationReason,
shouldStartTaskInTerminal: boolean,
shouldUseUserWorkingDirectory: boolean,
shouldParseOutput: boolean
): Promise<void> {
const canStartTask = await this.processPossiblyRunningTask(
isStoppingRunningTaskAllowed,
shouldStartTaskInTerminal
);
if (!canStartTask) {
return;
}
if (shouldUseUserWorkingDirectory) {
({ args, workingDirectory } = this.processPossibleUserRequestToChangeWorkingDirectory(
args,
workingDirectory
));
}
const { executable, args: preCommandArgs } = this._cargoInvocationManager.getExecutableAndArgs();
this.startTask(
executable,
preCommandArgs,
command,
args,
workingDirectory,
reason,
shouldStartTaskInTerminal,
shouldParseOutput
);
}
private async runCargo(
command: string,
args: string[],
force: boolean,
reason: CommandInvocationReason
): Promise<void> {
let workingDirectory: string;
try {
workingDirectory = await this._currentWorkingDirectoryManager.cwd();
} catch (error) {
window.showErrorMessage(error.message);
return;
}
const shouldExecuteCargoCommandInTerminal = this._configuration.shouldExecuteCargoCommandInTerminal();
this.processRequestToStartTask(
command,
args,
workingDirectory,
force,
reason,
shouldExecuteCargoCommandInTerminal,
true,
true
);
}
/**
* Checks whether some task is running and it is, then checks whether it can be stopped
* @param isStoppingRunningTaskAllowed The flag indicating whether the currently running task
* can be stopped
* @param isPossiblyRunningTaskRunInTerminal The flag indicating whether the currently
* running task is run in the terminal
* @return The flag inidicating whether there is no running task (there was no running task or
* the running task has been stopped)
*/
private async processPossiblyRunningTask(
isStoppingRunningTaskAllowed: boolean,
isPossiblyRunningTaskRunInTerminal: boolean
): Promise<boolean> {
let hasRunningTask = false;
if (isPossiblyRunningTaskRunInTerminal) {
hasRunningTask = this._terminalTaskManager.hasRunningTask();
} else {
hasRunningTask = this._outputChannelTaskManager.hasRunningTask();
}
if (!hasRunningTask) {
return true;
}
if (!isStoppingRunningTaskAllowed) {
return false;
}
let shouldStopRunningTask = false;
const helper = new Helper(this._configuration);
const result = await helper.handleCommandStartWhenThereIsRunningCommand();
switch (result) {
case CommandStartHandleResult.IgnoreNewCommand:
break;
case CommandStartHandleResult.StopRunningCommand:
shouldStopRunningTask = true;
}
if (shouldStopRunningTask) {
if (isPossiblyRunningTaskRunInTerminal) {
this._terminalTaskManager.stopRunningTask();
} else {
this._outputChannelTaskManager.stopRunningTask();
}
return true;
} else {
return false;
}
}
private async startTask(
executable: string,
preCommandArgs: string[],
command: string,
args: string[],
cwd: string,
reason: CommandInvocationReason,
shouldExecuteCargoCommandInTerminal: boolean,
shouldParseOutput: boolean
): Promise<void> {
if (shouldExecuteCargoCommandInTerminal) {
await this._terminalTaskManager.startTask(
executable,
preCommandArgs,
command,
args,
cwd
);
} else {
// The output channel should be shown only if the user wants that.
// The only exception is checking invoked on saving the active document - in that case the output channel shouldn't be shown.
const shouldShowOutputChannel: boolean =
this._configuration.shouldShowRunningCargoTaskOutputChannel() &&
!(command === 'check' && reason === CommandInvocationReason.ActionOnSave);
await this._outputChannelTaskManager.startTask(
executable,
preCommandArgs,
command,
args,
cwd,
shouldParseOutput,
shouldShowOutputChannel
);
}
}
/**
* The user can specify some directory which Cargo commands should be run in. In this case,
* Cargo should be known whether the correct manifest is located. The function checks whether
* the user specify some directory and if it is, then adds the manifest path to the arguments
* and replaces the working directory
* @param args The arguments to change
* @param workingDirectory The current working directory
* @return The new arguments and new working directory
*/
private processPossibleUserRequestToChangeWorkingDirectory(
args: string[],
workingDirectory: string
): { args: string[], workingDirectory: string } {
const userWorkingDirectory = this._configuration.getCargoCwd();
if (userWorkingDirectory !== undefined && userWorkingDirectory !== workingDirectory) {
const manifestPath = join(workingDirectory, 'Cargo.toml');
args = ['--manifest-path', manifestPath].concat(args);
workingDirectory = userWorkingDirectory;
}
return { args, workingDirectory };
}
} | the_stack |
import * as vscode from "vscode";
import * as path from "path";
import * as fs from "fs";
import {
EditorProviderBase,
ReplacementTuple,
ViewCommand,
} from "../editor-base";
import {
onFrameInfoChanged,
onMachineTypeChanged,
onConnectionStateChanged,
} from "../../emulator/notifier";
import { communicatorInstance } from "../../emulator/communicator";
import { DisassemblyAnnotation } from "../../disassembler/annotations";
import {
machineConfigurationInstance,
DISASS_ANN_FILE,
} from "../../emulator/machine-config";
import {
getAssetsFileName,
getAssetsFileResource,
} from "../../extension-paths";
import { machineTypes } from "../../emulator/machine-info";
import {
DisassemblyItem,
DisassemblyOutput,
intToX4,
MemorySection,
MemorySectionType,
} from "../../disassembler/disassembly-helper";
import { Z80Disassembler } from "../../disassembler/z80-disassembler";
import { DiagViewFrame } from "@shared/machines/diag-info";
import { breakpointDefinitions } from "../../emulator/breakpoints";
import { onCommandExecuted } from "../../emulator/command-handler";
import { CmdNode } from "../../command-parser/command-line-nodes";
/**
* The annotation for the current machine
*/
const romAnnotations: (DisassemblyAnnotation | null)[] = [];
/**
* Full annotations with a particular rom page
*/
const fullAnnotations: (DisassemblyAnnotation | null)[] = [];
/**
* This provide implements the functionality of the Disassembly Editor
*/
export class DisassemblyEditorProvider extends EditorProviderBase {
private static readonly viewType = "kliveide.disassemblyEditor";
/**
* Registers this editor provider
* @param context Extension context
*/
static register(context: vscode.ExtensionContext): vscode.Disposable {
const provider = new DisassemblyEditorProvider(context);
const providerRegistration = vscode.window.registerCustomEditorProvider(
DisassemblyEditorProvider.viewType,
provider
);
return providerRegistration;
}
/**
* Instantiates an editor provider
* @param context Extension context
*/
constructor(protected readonly context: vscode.ExtensionContext) {
super(context);
}
title = "Klive Disassembly Editor";
htmlFileName = "disassembly.html";
/**
* The replacements that should be carried out on the HTML contents
* of this panel's view
*/
getContentReplacements(): ReplacementTuple[] {
return [
["stylefile", getAssetsFileResource("style.css")],
["jsfile", getAssetsFileResource("disass.bundle.js")],
];
}
/**
* Resolve a custom editor for a given text resource.
*
* @param document Document for the resource to resolve.
* @param webviewPanel The webview panel used to display the editor UI for this resource.
* @param token A cancellation token that indicates the result is no longer needed.
* @return Thenable indicating that the custom editor has been resolved.
*/
async resolveCustomTextEditor(
document: vscode.TextDocument,
webviewPanel: vscode.WebviewPanel,
_token: vscode.CancellationToken
): Promise<void> {
super.resolveCustomTextEditor(document, webviewPanel, _token);
// --- Take care that initial annotations are read
if (romAnnotations.length === 0) {
await readRomAnnotations();
}
// --- Watch for PC changes
let lastPc = -1;
this.toDispose(
webviewPanel,
onFrameInfoChanged((fi: DiagViewFrame) => {
if (lastPc !== fi.pc && fi.pc !== undefined) {
lastPc = fi.pc;
webviewPanel.webview.postMessage({
viewNotification: "pc",
pc: lastPc,
});
}
})
);
// --- Watch for breakpoint commands
this.toDispose(
webviewPanel,
onCommandExecuted((cmd: CmdNode) => {
if (cmd.type.includes("Breakpoint")) {
this.sendBreakpointsToView();
}
})
);
// --- Refresh annotations whenever machine type changes
this.toDispose(
webviewPanel,
onMachineTypeChanged(async () => {
await readRomAnnotations();
this.refreshView();
this.refreshViewport(Date.now());
})
);
// --- Refresh the view whenever connection restores
this.toDispose(
webviewPanel,
onConnectionStateChanged(async (connected: boolean) => {
if (connected) {
this.refreshViewport(Date.now());
}
})
);
// --- Make sure we get rid of the listener when our editor is closed.
webviewPanel.onDidDispose(() => {
super.disposePanel(webviewPanel);
});
}
/**
* Process view command
* @param panel The WebviewPanel that should process a message from its view
* @param viewCommand Command notification to process
*/
async processViewCommand(viewCommand: ViewCommand): Promise<void> {
switch (viewCommand.command) {
case "requestRefresh":
// --- Send the refresh command to the view
this.refreshView();
this.refreshViewport(Date.now());
break;
case "requestViewportRefresh":
this.refreshViewport(Date.now());
break;
case "setBreakpoint":
breakpointDefinitions.set({
address: (viewCommand as any).address,
});
await communicatorInstance.setBreakpoints(breakpointDefinitions.toArray());
this.sendBreakpointsToView();
break;
case "removeBreakpoint":
breakpointDefinitions.remove((viewCommand as any).address);
await communicatorInstance.setBreakpoints(breakpointDefinitions.toArray());
this.sendBreakpointsToView();
break;
}
}
/**
* Sends the current breakpoints to the webview
*/
protected sendBreakpointsToView(): void {
this.panel.webview.postMessage({
viewNotification: "breakpoints",
breakpoints: breakpointDefinitions.toArray(),
});
}
/**
* Sends messages to the view so that can refresh itself
*/
async refreshView(): Promise<void> {
this.sendInitialStateToView();
this.sendBreakpointsToView();
}
/**
* Refresh the viewport of the specified panel
* @param panel Panel to refresh
*/
async refreshViewport(start: number): Promise<void> {
try {
const memContents = await communicatorInstance.getMemory();
const bytes = new Uint8Array(Buffer.from(memContents, "base64"));
const disassemblyOut = await disassembly(
bytes,
0x0000,
0xffff,
fullAnnotations[0]
);
// const fullView = await getFullDisassembly();
this.panel.webview.postMessage({
viewNotification: "refreshViewport",
fullView: JSON.stringify(disassemblyOut.outputItems),
start,
});
} catch (err) {
// --- This exception in intentionally ignored
}
}
}
/**
* Reads the ROM annotations of the specified machine type
* @param machineType
*/
async function readRomAnnotations(): Promise<void> {
// --- We need machine configuration to carry on
const machineType = machineConfigurationInstance.configuration.type;
const config = machineTypes[machineType];
if (!config) {
return;
}
// --- Number of ROM disassemblies to cache
const roms = config.paging.supportsPaging ? config.paging.roms : 1;
for (let i = 0; i < roms; i++) {
if (romAnnotations[i] === undefined) {
const romAnn = (romAnnotations[i] = getRomAnnotation(i));
const fullAnnotation = getFullAnnotation();
if (romAnn && fullAnnotation) {
fullAnnotation.merge(romAnn);
fullAnnotations[i] = fullAnnotation;
} else {
fullAnnotations[i] = romAnn;
}
}
}
}
/**
* Gets the annotation of the specified ROM page
* @param rom ROM page number
*/
function getRomAnnotation(rom: number): DisassemblyAnnotation | null {
// --- Let's assume on open project folder
const folders = vscode.workspace.workspaceFolders;
const projFolder = folders ? folders[0].uri.fsPath : null;
if (!projFolder) {
return null;
}
rom = rom ?? 0;
try {
// --- Obtain the file for the annotations
const annotations = machineConfigurationInstance.configuration?.annotations;
if (!annotations) {
return null;
}
let romAnnotationFile = annotations[rom];
if (romAnnotationFile.startsWith("#")) {
romAnnotationFile = getAssetsFileName(
path.join("annotations", romAnnotationFile.substr(1))
);
} else {
romAnnotationFile = path.join(projFolder, romAnnotationFile);
}
// --- Get root annotations from the file
const contents = fs.readFileSync(romAnnotationFile, "utf8");
const annotation = DisassemblyAnnotation.deserialize(contents);
return annotation;
} catch (err) {
console.log(err);
}
return null;
}
/**
* Gets the full annotation merged with the specified ROM page
*/
function getFullAnnotation(): DisassemblyAnnotation | null {
try {
const folders = vscode.workspace.workspaceFolders;
const projFolder = folders ? folders[0].uri.fsPath : null;
if (!projFolder) {
return null;
}
const viewFilePath = path.join(projFolder, DISASS_ANN_FILE);
const viewContents = fs.readFileSync(viewFilePath, "utf8");
return DisassemblyAnnotation.deserialize(viewContents);
} catch (err) {
console.log(err);
}
return null;
}
/**
* Gets the disassembly for the specified memory range
* @param from Start address
* @param to End address
*/
async function disassembly(
bytes: Uint8Array,
from: number,
to: number,
annotations?: DisassemblyAnnotation | null
): Promise<DisassemblyOutput | null> {
// --- Use the memory sections in the annotations
const sections: MemorySection[] = annotations?.memoryMap?.sections ?? [
new MemorySection(from, to, MemorySectionType.Disassemble),
];
// --- Do the disassembly
const disassembler = new Z80Disassembler(sections, bytes);
const rawItems = await disassembler.disassemble(from, to);
if (!rawItems) {
return rawItems;
}
// --- Compose annotations
const updatedItems: DisassemblyItem[] = [];
for (const item of rawItems.outputItems) {
const prefixComment = annotations?.prefixComments.get(item.address);
if (prefixComment) {
const prefixItem: DisassemblyItem = {
address: item.address,
isPrefixItem: true,
prefixComment,
};
updatedItems.push(prefixItem);
}
const formattedLabel = annotations?.labels.get(item.address);
item.formattedLabel =
formattedLabel ?? (item.hasLabel ? "L" + intToX4(item.address) : "");
item.formattedComment = item.hardComment ? item.hardComment + " " : "";
const comment = annotations?.comments.get(item.address);
if (comment) {
item.formattedComment += comment;
}
if (annotations && item.tokenLength && item.tokenLength > 0) {
let symbol: string | undefined;
if (item.hasLabelSymbol && item.symbolValue) {
const label = annotations.labels.get(item.symbolValue);
if (label) {
symbol = label;
}
} else {
symbol = annotations.literalReplacements.get(item.address);
}
if (symbol && item.instruction && item.tokenPosition) {
item.instruction =
item.instruction.substr(0, item.tokenPosition) +
symbol +
item.instruction.substr(item.tokenPosition + item.tokenLength);
}
}
updatedItems.push(item);
}
rawItems.replaceOutputItems(updatedItems);
return rawItems;
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs, enums } from "../types";
import * as utilities from "../utilities";
/**
* Creates a WAFv2 Web ACL resource.
*
* ## Example Usage
*
* This resource is based on `aws.wafv2.RuleGroup`, check the documentation of the `aws.wafv2.RuleGroup` resource to see examples of the various available statements.
* ### Managed Rule
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const example = new aws.wafv2.WebAcl("example", {
* defaultAction: {
* allow: {},
* },
* description: "Example of a managed rule.",
* rules: [{
* name: "rule-1",
* overrideAction: {
* count: {},
* },
* priority: 1,
* statement: {
* managedRuleGroupStatement: {
* excludedRules: [
* {
* name: "SizeRestrictions_QUERYSTRING",
* },
* {
* name: "NoUserAgent_HEADER",
* },
* ],
* name: "AWSManagedRulesCommonRuleSet",
* scopeDownStatement: {
* geoMatchStatement: {
* countryCodes: [
* "US",
* "NL",
* ],
* },
* },
* vendorName: "AWS",
* },
* },
* visibilityConfig: {
* cloudwatchMetricsEnabled: false,
* metricName: "friendly-rule-metric-name",
* sampledRequestsEnabled: false,
* },
* }],
* scope: "REGIONAL",
* tags: {
* Tag1: "Value1",
* Tag2: "Value2",
* },
* visibilityConfig: {
* cloudwatchMetricsEnabled: false,
* metricName: "friendly-metric-name",
* sampledRequestsEnabled: false,
* },
* });
* ```
* ### Rate Based
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const example = new aws.wafv2.WebAcl("example", {
* defaultAction: {
* block: {},
* },
* description: "Example of a rate based statement.",
* rules: [{
* action: {
* count: {},
* },
* name: "rule-1",
* priority: 1,
* statement: {
* rateBasedStatement: {
* aggregateKeyType: "IP",
* limit: 10000,
* scopeDownStatement: {
* geoMatchStatement: {
* countryCodes: [
* "US",
* "NL",
* ],
* },
* },
* },
* },
* visibilityConfig: {
* cloudwatchMetricsEnabled: false,
* metricName: "friendly-rule-metric-name",
* sampledRequestsEnabled: false,
* },
* }],
* scope: "REGIONAL",
* tags: {
* Tag1: "Value1",
* Tag2: "Value2",
* },
* visibilityConfig: {
* cloudwatchMetricsEnabled: false,
* metricName: "friendly-metric-name",
* sampledRequestsEnabled: false,
* },
* });
* ```
* ### Rule Group Reference
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const example = new aws.wafv2.RuleGroup("example", {
* capacity: 10,
* scope: "REGIONAL",
* rules: [
* {
* name: "rule-1",
* priority: 1,
* action: {
* count: {},
* },
* statement: {
* geoMatchStatement: {
* countryCodes: ["NL"],
* },
* },
* visibilityConfig: {
* cloudwatchMetricsEnabled: false,
* metricName: "friendly-rule-metric-name",
* sampledRequestsEnabled: false,
* },
* },
* {
* name: "rule-to-exclude-a",
* priority: 10,
* action: {
* allow: {},
* },
* statement: {
* geoMatchStatement: {
* countryCodes: ["US"],
* },
* },
* visibilityConfig: {
* cloudwatchMetricsEnabled: false,
* metricName: "friendly-rule-metric-name",
* sampledRequestsEnabled: false,
* },
* },
* {
* name: "rule-to-exclude-b",
* priority: 15,
* action: {
* allow: {},
* },
* statement: {
* geoMatchStatement: {
* countryCodes: ["GB"],
* },
* },
* visibilityConfig: {
* cloudwatchMetricsEnabled: false,
* metricName: "friendly-rule-metric-name",
* sampledRequestsEnabled: false,
* },
* },
* ],
* visibilityConfig: {
* cloudwatchMetricsEnabled: false,
* metricName: "friendly-metric-name",
* sampledRequestsEnabled: false,
* },
* });
* const test = new aws.wafv2.WebAcl("test", {
* scope: "REGIONAL",
* defaultAction: {
* block: {},
* },
* rules: [{
* name: "rule-1",
* priority: 1,
* overrideAction: {
* count: {},
* },
* statement: {
* ruleGroupReferenceStatement: {
* arn: example.arn,
* excludedRules: [
* {
* name: "rule-to-exclude-b",
* },
* {
* name: "rule-to-exclude-a",
* },
* ],
* },
* },
* visibilityConfig: {
* cloudwatchMetricsEnabled: false,
* metricName: "friendly-rule-metric-name",
* sampledRequestsEnabled: false,
* },
* }],
* tags: {
* Tag1: "Value1",
* Tag2: "Value2",
* },
* visibilityConfig: {
* cloudwatchMetricsEnabled: false,
* metricName: "friendly-metric-name",
* sampledRequestsEnabled: false,
* },
* });
* ```
*
* ## Import
*
* WAFv2 Web ACLs can be imported using `ID/Name/Scope` e.g.
*
* ```sh
* $ pulumi import aws:wafv2/webAcl:WebAcl example a1b2c3d4-d5f6-7777-8888-9999aaaabbbbcccc/example/REGIONAL
* ```
*/
export class WebAcl extends pulumi.CustomResource {
/**
* Get an existing WebAcl 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?: WebAclState, opts?: pulumi.CustomResourceOptions): WebAcl {
return new WebAcl(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'aws:wafv2/webAcl:WebAcl';
/**
* Returns true if the given object is an instance of WebAcl. 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 WebAcl {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === WebAcl.__pulumiType;
}
/**
* The Amazon Resource Name (ARN) of the IP Set that this statement references.
*/
public /*out*/ readonly arn!: pulumi.Output<string>;
/**
* The web ACL capacity units (WCUs) currently being used by this web ACL.
*/
public /*out*/ readonly capacity!: pulumi.Output<number>;
/**
* The action to perform if none of the `rules` contained in the WebACL match. See Default Action below for details.
*/
public readonly defaultAction!: pulumi.Output<outputs.wafv2.WebAclDefaultAction>;
/**
* A friendly description of the WebACL.
*/
public readonly description!: pulumi.Output<string | undefined>;
public /*out*/ readonly lockToken!: pulumi.Output<string>;
/**
* The name of the custom header. For custom request header insertion, when AWS WAF inserts the header into the request, it prefixes this name `x-amzn-waf-`, to avoid confusion with the headers that are already in the request. For example, for the header name `sample`, AWS WAF inserts the header `x-amzn-waf-sample`.
*/
public readonly name!: pulumi.Output<string>;
/**
* The rule blocks used to identify the web requests that you want to `allow`, `block`, or `count`. See Rules below for details.
*/
public readonly rules!: pulumi.Output<outputs.wafv2.WebAclRule[] | undefined>;
/**
* Specifies whether this is for an AWS CloudFront distribution or for a regional application. Valid values are `CLOUDFRONT` or `REGIONAL`. To work with CloudFront, you must also specify the region `us-east-1` (N. Virginia) on the AWS provider.
*/
public readonly scope!: pulumi.Output<string>;
/**
* An map of key:value pairs to associate with the resource. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level.
*/
public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* A map of tags assigned to the resource, including those inherited from the provider .
*/
public readonly tagsAll!: pulumi.Output<{[key: string]: string}>;
/**
* Defines and enables Amazon CloudWatch metrics and web request sample collection. See Visibility Configuration below for details.
*/
public readonly visibilityConfig!: pulumi.Output<outputs.wafv2.WebAclVisibilityConfig>;
/**
* Create a WebAcl 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: WebAclArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: WebAclArgs | WebAclState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as WebAclState | undefined;
inputs["arn"] = state ? state.arn : undefined;
inputs["capacity"] = state ? state.capacity : undefined;
inputs["defaultAction"] = state ? state.defaultAction : undefined;
inputs["description"] = state ? state.description : undefined;
inputs["lockToken"] = state ? state.lockToken : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["rules"] = state ? state.rules : undefined;
inputs["scope"] = state ? state.scope : undefined;
inputs["tags"] = state ? state.tags : undefined;
inputs["tagsAll"] = state ? state.tagsAll : undefined;
inputs["visibilityConfig"] = state ? state.visibilityConfig : undefined;
} else {
const args = argsOrState as WebAclArgs | undefined;
if ((!args || args.defaultAction === undefined) && !opts.urn) {
throw new Error("Missing required property 'defaultAction'");
}
if ((!args || args.scope === undefined) && !opts.urn) {
throw new Error("Missing required property 'scope'");
}
if ((!args || args.visibilityConfig === undefined) && !opts.urn) {
throw new Error("Missing required property 'visibilityConfig'");
}
inputs["defaultAction"] = args ? args.defaultAction : undefined;
inputs["description"] = args ? args.description : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["rules"] = args ? args.rules : undefined;
inputs["scope"] = args ? args.scope : undefined;
inputs["tags"] = args ? args.tags : undefined;
inputs["tagsAll"] = args ? args.tagsAll : undefined;
inputs["visibilityConfig"] = args ? args.visibilityConfig : undefined;
inputs["arn"] = undefined /*out*/;
inputs["capacity"] = undefined /*out*/;
inputs["lockToken"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(WebAcl.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering WebAcl resources.
*/
export interface WebAclState {
/**
* The Amazon Resource Name (ARN) of the IP Set that this statement references.
*/
arn?: pulumi.Input<string>;
/**
* The web ACL capacity units (WCUs) currently being used by this web ACL.
*/
capacity?: pulumi.Input<number>;
/**
* The action to perform if none of the `rules` contained in the WebACL match. See Default Action below for details.
*/
defaultAction?: pulumi.Input<inputs.wafv2.WebAclDefaultAction>;
/**
* A friendly description of the WebACL.
*/
description?: pulumi.Input<string>;
lockToken?: pulumi.Input<string>;
/**
* The name of the custom header. For custom request header insertion, when AWS WAF inserts the header into the request, it prefixes this name `x-amzn-waf-`, to avoid confusion with the headers that are already in the request. For example, for the header name `sample`, AWS WAF inserts the header `x-amzn-waf-sample`.
*/
name?: pulumi.Input<string>;
/**
* The rule blocks used to identify the web requests that you want to `allow`, `block`, or `count`. See Rules below for details.
*/
rules?: pulumi.Input<pulumi.Input<inputs.wafv2.WebAclRule>[]>;
/**
* Specifies whether this is for an AWS CloudFront distribution or for a regional application. Valid values are `CLOUDFRONT` or `REGIONAL`. To work with CloudFront, you must also specify the region `us-east-1` (N. Virginia) on the AWS provider.
*/
scope?: pulumi.Input<string>;
/**
* An map of key:value pairs to associate with the resource. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* A map of tags assigned to the resource, including those inherited from the provider .
*/
tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Defines and enables Amazon CloudWatch metrics and web request sample collection. See Visibility Configuration below for details.
*/
visibilityConfig?: pulumi.Input<inputs.wafv2.WebAclVisibilityConfig>;
}
/**
* The set of arguments for constructing a WebAcl resource.
*/
export interface WebAclArgs {
/**
* The action to perform if none of the `rules` contained in the WebACL match. See Default Action below for details.
*/
defaultAction: pulumi.Input<inputs.wafv2.WebAclDefaultAction>;
/**
* A friendly description of the WebACL.
*/
description?: pulumi.Input<string>;
/**
* The name of the custom header. For custom request header insertion, when AWS WAF inserts the header into the request, it prefixes this name `x-amzn-waf-`, to avoid confusion with the headers that are already in the request. For example, for the header name `sample`, AWS WAF inserts the header `x-amzn-waf-sample`.
*/
name?: pulumi.Input<string>;
/**
* The rule blocks used to identify the web requests that you want to `allow`, `block`, or `count`. See Rules below for details.
*/
rules?: pulumi.Input<pulumi.Input<inputs.wafv2.WebAclRule>[]>;
/**
* Specifies whether this is for an AWS CloudFront distribution or for a regional application. Valid values are `CLOUDFRONT` or `REGIONAL`. To work with CloudFront, you must also specify the region `us-east-1` (N. Virginia) on the AWS provider.
*/
scope: pulumi.Input<string>;
/**
* An map of key:value pairs to associate with the resource. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* A map of tags assigned to the resource, including those inherited from the provider .
*/
tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Defines and enables Amazon CloudWatch metrics and web request sample collection. See Visibility Configuration below for details.
*/
visibilityConfig: pulumi.Input<inputs.wafv2.WebAclVisibilityConfig>;
} | the_stack |
import { assert, assertEquals } from "../testing/asserts.ts";
import {
copy,
iterateReader,
iterateReaderSync,
readableStreamFromIterable,
readableStreamFromReader,
readAll,
readAllSync,
readerFromIterable,
readerFromStreamReader,
writableStreamFromWriter,
writeAll,
writeAllSync,
writerFromStreamWriter,
} from "./conversion.ts";
import { Buffer } from "../io/buffer.ts";
import { concat, copy as copyBytes } from "../bytes/mod.ts";
function repeat(c: string, bytes: number): Uint8Array {
assertEquals(c.length, 1);
const ui8 = new Uint8Array(bytes);
ui8.fill(c.charCodeAt(0));
return ui8;
}
Deno.test("[streams] readerFromIterable()", async function () {
const reader = readerFromIterable((function* () {
const encoder = new TextEncoder();
for (const string of ["hello", "deno", "foo"]) {
yield encoder.encode(string);
}
})());
const readStrings = [];
const decoder = new TextDecoder();
const p = new Uint8Array(4);
while (true) {
const n = await reader.read(p);
if (n == null) {
break;
}
readStrings.push(decoder.decode(p.slice(0, n)));
}
assertEquals(readStrings, ["hell", "o", "deno", "foo"]);
});
Deno.test("[streams] writerFromStreamWriter()", async function () {
const written: string[] = [];
const chunks: string[] = ["hello", "deno", "land"];
const writableStream = new WritableStream({
write(chunk): void {
const decoder = new TextDecoder();
written.push(decoder.decode(chunk));
},
});
const encoder = new TextEncoder();
const writer = writerFromStreamWriter(writableStream.getWriter());
for (const chunk of chunks) {
const n = await writer.write(encoder.encode(chunk));
// stream writers always write all the bytes
assertEquals(n, chunk.length);
}
assertEquals(written, chunks);
});
Deno.test("[streams] readerFromStreamReader()", async function () {
const chunks: string[] = ["hello", "deno", "land"];
const expected = chunks.slice();
const readChunks: Uint8Array[] = [];
const readableStream = new ReadableStream({
pull(controller): void {
const encoder = new TextEncoder();
const chunk = chunks.shift();
if (!chunk) return controller.close();
controller.enqueue(encoder.encode(chunk));
},
});
const decoder = new TextDecoder();
const reader = readerFromStreamReader(readableStream.getReader());
let i = 0;
while (true) {
const b = new Uint8Array(1024);
const n = await reader.read(b);
if (n === null) break;
readChunks.push(b.subarray(0, n));
assert(i < expected.length);
i++;
}
assertEquals(
expected,
readChunks.map((chunk) => decoder.decode(chunk)),
);
});
Deno.test("[streams] readerFromStreamReader() big chunks", async function () {
const bufSize = 1024;
const chunkSize = 3 * bufSize;
const writer = new Buffer();
// A readable stream can enqueue chunks bigger than Copy bufSize
// Reader returned by toReader should enqueue exceeding bytes
const chunks: string[] = [
"a".repeat(chunkSize),
"b".repeat(chunkSize),
"c".repeat(chunkSize),
];
const expected = chunks.slice();
const readableStream = new ReadableStream({
pull(controller): void {
const encoder = new TextEncoder();
const chunk = chunks.shift();
if (!chunk) return controller.close();
controller.enqueue(encoder.encode(chunk));
},
});
const reader = readerFromStreamReader(readableStream.getReader());
const n = await copy(reader, writer, { bufSize });
const expectedWritten = chunkSize * expected.length;
assertEquals(n, chunkSize * expected.length);
assertEquals(writer.length, expectedWritten);
});
Deno.test("[streams] readerFromStreamReader() irregular chunks", async function () {
const bufSize = 1024;
const chunkSize = 3 * bufSize;
const writer = new Buffer();
// A readable stream can enqueue chunks bigger than Copy bufSize
// Reader returned by toReader should enqueue exceeding bytes
const chunks: Uint8Array[] = [
repeat("a", chunkSize),
repeat("b", chunkSize + 253),
repeat("c", chunkSize + 8),
];
const expected = new Uint8Array(
chunks
.slice()
.map((chunk) => [...chunk])
.flat(),
);
const readableStream = new ReadableStream({
pull(controller): void {
const chunk = chunks.shift();
if (!chunk) return controller.close();
controller.enqueue(chunk);
},
});
const reader = readerFromStreamReader(readableStream.getReader());
const n = await copy(reader, writer, { bufSize });
assertEquals(n, expected.length);
assertEquals(expected, writer.bytes());
});
class MockWriterCloser implements Deno.Writer, Deno.Closer {
chunks: Uint8Array[] = [];
closeCall = 0;
write(p: Uint8Array): Promise<number> {
if (this.closeCall) {
throw new Error("already closed");
}
if (p.length) {
this.chunks.push(p);
}
return Promise.resolve(p.length);
}
close() {
this.closeCall++;
}
}
Deno.test("[streams] writableStreamFromWriter()", async function () {
const written: string[] = [];
const chunks: string[] = ["hello", "deno", "land"];
const decoder = new TextDecoder();
// deno-lint-ignore require-await
async function write(p: Uint8Array): Promise<number> {
written.push(decoder.decode(p));
return p.length;
}
const writableStream = writableStreamFromWriter({ write });
const encoder = new TextEncoder();
const streamWriter = writableStream.getWriter();
for (const chunk of chunks) {
await streamWriter.write(encoder.encode(chunk));
}
assertEquals(written, chunks);
});
Deno.test("[streams] writableStreamFromWriter() - calls close on close", async function () {
const written: string[] = [];
const chunks: string[] = ["hello", "deno", "land"];
const decoder = new TextDecoder();
const writer = new MockWriterCloser();
const writableStream = writableStreamFromWriter(writer);
const encoder = new TextEncoder();
const streamWriter = writableStream.getWriter();
for (const chunk of chunks) {
await streamWriter.write(encoder.encode(chunk));
}
await streamWriter.close();
for (const chunk of writer.chunks) {
written.push(decoder.decode(chunk));
}
assertEquals(written, chunks);
assertEquals(writer.closeCall, 1);
});
Deno.test("[streams] writableStreamFromWriter() - calls close on abort", async function () {
const written: string[] = [];
const chunks: string[] = ["hello", "deno", "land"];
const decoder = new TextDecoder();
const writer = new MockWriterCloser();
const writableStream = writableStreamFromWriter(writer);
const encoder = new TextEncoder();
const streamWriter = writableStream.getWriter();
for (const chunk of chunks) {
await streamWriter.write(encoder.encode(chunk));
}
await streamWriter.abort();
for (const chunk of writer.chunks) {
written.push(decoder.decode(chunk));
}
assertEquals(written, chunks);
assertEquals(writer.closeCall, 1);
});
Deno.test("[streams] writableStreamFromWriter() - doesn't call close with autoClose false", async function () {
const written: string[] = [];
const chunks: string[] = ["hello", "deno", "land"];
const decoder = new TextDecoder();
const writer = new MockWriterCloser();
const writableStream = writableStreamFromWriter(writer, { autoClose: false });
const encoder = new TextEncoder();
const streamWriter = writableStream.getWriter();
for (const chunk of chunks) {
await streamWriter.write(encoder.encode(chunk));
}
await streamWriter.close();
for (const chunk of writer.chunks) {
written.push(decoder.decode(chunk));
}
assertEquals(written, chunks);
assertEquals(writer.closeCall, 0);
});
Deno.test("[streams] readableStreamFromIterable() array", async function () {
const strings: string[] = ["hello", "deno", "land"];
const encoder = new TextEncoder();
const readableStream = readableStreamFromIterable(
strings.map((s) => encoder.encode(s)),
);
const readStrings = [];
const decoder = new TextDecoder();
for await (const chunk of readableStream) {
readStrings.push(decoder.decode(chunk));
}
assertEquals(readStrings, strings);
});
Deno.test("[streams] readableStreamFromIterable() generator", async function () {
const strings: string[] = ["hello", "deno", "land"];
const readableStream = readableStreamFromIterable((function* () {
const encoder = new TextEncoder();
for (const string of strings) {
yield encoder.encode(string);
}
})());
const readStrings = [];
const decoder = new TextDecoder();
for await (const chunk of readableStream) {
readStrings.push(decoder.decode(chunk));
}
assertEquals(readStrings, strings);
});
Deno.test("[streams] readableStreamFromIterable() cancel", async function () {
let generatorError = null;
const readable = readableStreamFromIterable(async function* () {
try {
yield "foo";
} catch (error) {
generatorError = error;
}
}());
const reader = readable.getReader();
assertEquals(await reader.read(), { value: "foo", done: false });
const cancelReason = new Error("Cancelled by consumer.");
await reader.cancel(cancelReason);
assertEquals(generatorError, cancelReason);
});
class MockReaderCloser implements Deno.Reader, Deno.Closer {
chunks: Uint8Array[] = [];
closeCall = 0;
read(p: Uint8Array): Promise<number | null> {
if (this.closeCall) {
throw new Error("already closed");
}
if (p.length === 0) {
return Promise.resolve(0);
}
const chunk = this.chunks.shift();
if (chunk) {
const copied = copyBytes(chunk, p);
if (copied < chunk.length) {
this.chunks.unshift(chunk.subarray(copied));
}
return Promise.resolve(copied);
}
return Promise.resolve(null);
}
close() {
this.closeCall++;
}
}
Deno.test("[streams] readableStreamFromReader()", async function () {
const encoder = new TextEncoder();
const reader = new Buffer(encoder.encode("hello deno land"));
const stream = readableStreamFromReader(reader);
const actual: Uint8Array[] = [];
for await (const read of stream) {
actual.push(read);
}
const decoder = new TextDecoder();
assertEquals(decoder.decode(concat(...actual)), "hello deno land");
});
Deno.test({
name: "[streams] readableStreamFromReader() auto closes closer",
async fn() {},
});
Deno.test("[streams] readableStreamFromReader() - calls close", async function () {
const encoder = new TextEncoder();
const reader = new MockReaderCloser();
reader.chunks = [
encoder.encode("hello "),
encoder.encode("deno "),
encoder.encode("land"),
];
const stream = readableStreamFromReader(reader);
const actual: Uint8Array[] = [];
for await (const read of stream) {
actual.push(read);
}
const decoder = new TextDecoder();
assertEquals(decoder.decode(concat(...actual)), "hello deno land");
assertEquals(reader.closeCall, 1);
});
Deno.test("[streams] readableStreamFromReader() - doesn't call close with autoClose false", async function () {
const encoder = new TextEncoder();
const reader = new MockReaderCloser();
reader.chunks = [
encoder.encode("hello "),
encoder.encode("deno "),
encoder.encode("land"),
];
const stream = readableStreamFromReader(reader, { autoClose: false });
const actual: Uint8Array[] = [];
for await (const read of stream) {
actual.push(read);
}
const decoder = new TextDecoder();
assertEquals(decoder.decode(concat(...actual)), "hello deno land");
assertEquals(reader.closeCall, 0);
});
Deno.test("[streams] readableStreamFromReader() - chunkSize", async function () {
const encoder = new TextEncoder();
const reader = new MockReaderCloser();
reader.chunks = [
encoder.encode("hello "),
encoder.encode("deno "),
encoder.encode("land"),
];
const stream = readableStreamFromReader(reader, { chunkSize: 2 });
const actual: Uint8Array[] = [];
for await (const read of stream) {
actual.push(read);
}
const decoder = new TextDecoder();
assertEquals(actual.length, 8);
assertEquals(decoder.decode(concat(...actual)), "hello deno land");
assertEquals(reader.closeCall, 1);
});
// N controls how many iterations of certain checks are performed.
const N = 100;
let testBytes: Uint8Array | null;
export function init(): void {
if (testBytes == null) {
testBytes = new Uint8Array(N);
for (let i = 0; i < N; i++) {
testBytes[i] = "a".charCodeAt(0) + (i % 26);
}
}
}
Deno.test("testReadAll", async () => {
init();
assert(testBytes);
const reader = new Buffer(testBytes.buffer);
const actualBytes = await readAll(reader);
assertEquals(testBytes.byteLength, actualBytes.byteLength);
for (let i = 0; i < testBytes.length; ++i) {
assertEquals(testBytes[i], actualBytes[i]);
}
});
Deno.test("testReadAllSync", () => {
init();
assert(testBytes);
const reader = new Buffer(testBytes.buffer);
const actualBytes = readAllSync(reader);
assertEquals(testBytes.byteLength, actualBytes.byteLength);
for (let i = 0; i < testBytes.length; ++i) {
assertEquals(testBytes[i], actualBytes[i]);
}
});
Deno.test("testwriteAll", async () => {
init();
assert(testBytes);
const writer = new Buffer();
await writeAll(writer, testBytes);
const actualBytes = writer.bytes();
assertEquals(testBytes.byteLength, actualBytes.byteLength);
for (let i = 0; i < testBytes.length; ++i) {
assertEquals(testBytes[i], actualBytes[i]);
}
});
Deno.test("testWriteAllSync", () => {
init();
assert(testBytes);
const writer = new Buffer();
writeAllSync(writer, testBytes);
const actualBytes = writer.bytes();
assertEquals(testBytes.byteLength, actualBytes.byteLength);
for (let i = 0; i < testBytes.length; ++i) {
assertEquals(testBytes[i], actualBytes[i]);
}
});
Deno.test("iterateReader", async () => {
// ref: https://github.com/denoland/deno/issues/2330
const encoder = new TextEncoder();
class TestReader implements Deno.Reader {
#offset = 0;
#buf: Uint8Array;
constructor(s: string) {
this.#buf = new Uint8Array(encoder.encode(s));
}
read(p: Uint8Array): Promise<number | null> {
const n = Math.min(p.byteLength, this.#buf.byteLength - this.#offset);
p.set(this.#buf.slice(this.#offset, this.#offset + n));
this.#offset += n;
if (n === 0) {
return Promise.resolve(null);
}
return Promise.resolve(n);
}
}
const reader = new TestReader("hello world!");
let totalSize = 0;
for await (const buf of iterateReader(reader)) {
totalSize += buf.byteLength;
}
assertEquals(totalSize, 12);
});
Deno.test("iterateReaderSync", () => {
// ref: https://github.com/denoland/deno/issues/2330
const encoder = new TextEncoder();
class TestReader implements Deno.ReaderSync {
#offset = 0;
#buf: Uint8Array;
constructor(s: string) {
this.#buf = new Uint8Array(encoder.encode(s));
}
readSync(p: Uint8Array): number | null {
const n = Math.min(p.byteLength, this.#buf.byteLength - this.#offset);
p.set(this.#buf.slice(this.#offset, this.#offset + n));
this.#offset += n;
if (n === 0) {
return null;
}
return n;
}
}
const reader = new TestReader("hello world!");
let totalSize = 0;
for (const buf of iterateReaderSync(reader)) {
totalSize += buf.byteLength;
}
assertEquals(totalSize, 12);
}); | the_stack |
import { Property, Complex, ChildProperty } from '@syncfusion/ej2-base';
import { TextStyle, Margin } from '../core/appearance';
import { Point } from '../primitives/point';
import { TextStyleModel, MarginModel } from '../core/appearance-model';
import { PointModel } from '../primitives/point-model';
import { HyperlinkModel, AnnotationModel } from '../objects/annotation-model';
import { HorizontalAlignment, VerticalAlignment, AnnotationAlignment, AnnotationTypes, TextDecoration, AnnotationType } from '../enum/enum';
import { AnnotationConstraints } from '../enum/enum';
import { randomId } from '../utility/base-util';
/**
* Defines the hyperlink for the annotations in the nodes/connectors
*/
export class Hyperlink extends ChildProperty<Hyperlink> {
/**
* Sets the fill color of the hyperlink
*
* @default 'blue'
*/
@Property('blue')
public color: string;
/**
* Defines the content for hyperlink
*
* @default ''
*/
@Property('')
public content: string;
/**
* Defines the link for hyperlink
*
* @default ''
*/
@Property('')
public link: string;
/**
* Defines how the link should be decorated. For example, with underline/over line
* * Overline - Decorates the text with a line above the text
* * Underline - Decorates the text with an underline
* * LineThrough - Decorates the text by striking it with a line
* * None - Text will not have any specific decoration
*
* @default 'None'
*/
@Property('None')
public textDecoration: TextDecoration;
}
/**
* Defines the textual description of nodes/connectors
*/
export class Annotation extends ChildProperty<Annotation> {
/**
* Sets the textual description of the node/connector
*
* @default ''
*/
@Property('')
public content: string;
/**
* Sets the textual description of the node/connector
*
* @default 'undefined'
*/
@Property(undefined)
public template: string | HTMLElement;
/**
* Defines the type of annotation template
* String - Defines annotation template to be in string
* Template - Defines annotation template to be in html content
*
* @default 'String'
*/
@Property('String')
public annotationType: AnnotationType;
/**
* Defines the visibility of the label
*
* @default true
*/
@Property(true)
public visibility: boolean;
/**
* Enables or disables the default behaviors of the label.
* * ReadOnly - Enables/Disables the ReadOnly Constraints
* * InheritReadOnly - Enables/Disables the InheritReadOnly Constraints
*
* @default 'InheritReadOnly'
* @aspNumberEnum
*/
@Property(AnnotationConstraints.InheritReadOnly)
public constraints: AnnotationConstraints;
/**
* Sets the hyperlink of the label
* ```html
* <div id='diagram'></div>
* ```
* ```typescript
* let nodes: NodeModel[] = [{
* id: 'node1', width: 100, height: 100, offsetX: 100, offsetY: 100,
* annotations: [{ id: 'label1',
* content: 'Default Shape', style: { color: 'red' },
* hyperlink: { link: 'https://www.google.com', color : 'blue', textDecoration : 'Overline', content : 'google' }
* }, {content: 'text', constraints: ~AnnotationConstraints.InheritReadOnly
* }],
* }];
* let diagram: Diagram = new Diagram({
* ...
* nodes : nodes,
* ...
* });
* diagram.appendTo('#diagram');
* ```
*
* @aspDefaultValueIgnore
* @default undefined
*/
@Complex<HyperlinkModel>(undefined, Hyperlink)
public hyperlink: HyperlinkModel;
/**
* Defines the unique id of the annotation
*
* @default ''
*/
@Property('')
public id: string;
/**
* Sets the width of the text
*
* @aspDefaultValueIgnore
* @default undefined
*/
@Property()
public width: number;
/**
* Sets the height of the text
*
* @aspDefaultValueIgnore
* @default undefined
*/
@Property()
public height: number;
/**
* Sets the rotate angle of the text
*
* @default 0
*/
@Property(0)
public rotateAngle: number;
/**
* Defines the appearance of the text
*
* @default new TextStyle()
*/
@Complex<TextStyleModel>({ strokeWidth: 0, strokeColor: 'transparent', fill: 'transparent' }, TextStyle)
public style: TextStyleModel;
/**
* Sets the horizontal alignment of the text with respect to the parent node/connector
* * Stretch - Stretches the diagram element throughout its immediate parent
* * Left - Aligns the diagram element at the left of its immediate parent
* * Right - Aligns the diagram element at the right of its immediate parent
* * Center - Aligns the diagram element at the center of its immediate parent
* * Auto - Aligns the diagram element based on the characteristics of its immediate parent
*
* @default 'Center'
*/
@Property('Center')
public horizontalAlignment: HorizontalAlignment;
/**
* Sets the vertical alignment of the text with respect to the parent node/connector
* * Stretch - Stretches the diagram element throughout its immediate parent
* * Top - Aligns the diagram element at the top of its immediate parent
* * Bottom - Aligns the diagram element at the bottom of its immediate parent
* * Center - Aligns the diagram element at the center of its immediate parent
* * Auto - Aligns the diagram element based on the characteristics of its immediate parent
*
* @default 'Center'
*/
@Property('Center')
public verticalAlignment: VerticalAlignment;
/**
* Sets the space to be left between an annotation and its parent node/connector
*
* @default new Margin(0,0,0,0)
*/
@Complex<MarginModel>({}, Margin)
public margin: MarginModel;
/**
* Sets the space to be left between an annotation and its parent node/connector
*
* @default new Margin(20,20,20,20)
*/
@Complex<MarginModel>({ top: undefined, bottom: undefined, left: undefined, right: undefined }, Margin)
public dragLimit: MarginModel;
/**
* Sets the type of the annotation
* * Shape - Sets the annotation type as Shape
* * Path - Sets the annotation type as Path
*
* @default 'Shape'
*/
@Property('Shape')
public type: AnnotationTypes;
/**
* Allows the user to save custom information/data about an annotation
* ```html
* <div id='diagram'></div>
* ```
* ```typescript
* let addInfo: {} = { content: 'label' };
* let nodes: NodeModel[] = [{
* id: 'node1', width: 100, height: 100, offsetX: 100, offsetY: 100,
* annotations: [{ id: 'label1',
* content: 'text', constraints: ~AnnotationConstraints.InheritReadOnly, addInfo: addInfo
* }],
* }];
* let diagram: Diagram = new Diagram({
* ...
* nodes : nodes,
* ...
* });
* diagram.appendTo('#diagram');
* ```
*
* @aspDefaultValueIgnore
* @default undefined
*/
@Property()
public addInfo: Object;
// tslint:disable-next-line:no-any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
constructor(parent: any, propName: string, defaultValue: Object, isArray?: boolean) {
super(parent, propName, defaultValue, isArray);
if (!(defaultValue as AnnotationModel).id) {
if (parent.parentObj && parent.parentObj.propName && parent.parentObj.propName === 'phases') {
this.id = parent.parentObj.id;
} else {
this.id = randomId();
}
}
}
}
/**
* Defines the textual description of nodes/connectors with respect to bounds
*/
export class ShapeAnnotation extends Annotation {
/**
* Sets the position of the annotation with respect to its parent bounds
*
* @default { x: 0.5, y: 0.5 }
* @blazorType NodeAnnotationOffset
*/
@Complex<PointModel>({ x: 0.5, y: 0.5 }, Point)
public offset: PointModel;
/* eslint-disable */
constructor(parent: any, propName: string, defaultValue: Object, isArray?: boolean) {
super(parent, propName, defaultValue, isArray);
}
// eslint-disable-next-line valid-jsdoc
/**
* @private
* Returns the module of class ShapeAnnotation
*/
public getClassName(): string {
return 'ShapeAnnotation';
}
/* eslint-enable */
}
/**
* Defines the connector annotation
*/
export class PathAnnotation extends Annotation {
/**
* Sets the segment offset of annotation
*
* @default 0.5
*/
@Property(0.5)
public offset: number;
/**
* Sets the displacement of an annotation from its actual position
*
* @aspDefaultValueIgnore
* @blazorDefaultValueIgnore
* @default undefined
*/
@Complex<PointModel>({ x: 0, y: 0 }, Point)
public displacement: PointModel;
/**
* Sets the segment alignment of annotation
* * Center - Aligns the annotation at the center of a connector segment
* * Before - Aligns the annotation before a connector segment
* * After - Aligns the annotation after a connector segment
*
* @default Center
*/
@Property('Center')
public alignment: AnnotationAlignment;
/**
* Enable/Disable the angle based on the connector segment
*
* @default false
*/
@Property(false)
public segmentAngle: boolean;
/* eslint-disable */
constructor(parent: any, propName: string, defaultValue: Object, isArray?: boolean) {
super(parent, propName, defaultValue, isArray);
}
/* eslint-enable */
/**
* Returns the module of class PathAnnotation.
*
* @returns {string} Returns the module of class PathAnnotation.
* @private
*/
public getClassName(): string {
return 'PathAnnotation';
}
} | the_stack |
import {
Connection,
Keypair,
PublicKey,
sendAndConfirmTransaction,
SystemProgram,
SYSVAR_CLOCK_PUBKEY,
SYSVAR_RENT_PUBKEY,
Transaction,
} from "@solana/web3.js"
import BN from "bn.js"
import * as dircompare from "dir-compare"
import * as fs from "fs"
import { State, State2 } from "./example-program-gen/act/accounts"
import { fromTxError } from "./example-program-gen/act/errors"
import { SomeError } from "./example-program-gen/act/errors/custom"
import { InvalidProgramId } from "./example-program-gen/act/errors/anchor"
import {
causeError,
initialize,
initializeWithValues,
initializeWithValues2,
} from "./example-program-gen/act/instructions"
import { BarStruct, FooStruct } from "./example-program-gen/act/types"
import {
Named,
NoFields,
Struct,
Unnamed,
} from "./example-program-gen/act/types/FooEnum"
import * as path from "path"
const c = new Connection("http://127.0.0.1:8899", "processed")
const faucet = JSON.parse(
fs.readFileSync("tests/.test-ledger/faucet-keypair.json").toString()
)
const payer = Keypair.fromSecretKey(Uint8Array.from(faucet))
test("generator output", async () => {
const res = await dircompare.compare(
"tests/example-program-gen/exp",
"tests/example-program-gen/act",
{
compareContent: true,
compareFileAsync:
dircompare.fileCompareHandlers.lineBasedFileCompare.compareAsync,
}
)
res.diffSet?.forEach((diff) => {
if (diff.state !== "equal") {
const p1 =
(diff.name1 && path.join("exp", diff.relativePath, diff.name1)) ||
undefined
const p2 =
(diff.name2 && path.join("act", diff.relativePath, diff.name2)) ||
undefined
throw new Error(`${p1} is different from ${p2}: ${diff.reason}`)
}
})
})
test("init and account fetch", async () => {
const state = new Keypair()
const tx = new Transaction({ feePayer: payer.publicKey })
tx.add(
initialize({
state: state.publicKey,
payer: payer.publicKey,
nested: {
clock: SYSVAR_CLOCK_PUBKEY,
rent: SYSVAR_RENT_PUBKEY,
},
systemProgram: SystemProgram.programId,
})
)
await sendAndConfirmTransaction(c, tx, [state, payer])
const res = await State.fetch(c, state.publicKey)
if (res === null) {
fail("account not found")
}
expect(res.boolField).toBe(true)
expect(res.u8Field).toBe(234)
expect(res.i8Field).toBe(-123)
expect(res.u16Field).toBe(62345)
expect(res.i16Field).toBe(-31234)
expect(res.u32Field).toBe(1234567891)
expect(res.i32Field).toBe(-1234567891)
expect(res.f32Field).toBe(123456.5)
expect(res.u64Field.eq(new BN("9223372036854775817"))).toBe(true)
expect(res.i64Field.eq(new BN("-4611686018427387914"))).toBe(true)
expect(res.f64Field).toBe(1234567891.345)
expect(
res.u128Field.eq(new BN("170141183460469231731687303715884105737"))
).toBe(true)
expect(
res.i128Field.eq(new BN("-85070591730234615865843651857942052874"))
).toBe(true)
expect(res.bytesField).toStrictEqual([1, 2, 255, 254])
expect(res.stringField).toBe("hello")
expect(
res.pubkeyField.equals(
new PublicKey("EPZP2wrcRtMxrAPJCXVEQaYD9eH7fH7h12YqKDcd4aS7")
)
).toBe(true)
// vecField
expect(res.vecField.length).toBe(5)
expect(res.vecField[0].eq(new BN("1")))
expect(res.vecField[1].eq(new BN("2")))
expect(res.vecField[2].eq(new BN("100")))
expect(res.vecField[3].eq(new BN("1000")))
expect(res.vecField[4].eq(new BN("18446744073709551615")))
// vecStructField
expect(res.vecStructField.length).toBe(1)
{
const act = res.vecStructField[0]
expect(act.field1).toBe(123)
expect(act.field2).toBe(999)
expect(act.nested.someField).toBe(true)
expect(act.nested.otherField).toBe(10)
expect(act.vecNested.length).toBe(1)
expect(act.vecNested[0].someField).toBe(true)
expect(act.vecNested[0].otherField).toBe(10)
expect(act.optionNested).not.toBeNull()
expect(act.optionNested?.someField).toBe(true)
expect(act.optionNested?.otherField).toBe(10)
if (act.enumField.discriminator !== 2) {
fail()
}
expect(act.enumField.kind).toBe("Named")
expect(act.enumField.value.boolField).toBe(true)
expect(act.enumField.value.u8Field).toBe(15)
expect(act.enumField.value.nested.someField).toBe(true)
expect(act.enumField.value.nested.otherField).toBe(10)
}
expect(res.optionField).toBe(null)
// structField
{
const act = res.structField
expect(act.field1).toBe(123)
expect(act.field2).toBe(999)
expect(act.nested.someField).toBe(true)
expect(act.nested.otherField).toBe(10)
expect(act.vecNested.length).toBe(1)
expect(act.vecNested[0].someField).toBe(true)
expect(act.vecNested[0].otherField).toBe(10)
expect(act.optionNested).not.toBeNull()
expect(act.optionNested?.someField).toBe(true)
expect(act.optionNested?.otherField).toBe(10)
if (act.enumField.discriminator !== 2) {
fail()
}
expect(act.enumField.kind).toBe("Named")
expect(act.enumField.value.boolField).toBe(true)
expect(act.enumField.value.u8Field).toBe(15)
expect(act.enumField.value.nested.someField).toBe(true)
expect(act.enumField.value.nested.otherField).toBe(10)
}
expect(res.arrayField).toStrictEqual([true, false, true])
// enumField1
{
const act = res.enumField1
if (act.discriminator !== 0) {
fail()
}
expect(act.kind).toBe("Unnamed")
expect(act.value.length).toBe(3)
expect(act.value[0]).toBe(false)
expect(act.value[1]).toBe(10)
expect(act.value[2].someField).toBe(true)
expect(act.value[2].otherField).toBe(10)
}
// enumField2
{
const act = res.enumField2
if (act.discriminator !== 2) {
fail()
}
expect(act.kind).toBe("Named")
expect(act.value.boolField).toBe(true)
expect(act.value.u8Field).toBe(20)
expect(act.value.nested.someField).toBe(true)
expect(act.value.nested.otherField).toBe(10)
}
// enumField3
{
const act = res.enumField3
if (act.discriminator !== 3) {
fail()
}
expect(act.kind).toBe("Struct")
expect(act.value.length).toBe(1)
expect(act.value[0].someField).toBe(true)
expect(act.value[0].otherField).toBe(10)
}
// enumField4
{
const act = res.enumField4
if (act.discriminator !== 6) {
fail()
}
expect(act.kind).toBe("NoFields")
}
})
test("fetch multiple", async () => {
const state = new Keypair()
const another_state = new Keypair()
const non_state = new Keypair()
const tx = new Transaction({ feePayer: payer.publicKey })
tx.add(
initialize({
state: state.publicKey,
payer: payer.publicKey,
nested: {
clock: SYSVAR_CLOCK_PUBKEY,
rent: SYSVAR_RENT_PUBKEY,
},
systemProgram: SystemProgram.programId,
})
)
tx.add(
initialize({
state: another_state.publicKey,
payer: payer.publicKey,
nested: {
clock: SYSVAR_CLOCK_PUBKEY,
rent: SYSVAR_RENT_PUBKEY,
},
systemProgram: SystemProgram.programId,
})
)
await sendAndConfirmTransaction(c, tx, [state, another_state, payer])
const res = await State.fetchMultiple(c, [
state.publicKey,
non_state.publicKey,
another_state.publicKey,
])
expect(res).toEqual([expect.any(State), null, expect.any(State)])
})
test("instruction with args", async () => {
const state = new Keypair()
const state2 = new Keypair()
const tx = new Transaction({ feePayer: payer.publicKey })
tx.add(
initializeWithValues(
{
boolField: true,
u8Field: 253,
i8Field: -120,
u16Field: 61234,
i16Field: -31253,
u32Field: 1234567899,
i32Field: -123456789,
f32Field: 123458.5,
u64Field: new BN("9223372036854775810"),
i64Field: new BN("-4611686018427387912"),
f64Field: 1234567892.445,
u128Field: new BN("170141183460469231731687303715884105740"),
i128Field: new BN("-85070591730234615865843651857942052877"),
bytesField: [5, 10, 255],
stringField: "string value",
pubkeyField: new PublicKey(
"GDddEKTjLBqhskzSMYph5o54VYLQfPCR3PoFqKHLJK6s"
),
vecField: [new BN(1), new BN("123456789123456789")],
vecStructField: [
new FooStruct({
field1: 1,
field2: 2,
nested: new BarStruct({
someField: true,
otherField: 55,
}),
vecNested: [
new BarStruct({
someField: false,
otherField: 11,
}),
],
optionNested: null,
enumField: new Unnamed([
true,
22,
new BarStruct({
someField: true,
otherField: 33,
}),
]),
}),
],
optionField: true,
optionStructField: null,
structField: new FooStruct({
field1: 1,
field2: 2,
nested: new BarStruct({
someField: true,
otherField: 55,
}),
vecNested: [
new BarStruct({
someField: false,
otherField: 11,
}),
],
optionNested: null,
enumField: new NoFields(),
}),
arrayField: [true, true, false],
enumField1: new Unnamed([
true,
15,
new BarStruct({
someField: false,
otherField: 200,
}),
]),
enumField2: new Named({
boolField: true,
u8Field: 128,
nested: new BarStruct({
someField: false,
otherField: 1,
}),
}),
enumField3: new Struct([
new BarStruct({
someField: true,
otherField: 15,
}),
]),
enumField4: new NoFields(),
},
{
state: state.publicKey,
payer: payer.publicKey,
nested: {
clock: SYSVAR_CLOCK_PUBKEY,
rent: SYSVAR_RENT_PUBKEY,
},
systemProgram: SystemProgram.programId,
}
)
)
tx.add(
initializeWithValues2(
{
vecOfOption: [null, new BN(20)],
},
{
state: state2.publicKey,
payer: payer.publicKey,
systemProgram: SystemProgram.programId,
}
)
)
await sendAndConfirmTransaction(c, tx, [state, state2, payer])
const res = await State.fetch(c, state.publicKey)
if (res === null) {
fail("account for State not found")
}
const res2 = await State2.fetch(c, state2.publicKey)
if (res2 === null) {
fail("account for State2 not found")
}
expect(res.boolField).toBe(true)
expect(res.u8Field).toBe(253)
expect(res.i8Field).toBe(-120)
expect(res.u16Field).toBe(61234)
expect(res.i16Field).toBe(-31253)
expect(res.u32Field).toBe(1234567899)
expect(res.i32Field).toBe(-123456789)
expect(res.f32Field).toBe(123458.5)
expect(res.u64Field.eq(new BN("9223372036854775810"))).toBe(true)
expect(res.i64Field.eq(new BN("-4611686018427387912"))).toBe(true)
expect(res.f64Field).toBe(1234567892.445)
expect(
res.u128Field.eq(new BN("170141183460469231731687303715884105740"))
).toBe(true)
expect(
res.i128Field.eq(new BN("-85070591730234615865843651857942052877"))
).toBe(true)
expect(res.bytesField).toStrictEqual([5, 10, 255])
expect(res.stringField).toBe("string value")
expect(
res.pubkeyField.equals(
new PublicKey("GDddEKTjLBqhskzSMYph5o54VYLQfPCR3PoFqKHLJK6s")
)
).toBe(true)
// vecField
expect(res.vecField.length).toBe(2)
expect(res.vecField[0].eq(new BN("1")))
expect(res.vecField[1].eq(new BN("123456789123456789")))
// vecStructField
expect(res.vecStructField.length).toBe(1)
{
const act = res.vecStructField[0]
expect(act.field1).toBe(1)
expect(act.field2).toBe(2)
expect(act.nested.someField).toBe(true)
expect(act.nested.otherField).toBe(55)
expect(act.vecNested.length).toBe(1)
expect(act.vecNested[0].someField).toBe(false)
expect(act.vecNested[0].otherField).toBe(11)
expect(act.optionNested).toBeNull()
if (act.enumField.discriminator !== 0) {
fail()
}
expect(act.enumField.kind).toBe("Unnamed")
expect(act.enumField.value.length).toBe(3)
expect(act.enumField.value[0]).toBe(true)
expect(act.enumField.value[1]).toBe(22)
expect(act.enumField.value[2].someField).toBe(true)
expect(act.enumField.value[2].otherField).toBe(33)
}
// optionField
expect(res.optionField).toBe(true)
// optionStructField
expect(res.optionStructField).toBeNull()
// structField
{
const act = res.structField
expect(act.field1).toBe(1)
expect(act.field2).toBe(2)
expect(act.nested.someField).toBe(true)
expect(act.nested.otherField).toBe(55)
expect(act.vecNested.length).toBe(1)
expect(act.vecNested[0].someField).toBe(false)
expect(act.vecNested[0].otherField).toBe(11)
expect(act.optionNested).toBeNull()
if (act.enumField.discriminator !== 6) {
fail()
}
expect(act.enumField.kind).toBe("NoFields")
}
// arrayField
expect(res.arrayField).toStrictEqual([true, true, false])
// enumField1
{
const act = res.enumField1
if (act.discriminator !== 0) {
fail()
}
expect(act.kind).toBe("Unnamed")
expect(act.value.length).toBe(3)
expect(act.value[0]).toBe(true)
expect(act.value[1]).toBe(15)
expect(act.value[2].someField).toBe(false)
expect(act.value[2].otherField).toBe(200)
}
// enumField2
{
const act = res.enumField2
if (act.discriminator !== 2) {
fail()
}
expect(act.kind).toBe("Named")
expect(act.value.boolField).toBe(true)
expect(act.value.u8Field).toBe(128)
expect(act.value.nested.someField).toBe(false)
expect(act.value.nested.otherField).toBe(1)
}
// enumField3
{
const act = res.enumField3
if (act.discriminator !== 3) {
fail()
}
expect(act.kind).toBe("Struct")
expect(act.value.length).toBe(1)
expect(act.value[0].someField).toBe(true)
expect(act.value[0].otherField).toBe(15)
}
// enumField4
{
const act = res.enumField4
if (act.discriminator !== 6) {
fail()
}
expect(act.kind).toBe("NoFields")
}
// vecOfOption
expect(res2.vecOfOption[0]).toBe(null)
expect(res2.vecOfOption[1] !== null && res2.vecOfOption[1].eqn(20)).toBe(true)
})
test("tx error", async () => {
const tx = new Transaction({ feePayer: payer.publicKey })
tx.add(causeError())
await expect(async () => {
try {
await sendAndConfirmTransaction(c, tx, [payer])
} catch (e) {
throw fromTxError(e)
}
}).rejects.toThrow(SomeError)
})
describe("fromTxError", () => {
it("returns null when CPI call fails", async () => {
const errMock = {
logs: [
"Program 3rTQ3R4B2PxZrAyx7EUefySPgZY8RhJf16cZajbmrzp8 invoke [1]",
"Program log: Instruction: CauseError",
"Program 11111111111111111111111111111111 invoke [2]",
"Allocate: requested 1000000000000000000, max allowed 10485760",
"Program 11111111111111111111111111111111 failed: custom program error: 0x3",
"Program 3rTQ3R4B2PxZrAyx7EUefySPgZY8RhJf16cZajbmrzp8 consumed 7958 of 1400000 compute units",
"Program 3rTQ3R4B2PxZrAyx7EUefySPgZY8RhJf16cZajbmrzp8 failed: custom program error: 0x3",
],
}
expect(fromTxError(errMock)).toBe(null)
})
it("parses anchor error correctly", () => {
const errMock = {
logs: [
"Program 3rTQ3R4B2PxZrAyx7EUefySPgZY8RhJf16cZajbmrzp8 invoke [1]",
"Program log: Instruction: CauseError",
"Program log: AnchorError caused by account: system_program. Error Code: InvalidProgramId. Error Number: 3008. Error Message: Program ID was not as expected.",
"Program log: Left:",
"Program log: 24S58Cp5Myf6iGx4umBNd7RgDrZ9nkKzvkfFHBMDomNa",
"Program log: Right:",
"Program log: 11111111111111111111111111111111",
"Program 3rTQ3R4B2PxZrAyx7EUefySPgZY8RhJf16cZajbmrzp8 consumed 5043 of 1400000 compute units",
"Program 3rTQ3R4B2PxZrAyx7EUefySPgZY8RhJf16cZajbmrzp8 failed: custom program error: 0xbc0",
],
}
expect(fromTxError(errMock)).toBeInstanceOf(InvalidProgramId)
})
})
test("toJSON", async () => {
const state = new State({
boolField: true,
u8Field: 255,
i8Field: -120,
u16Field: 62000,
i16Field: -31000,
u32Field: 123456789,
i32Field: -123456789,
f32Field: 123456.5,
u64Field: new BN("9223372036854775805"),
i64Field: new BN("4611686018427387910"),
f64Field: 1234567891.35,
u128Field: new BN("170141183460469231731687303715884105760"),
i128Field: new BN("-85070591730234615865843651857942052897"),
bytesField: [1, 255],
stringField: "a string",
pubkeyField: new PublicKey("EPZP2wrcRtMxrAPJCXVEQaYD9eH7fH7h12YqKDcd4aS7"),
vecField: [new BN("10"), new BN("1234567890123456")],
vecStructField: [
new FooStruct({
field1: 5,
field2: 6,
nested: new BarStruct({
someField: true,
otherField: 15,
}),
vecNested: [
new BarStruct({
someField: true,
otherField: 13,
}),
],
optionNested: null,
enumField: new Unnamed([
false,
111,
new BarStruct({
someField: false,
otherField: 11,
}),
]),
}),
],
optionField: null,
optionStructField: new FooStruct({
field1: 8,
field2: 9,
nested: new BarStruct({
someField: true,
otherField: 17,
}),
vecNested: [
new BarStruct({
someField: true,
otherField: 10,
}),
],
optionNested: new BarStruct({
someField: false,
otherField: 99,
}),
enumField: new NoFields(),
}),
structField: new FooStruct({
field1: 11,
field2: 12,
nested: new BarStruct({
someField: false,
otherField: 177,
}),
vecNested: [
new BarStruct({
someField: true,
otherField: 15,
}),
],
optionNested: new BarStruct({
someField: true,
otherField: 75,
}),
enumField: new NoFields(),
}),
arrayField: [true, false],
enumField1: new Unnamed([
false,
157,
new BarStruct({
someField: true,
otherField: 193,
}),
]),
enumField2: new Named({
boolField: false,
u8Field: 77,
nested: new BarStruct({
someField: true,
otherField: 100,
}),
}),
enumField3: new Struct([
new BarStruct({
someField: false,
otherField: 122,
}),
]),
enumField4: new NoFields(),
})
const stateJSON = state.toJSON()
expect(stateJSON).toStrictEqual({
boolField: true,
u8Field: 255,
i8Field: -120,
u16Field: 62000,
i16Field: -31000,
u32Field: 123456789,
i32Field: -123456789,
f32Field: 123456.5,
u64Field: "9223372036854775805",
i64Field: "4611686018427387910",
f64Field: 1234567891.35,
u128Field: "170141183460469231731687303715884105760",
i128Field: "-85070591730234615865843651857942052897",
bytesField: [1, 255],
stringField: "a string",
pubkeyField: "EPZP2wrcRtMxrAPJCXVEQaYD9eH7fH7h12YqKDcd4aS7",
vecField: ["10", "1234567890123456"],
vecStructField: [
{
field1: 5,
field2: 6,
nested: {
someField: true,
otherField: 15,
},
vecNested: [
{
someField: true,
otherField: 13,
},
],
optionNested: null,
enumField: {
kind: "Unnamed",
value: [
false,
111,
{
someField: false,
otherField: 11,
},
],
},
},
],
optionField: null,
optionStructField: {
field1: 8,
field2: 9,
nested: {
someField: true,
otherField: 17,
},
vecNested: [
{
someField: true,
otherField: 10,
},
],
optionNested: {
someField: false,
otherField: 99,
},
enumField: {
kind: "NoFields",
},
},
structField: {
field1: 11,
field2: 12,
nested: {
someField: false,
otherField: 177,
},
vecNested: [
{
someField: true,
otherField: 15,
},
],
optionNested: {
someField: true,
otherField: 75,
},
enumField: {
kind: "NoFields",
},
},
arrayField: [true, false],
enumField1: {
kind: "Unnamed",
value: [
false,
157,
{
someField: true,
otherField: 193,
},
],
},
enumField2: {
kind: "Named",
value: {
boolField: false,
u8Field: 77,
nested: {
someField: true,
otherField: 100,
},
},
},
enumField3: {
kind: "Struct",
value: [
{
someField: false,
otherField: 122,
},
],
},
enumField4: {
kind: "NoFields",
},
})
/**
* fromJSON
*/
const stateFromJSON = State.fromJSON(stateJSON)
expect(stateFromJSON.boolField).toBe(state.boolField)
expect(stateFromJSON.u8Field).toBe(state.u8Field)
expect(stateFromJSON.i8Field).toBe(state.i8Field)
expect(stateFromJSON.u16Field).toBe(state.u16Field)
expect(stateFromJSON.i16Field).toBe(state.i16Field)
expect(stateFromJSON.u32Field).toBe(state.u32Field)
expect(stateFromJSON.i32Field).toBe(state.i32Field)
expect(stateFromJSON.f32Field).toBe(state.f32Field)
expect(stateFromJSON.u64Field.toString()).toBe(state.u64Field.toString())
expect(stateFromJSON.i64Field.toString()).toBe(state.i64Field.toString())
expect(stateFromJSON.f64Field).toBe(state.f64Field)
expect(stateFromJSON.u128Field.toString()).toBe(state.u128Field.toString())
expect(stateFromJSON.i128Field.toString()).toBe(state.i128Field.toString())
expect(stateFromJSON.bytesField).toStrictEqual(state.bytesField)
expect(stateFromJSON.stringField).toBe(state.stringField)
expect(stateFromJSON.pubkeyField.toString()).toBe(
state.pubkeyField.toString()
)
// vecField
expect(stateFromJSON.vecField.length).toBe(2)
expect(stateFromJSON.vecField[0].toString()).toBe(
state.vecField[0].toString()
)
expect(stateFromJSON.vecField[1].toString()).toBe(
state.vecField[1].toString()
)
// vecStructField
expect(stateFromJSON.vecStructField.length).toBe(1)
{
const act = stateFromJSON.vecStructField[0]
const exp = state.vecStructField[0]
expect(act.field1).toBe(exp.field1)
expect(act.field2).toBe(exp.field2)
expect(act.nested.someField).toBe(exp.nested.someField)
expect(act.nested.otherField).toBe(exp.nested.otherField)
expect(act.vecNested.length).toBe(exp.vecNested.length)
expect(act.vecNested[0].someField).toBe(exp.vecNested[0].someField)
expect(act.vecNested[0].otherField).toBe(exp.vecNested[0].otherField)
expect(act.optionNested).toBe(null)
if (
act.enumField.discriminator !== 0 ||
exp.enumField.discriminator !== 0
) {
fail()
}
expect(act.enumField.kind).toBe("Unnamed")
expect(act.enumField.value.length).toBe(exp.enumField.value.length)
expect(act.enumField.value[0]).toBe(exp.enumField.value[0])
expect(act.enumField.value[1]).toBe(exp.enumField.value[1])
expect(act.enumField.value[2].someField).toBe(
exp.enumField.value[2].someField
)
expect(act.enumField.value[2].otherField).toBe(
exp.enumField.value[2].otherField
)
}
// optionField
expect(stateFromJSON.optionField).toBe(state.optionField)
// optionStructField
{
const act = stateFromJSON.optionStructField
const exp = state.optionStructField
if (exp === null || act === null) {
fail()
}
expect(act.field1).toBe(exp.field1)
expect(act.field2).toBe(exp.field2)
expect(act.nested.someField).toBe(exp.nested.someField)
expect(act.nested.otherField).toBe(exp.nested.otherField)
expect(act.vecNested.length).toBe(exp.vecNested.length)
expect(act.vecNested[0].someField).toBe(exp.vecNested[0].someField)
expect(act.vecNested[0].otherField).toBe(exp.vecNested[0].otherField)
expect(act.optionNested?.someField).toBe(exp.optionNested?.someField)
expect(act.optionNested?.otherField).toBe(exp.optionNested?.otherField)
if (
act.enumField.discriminator !== 6 ||
exp.enumField.discriminator !== 6
) {
fail()
}
}
// structField
{
const act = stateFromJSON.structField
const exp = state.structField
if (exp === null || act === null) {
fail()
}
expect(act.field1).toBe(exp.field1)
expect(act.field2).toBe(exp.field2)
expect(act.optionNested?.someField).toBe(exp.optionNested?.someField)
expect(act.optionNested?.otherField).toBe(exp.optionNested?.otherField)
expect(act.vecNested.length).toBe(exp.vecNested.length)
expect(act.vecNested[0].someField).toBe(exp.vecNested[0].someField)
expect(act.vecNested[0].otherField).toBe(exp.vecNested[0].otherField)
if (
act.enumField.discriminator !== 6 ||
exp.enumField.discriminator !== 6
) {
fail()
}
}
// arrayField
expect(stateFromJSON.arrayField).toStrictEqual(state.arrayField)
// enumField1
{
const act = stateFromJSON.enumField1
const exp = state.enumField1
if (act.discriminator !== 0 || exp.discriminator !== 0) {
fail()
}
expect(act.kind).toBe("Unnamed")
expect(act.value.length).toEqual(exp.value.length)
expect(act.value[0]).toEqual(exp.value[0])
expect(act.value[1]).toEqual(exp.value[1])
expect(act.value[2].someField).toEqual(exp.value[2].someField)
expect(act.value[2].otherField).toEqual(exp.value[2].otherField)
}
// enumField2
{
const act = stateFromJSON.enumField2
const exp = state.enumField2
if (act.discriminator !== 2 || exp.discriminator !== 2) {
fail()
}
expect(act.kind).toBe("Named")
expect(act.value.boolField).toEqual(exp.value.boolField)
expect(act.value.u8Field).toEqual(exp.value.u8Field)
expect(act.value.nested.someField).toEqual(exp.value.nested.someField)
expect(act.value.nested.otherField).toEqual(exp.value.nested.otherField)
}
// enumField3
{
const act = stateFromJSON.enumField3
const exp = state.enumField3
if (act.discriminator !== 3 || exp.discriminator !== 3) {
fail()
}
expect(act.kind).toBe("Struct")
expect(act.value.length).toEqual(exp.value.length)
expect(act.value[0].someField).toEqual(exp.value[0].someField)
expect(act.value[0].otherField).toEqual(exp.value[0].otherField)
}
// enumField4
{
const act = stateFromJSON.enumField4
if (act.discriminator !== 6) {
fail()
}
expect(act.kind).toBe("NoFields")
}
}) | the_stack |
module tileworld {
// a rule view encapsulates a rule and allows editing of the rule
// as well as creating views of the underlying rule, where the
// views are mirrors or rotates of the underlying rule
export class RuleView {
private view: RuleTransforms = RuleTransforms.None;
constructor(private p: Project, private rid: number, private r: Rule) {
}
public getBaseRule(): Rule {
return this.r;
}
public getDerivedRules(): RuleView[] {
const ret: RuleView[] = [];
switch(this.r.transforms){
case RuleTransforms.HorzMirror:
case RuleTransforms.VertMirror:
case RuleTransforms.LeftRotate:
case RuleTransforms.RightRotate:
{
const rv = new RuleView(this.p, -1, this.r);
rv.view = this.r.transforms;
ret.push(rv);
break;
}
case RuleTransforms.Rotate3Way: {
for (let t = RuleTransforms.LeftRotate; t != RuleTransforms.Rotate3Way; t++) {
const rv = new RuleView(this.p, -1, this.r);
rv.view = t;
ret.push(rv)
}
break;
}
}
return ret;
}
public getViewTransform(): number {
if (this.rid == -1)
return this.view;
return -1;
}
public getTransforms(): number {
return this.r.transforms;
}
public setTransforms(n:number): void {
this.r.transforms = n;
}
public getRuleId(): number {
return this.rid;
}
public getRuleType(): RuleType {
return this.r.ruleType;
}
public setRuleType(rt: RuleType): void {
this.r.ruleType = rt;
}
public getRuleArg(): RuleArg {
return this.rid != -1 ? this.r.ruleArg :
this.r.ruleType == RuleType.ButtonPress ? flipRotateDir(this.r.ruleArg, this.view) : this.r.ruleArg;
}
public setRuleArg(ra: RuleArg): void {
this.r.ruleArg = ra;
}
public getDirFromRule(): number {
const rt = this.getRuleType();
if (rt == RuleType.Collision || rt == RuleType.ContextChange) {
const wd = this.getWhenDo(2, 2);
return wd == -1 ? AnyDir : this.getWitnessDirection(wd);
} else if (rt == RuleType.ButtonPress) {
return this.getRuleArg();
}
return AnyDir;
}
private rawView(): number {
return this.view == RuleTransforms.LeftRotate ? RuleTransforms.RightRotate :
(this.view == RuleTransforms.RightRotate ? RuleTransforms.LeftRotate: this.view);
}
public getWhenDo(col: number, row: number): number {
if (this.rid == -1) {
const ncol = transformCol(col, row, this.rawView());
const nrow = transformRow(row, col, this.rawView());
col = ncol;
row = nrow;
}
const whendo = this.r.whenDo.find(wd => wd.col == col && wd.row == row);
if (whendo == null)
return -1;
else
return this.r.whenDo.indexOf(whendo);
}
public makeWhenDo(col: number, row: number): number {
const wd = new WhenDo(col, row);
wd.bgPred = control.createBuffer(this.p.backCnt());
wd.spPred = control.createBuffer(this.p.spriteCnt());
wd.commandsLen = 0;
wd.commands = control.createBuffer(MaxCommands << 1);
this.r.whenDo.push(wd);
return this.r.whenDo.length - 1;
}
public getWhenDoCol(whendo: number): number {
return this.r.whenDo[whendo].col;
}
public getWhenDoRow(whendo: number): number {
return this.r.whenDo[whendo].row;
}
private getSetBuffAttr(buf: Buffer, index: number, val: number): number {
const byteIndex = index >> 2;
const byte = buf.getUint8(byteIndex);
const remainder = index - (byteIndex << 2);
if (val != 0xffff) {
const mask = (0x3 << (remainder << 1)) ^ 0xff;
const newByte = (byte & mask) | ((val & 0x3) << (remainder << 1));
buf.setUint8(byteIndex, newByte)
}
return (byte >> (remainder << 1)) & 0x3;
}
public getSetBgAttr(wdid: number, index: number, val = 0xffff): AttrType {
return this.getSetBuffAttr(this.r.whenDo[wdid].bgPred, index, val);
}
public getSetSpAttr(wdid: number, index: number, val = 0xffff): AttrType {
return this.getSetBuffAttr(this.r.whenDo[wdid].spPred, index, val);
}
public attrCnt(whendo: number): number {
let cnt = 0;
for (let i = 0; i < this.p.backCnt(); i++) {
if (this.getSetBgAttr(whendo, i) != AttrType.OK)
cnt++;
}
for (let i = 0; i < this.p.spriteCnt(); i++) {
if (this.getSetSpAttr(whendo, i) != AttrType.OK)
cnt++;
}
return cnt;
}
private attrBgIndex(whendo: number, a: AttrType): number {
for (let i = 0; i < this.p.backCnt(); i++) {
if (this.getSetBgAttr(whendo, i) == a)
return i;
}
return -1;
}
private attrSpIndex(whendo: number, a: AttrType): number {
for (let i = 0; i < this.p.spriteCnt(); i++) {
if (this.getSetSpAttr(whendo, i) == a)
return i;
}
return -1;
}
public findWitnessColRow(col: number, row: number, editor = true): number {
if (editor && this.getRuleType() == RuleType.NegationCheck)
return -1;
const whendo = this.getWhenDo(col, row);
if (whendo == -1)
return -1;
if (this.attrBgIndex(whendo, AttrType.Include) != -1)
return -1;
return this.attrSpIndex(whendo, AttrType.Include);
}
public getWitnessDirection(wdid: number): number {
const dir = this.r.whenDo[wdid].dir;
return (this.rid != -1 || dir >= Resting) ? dir : flipRotateDir(dir, this.view);
}
public setWitnessDirection(wdid: number, val:number): void {
this.r.whenDo[wdid].dir = val;
}
public getCmdsLen(wdid: number): number {
return this.r.whenDo[wdid].commandsLen;
}
public getCmdInst(wdid: number, cid: number): number {
const wd = this.r.whenDo[wdid];
if (cid >= wd.commandsLen) return 0xff;
return wd.commands.getUint8(cid << 1);
}
public getCmdArg(wdid: number, cid: number): number {
const wd = this.r.whenDo[wdid];
if (cid >= wd.commandsLen) return 0xff;
let arg = wd.commands.getUint8((cid << 1)+1);
if (this.rid == -1 && this.getCmdInst(wdid, cid) == CommandType.Move) {
arg = flipRotateDir(arg, this.view);
}
return arg;
}
public setCmdInst(wdid: number, cid: number, n: number): number {
const wd = this.r.whenDo[wdid];
if (cid > wd.commandsLen)
return 0xff;
if (cid == wd.commandsLen)
wd.commandsLen++;
wd.commands.setUint8(cid << 1, n & 0xff);
return n & 0xff;
}
public setCmdArg(wdid: number, cid: number, n: number): number {
const wd = this.r.whenDo[wdid];
if (cid > wd.commandsLen)
return 0xff;
if (cid == wd.commandsLen)
wd.commandsLen++;
wd.commands.setUint8((cid << 1)+1, n & 0xff);
return n & 0xff;
}
public removeCommand(wdid: number, cid: number): number {
const wd = this.r.whenDo[wdid];
if (wd.commandsLen == 0 || cid >= wd.commandsLen)
return wd.commandsLen;
for(let i=(cid << 1); i <= ((MaxCommands-1)<<1)-1; i++) {
wd.commands.setUint8(i, wd.commands.getUint8(i+2));
}
wd.commandsLen--;
return wd.commandsLen;
}
// predicates/misc info
public getSpriteKinds(): number[] {
const wd = this.getWhenDo(2, 2);
const ret: number[] = [];
for(let i=0; i < this.p.spriteCnt(); i++) {
const at = this.getSetSpAttr(wd, i);
// TODO: Include vs. Include2?
if (at == AttrType.Include || at == AttrType.Include2)
ret.push(i);
}
return ret;
}
public hasSpriteKind(kind: number): boolean {
const wd = this.getWhenDo(2, 2);
// TODO: Include vs. Include2?
return wd == -1 ? false : this.getSetSpAttr(wd, kind) == AttrType.Include
}
public whendoTrue(whendo: number): boolean {
const wd = this.r.whenDo[whendo];
return isWhenDoTrue(wd);
}
public isRuleTrue(): boolean {
return isRuleTrue(this.r);
}
// printing out a rule
private whenDoAttrs(wd: number, a: AttrType) {
const ret: string[] = [];
for(let i = 0; i < this.p.backCnt(); i++) {
if (this.getSetBgAttr(wd, i) == a)
ret.push("b"+i.toString())
}
for(let i = 0; i < this.p.spriteCnt(); i++) {
if (this.getSetSpAttr(wd, i) == a)
ret.push("s"+i.toString())
}
return ret;
}
private ruleArgToString() {
if (this.getRuleType() != RuleType.ButtonPress)
return "none"
return buttonArgToString[this.getRuleArg()];
}
private commandArgToString(inst: number, arg: number) {
if (inst == CommandType.Move)
return moveArgToString[arg];
if (inst == CommandType.Game)
return gameArgToString[arg];
if (inst == CommandType.Paint || inst == CommandType.Spawn || inst == CommandType.Portal)
return arg.toString();
return "none";
}
public printRule(): void {
// rule header
console.log("id:"+this.getRuleId().toString());
console.log("rule:"+ruleToString[this.getRuleType()]+":"+this.ruleArgToString());
// rule body
this.getBaseRule().whenDo.forEach((wd,wdi) => {
console.log("tile:"+wd.col.toString()+":"+wd.row.toString());
// output attributes
console.log("include:"+this.whenDoAttrs(wdi,AttrType.Include).join(":"));
console.log("include2:"+this.whenDoAttrs(wdi,AttrType.Include2).join(":"));
console.log("exclude:"+this.whenDoAttrs(wdi,AttrType.Exclude).join(":"));
// output commands
for(let i=0; i<wd.commandsLen; i++) {
const inst = this.getCmdInst(wdi, i);
const arg = this.getCmdArg(wdi, i)
console.log("cmd:"+cmdInstToString[inst]+":"+this.commandArgToString(inst, arg))
}
});
console.log("\n");
}
}
} | the_stack |
jest.mock("node-fetch");
import fetch from "node-fetch";
import qs from "querystring";
import { ResolvedSearchParameters, SearchParameters } from "../../search";
import { HTMLSearcher } from "../html-searcher";
type ResultInfo = {
isFeatured: boolean;
isThirdParty: boolean;
title: string;
path: string;
description: string;
imageAttributes: string;
datePosted: string;
id: string;
};
const defaultResultInfo: ResultInfo = {
isFeatured: false,
isThirdParty: false,
title: "",
path: "/someAd",
description: "",
imageAttributes: "",
datePosted: "",
id: ""
};
// Result pages in most categories use this markup
const createStandardResultHTML = (info: Partial<ResultInfo>): string => {
info = { ...defaultResultInfo, ...info };
return `
<div class="search-item
${info.isFeatured ? "top-feature" : "regular-ad"}
${info.isThirdParty ? "third-party" : ""}"
${info.id ? `data-listing-id="${info.id}"` : ""}>
<div class="clearfix">
<div class="left-col">
<div class="image">
<picture><img ${info.imageAttributes}></picture>
</div>
<div class="info">
<div class="info-container">
<div class="title">
<a class="title" href="${info.path}">${info.title}</a>
</div>
<div class="location">
<span class="">Some location</span>
<span class="date-posted">${info.datePosted}</span>
</div>
<div class="description">${info.description}</div>
</div>
</div>
</div>
</div>
</div>
`;
};
// For some reason, some categories (like anything under
// SERVICES) use different markup classes than usual
const createServiceResultHTML = (info: Partial<ResultInfo>): string => {
info = { ...defaultResultInfo, ...info };
return `
<table class="
${info.isFeatured ? "top-feature" : "regular-ad"}
${info.isThirdParty ? "third-party" : ""}"
${info.id ? `data-listing-id="${info.id}"` : ""}>
<tbody>
<tr>
<td class="description">
<a class="title" href="${info.path}">${info.title}</a>
<p>${info.description}</p>
</td>
<td class="image">
<div class="multiple-images">
<picture><img ${info.imageAttributes}></picture>
</div>
</td>
<td class="posted">
${info.datePosted}<br>
Some location
</td>
</tr>
</tbody>
</table>
`;
};
describe.each`
markup | createResultHTML
${"standard result page markup"} | ${createStandardResultHTML}
${"service result page markup"} | ${createServiceResultHTML}
`("Search result HTML scraper ($markup)", ({ createResultHTML }) => {
const fetchSpy = fetch as any as jest.Mock;
afterEach(() => {
jest.resetAllMocks();
});
const validateSearchUrl = (url: string, expectedParams: SearchParameters) => {
const splitUrl = url.split("?");
expect(splitUrl.length).toBe(2);
expect(splitUrl[0]).toBe("https://www.kijiji.ca/b-search.html")
expect(qs.parse(splitUrl[1])).toEqual(qs.parse(qs.stringify(expectedParams)));
};
const validateRequestHeaders = () => {
expect(fetchSpy).toBeCalled();
for (const call of fetchSpy.mock.calls) {
expect(call).toEqual([
expect.any(String),
{
headers: {
"Accept-Language": "en-CA",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0"
}
}
]);
};
}
const search = (params: ResolvedSearchParameters = { locationId: 0, categoryId: 0}) => {
return new HTMLSearcher().getPageResults(params, 1);
};
const defaultSearchParams: SearchParameters = {
locationId: 0,
categoryId: 0,
formSubmit: true,
siteLocale: "en_CA"
};
it.each`
test | firstRequestStatus
${"fail on initial request"} | ${200}
${"fail on redirected request"} | ${403}
`("should detect ban ($test)", async ({ firstRequestStatus }) => {
fetchSpy.mockResolvedValueOnce({ status: firstRequestStatus, url: "http://example.com/search/results" });
fetchSpy.mockResolvedValueOnce({ status: 403 });
try {
await search();
fail("Expected error for ban");
} catch (err) {
expect(err.message).toBe(
"Kijiji denied access. You are likely temporarily blocked. This " +
"can happen if you scrape too aggressively. Try scraping again later, " +
"and more slowly. If this happens even when scraping reasonably, please " +
"open an issue at: https://github.com/mwpenny/kijiji-scraper/issues"
)
validateRequestHeaders();
}
});
describe("search parameters", () => {
it("should pass all defined params in search URL", async () => {
const params = {
...defaultSearchParams,
locationId: 123,
categoryId: 456,
someOtherParam: "hello",
undef: undefined
};
fetchSpy.mockResolvedValueOnce({ status: 200, url: "http://example.com/search/results" });
fetchSpy.mockResolvedValueOnce({ text: () => "" });
await search(params);
validateRequestHeaders();
validateSearchUrl(fetchSpy.mock.calls[0][0], params);
});
});
describe("result page redirect", () => {
it.each`
test | response
${"non-200 response code"} | ${{ status: 418 }}
${"no redirect"} | ${{ status: 200 }}
`("should throw error for bad response ($test)", async ({ response }) => {
fetchSpy.mockResolvedValue(response);
try {
await search();
fail("Expected error for non-200 response code");
} catch (err) {
expect(err.message).toBe(
"Kijiji failed to redirect to results page. It is possible " +
"that Kijiji changed their markup. If you believe this to be " +
"the case, please open an issue at: " +
"https://github.com/mwpenny/kijiji-scraper/issues"
);
validateRequestHeaders();
}
});
it("should be used for pagination", async () => {
fetchSpy.mockResolvedValueOnce({ status: 200, url: "http://example.com/search/results" });
fetchSpy.mockResolvedValueOnce({ text: () => createResultHTML({}) });
fetchSpy.mockResolvedValueOnce({ text: () => createResultHTML({}) });
const searcher = new HTMLSearcher();
await searcher.getPageResults({ locationId: 0, categoryId: 0 }, 1);
await searcher.getPageResults({ locationId: 0, categoryId: 0 }, 2);
expect(fetchSpy).toBeCalledTimes(3);
validateRequestHeaders();
// Only the first request should include the paramaters since
// the searcher instance is re-used for subsequent requests
validateSearchUrl(fetchSpy.mock.calls[0][0], { locationId: 0, categoryId: 0});
expect(fetchSpy.mock.calls[1][0]).toBe("http://example.com/search/page-1/results");
expect(fetchSpy.mock.calls[2][0]).toBe("http://example.com/search/page-2/results");
});
});
describe("result page scraping", () => {
// Helpers for date tests
const nanDataValidator = (date: Date) => {
expect(Number.isNaN(date.getTime())).toBe(true);
};
const makeSpecificDateValidator = (month: number, day: number, year: number) => {
return (date: Date) => {
const d = new Date();
d.setMonth(month - 1);
d.setDate(day);
d.setFullYear(year);
d.setHours(0, 0, 0, 0);
expect(date).toEqual(d);
}
};
const makeMinutesAgoValidator = (minutes: number) => {
return (date: Date) => {
const minutesAgo = new Date();
minutesAgo.setMinutes(minutesAgo.getMinutes() - minutes, 0, 0);
expect(date).toEqual(minutesAgo);
}
};
const makeHoursAgoValidator = (hours: number) => {
return (date: Date) => {
const hoursAgo = new Date();
hoursAgo.setHours(hoursAgo.getHours() - hours, 0, 0, 0);
expect(date).toEqual(hoursAgo);
}
};
const makeDaysAgoValidator = (days: number) => {
return (date: Date) => {
const daysAgo = new Date();
daysAgo.setDate(daysAgo.getDate() - days);
daysAgo.setHours(0, 0, 0, 0);
expect(date).toEqual(daysAgo);
}
};
const nowIshValidator = (date: Date) => {
const nowIsh = new Date();
nowIsh.setSeconds(date.getSeconds());
nowIsh.setMilliseconds(date.getMilliseconds());
expect(date).toEqual(nowIsh);
};
beforeEach(() => {
fetchSpy.mockResolvedValueOnce({ status: 200, url: "http://example.com/search/results" });
});
it("should throw error if results page is invalid", async () => {
fetchSpy.mockResolvedValueOnce({ text: () => createResultHTML({ path: "" }) });
try {
await search();
fail("Expected error while scraping results page");
} catch (err) {
expect(err.message).toBe(
"Result ad has no URL. It is possible that Kijiji changed their " +
"markup. If you believe this to be the case, please open an issue " +
"at: https://github.com/mwpenny/kijiji-scraper/issues"
);
validateRequestHeaders();
}
});
it("should scrape ID", async () => {
fetchSpy.mockResolvedValueOnce({ text: () => createResultHTML({ id: "123" }) });
const { pageResults } = await search();
validateRequestHeaders();
expect(pageResults).toEqual([expect.objectContaining({
id: "123",
})]);
});
it("should scrape title", async () => {
fetchSpy.mockResolvedValueOnce({ text: () => createResultHTML({ title: "My title" }) });
const { pageResults } = await search();
validateRequestHeaders();
expect(pageResults).toEqual([expect.objectContaining({
title: "My title"
})]);
});
it.each`
test | imageAttributes | expectedValue
${"with data-src"} | ${'data-src="/image" src="blah"'} | ${"/image"}
${"with src"} | ${'data-src="" src="/image"'} | ${"/image"}
${"with no attributes"} | ${""} | ${""}
${"upsize"} | ${'src="/image/s-l123.jpg"'} | ${"/image/s-l2000.jpg"}
`("should scrape image ($test)", async ({ imageAttributes, expectedValue }) => {
fetchSpy.mockResolvedValueOnce({ text: () => createResultHTML({ imageAttributes }) });
const { pageResults } = await search();
validateRequestHeaders();
expect(pageResults).toEqual([expect.objectContaining({
image: expectedValue
})]);
expect(pageResults[0].isScraped()).toBe(false);
});
it.each`
test | datePosted | validator
${"no date"} | ${""} | ${nanDataValidator}
${"invalid"} | ${"invalid"} | ${nanDataValidator}
${"dd/mm/yyyy"} | ${"7/9/2020"} | ${makeSpecificDateValidator(9, 7, 2020)}
${"minutes ago"} | ${"< 5 minutes ago"} | ${makeMinutesAgoValidator(5)}
${"hours ago"} | ${"< 2 hours ago"} | ${makeHoursAgoValidator(2)}
${"invalid ago"} | ${"< 1 parsec ago"} | ${nowIshValidator}
${"yesterday"} | ${"yesterday"} | ${makeDaysAgoValidator(1)}
`("should scrape date ($test)", async ({ datePosted, validator }) => {
fetchSpy.mockResolvedValueOnce({ text: () => createResultHTML({ datePosted }) });
const { pageResults } = await search();
validateRequestHeaders();
expect(pageResults.length).toBe(1);
validator(pageResults[0].date);
expect(pageResults[0].isScraped()).toBe(false);
});
it("should scrape description", async () => {
fetchSpy.mockResolvedValueOnce({ text: () => createResultHTML({ description: "My desc" }) });
const { pageResults } = await search();
validateRequestHeaders();
expect(pageResults).toEqual([expect.objectContaining({
description: "My desc"
})]);
expect(pageResults[0].isScraped()).toBe(false);
});
it("should scrape url", async () => {
fetchSpy.mockResolvedValueOnce({ text: () => createResultHTML({ path: "/myad" }) });
const { pageResults } = await search();
validateRequestHeaders();
expect(pageResults).toEqual([expect.objectContaining({
url: "https://www.kijiji.ca/myad"
})]);
expect(pageResults[0].isScraped()).toBe(false);
});
it("should exclude featured ads", async () => {
fetchSpy.mockResolvedValueOnce({ text: () => createResultHTML({}) + createResultHTML({ isFeatured: true }) });
const { pageResults } = await search();
validateRequestHeaders();
expect(pageResults.length).toBe(1);
expect(pageResults[0].isScraped()).toBe(false);
});
it("should exclude third-party ads", async () => {
fetchSpy.mockResolvedValueOnce({ text: () => createResultHTML({}) + createResultHTML({ isThirdParty: true }) });
const { pageResults } = await search();
validateRequestHeaders();
expect(pageResults.length).toBe(1);
expect(pageResults[0].isScraped()).toBe(false);
});
it.each`
isLastPage
${true}
${false}
`("should detect last page (isLastPage=$isLastPage)", async ({ isLastPage }) => {
let mockResponse = createResultHTML({});
if (isLastPage) {
mockResponse += '"isLastPage":true';
}
fetchSpy.mockResolvedValueOnce({ text: () => mockResponse });
const result = await search();
validateRequestHeaders();
expect(result.pageResults.length).toBe(1);
expect(result.pageResults[0].isScraped()).toBe(false);
expect(result.isLastPage).toBe(isLastPage);
});
it("should handle empty response", async () => {
fetchSpy.mockResolvedValueOnce({ text: () => "" });
const { pageResults } = await search();
validateRequestHeaders();
expect(pageResults.length).toBe(0);
});
});
}); | the_stack |
import React from "react";
import styled from "styled-components";
import { last as getLast } from "lodash-es";
import Menu from "./Menu";
import Icon from "./Icon";
import { Button } from "../src/components/Button";
import { HostApi } from "../webview-api";
import {
FetchThirdPartyChannelsRequestType,
CreateThirdPartyPostRequest,
ThirdPartyChannel
} from "@codestream/protocols/agent";
import { CodeStreamState } from "../store";
import { useSelector, useDispatch } from "react-redux";
import {
isConnected,
getProviderConfig,
getConnectedSharingTargets
} from "../store/providers/reducer";
import { connectProvider } from "../store/providers/actions";
import { getIntegrationData } from "../store/activeIntegrations/reducer";
import { updateForProvider } from "../store/activeIntegrations/actions";
import { SlackV2IntegrationData } from "../store/activeIntegrations/types";
import { setContext } from "../store/context/actions";
import { safe } from "../utils";
import { useDidMount, useUpdates } from "../utilities/hooks";
import { setUserPreference } from "./actions";
import { Modal } from "./Modal";
import { InlineMenu } from "../src/components/controls/InlineMenu";
import { CSTeamSettings } from "@codestream/protocols/api";
const TextButton = styled.span`
color: ${props => props.theme.colors.textHighlight};
cursor: pointer;
.octicon-chevron-down,
.octicon-chevron-down-thin {
transform: scale(0.7);
margin-left: 2px;
margin-right: 5px;
}
&:focus {
margin: -3px;
border: 3px solid transparent;
}
`;
const ChannelTable = styled.table`
color: ${props => props.theme.colors.text};
margin: 0 auto;
border-collapse: collapse;
td {
text-align: left;
white-space: nowrap;
padding: 2px 10px;
.icon {
vertical-align: -2px;
}
}
tbody tr:hover td {
background: rgba(127, 127, 127, 0.1);
}
hr {
border: none;
border-bottom: 1px solid ${props => props.theme.colors.baseBorder};
}
`;
const Root = styled.div`
color: ${props => props.theme.colors.textSubtle};
.octicon {
fill: currentColor;
vertical-align: text-top;
}
`;
const formatChannelName = (channel: { type: string; name: string }) =>
channel.type === "direct" ? channel.name : `#${channel.name}`;
function useActiveIntegrationData<T>(providerId: string) {
const dispatch = useDispatch();
const data = useSelector((state: CodeStreamState) =>
getIntegrationData<T>(state.activeIntegrations, providerId)
);
return React.useMemo(() => {
return {
get() {
return data;
},
set(fn: (data: T) => T) {
dispatch(updateForProvider(providerId, fn(data)));
}
};
}, [data]);
}
function useDataForTeam(providerId: string, providerTeamId: string = "") {
const data = useActiveIntegrationData<SlackV2IntegrationData>(providerId);
const teamData = data.get()[providerTeamId] || { channels: [] };
return React.useMemo(() => {
return {
get() {
return teamData;
},
set(fn: (currentTeamData: typeof teamData) => typeof teamData) {
data.set(d => ({ ...d, [providerTeamId]: fn(teamData) }));
}
};
}, [teamData]);
}
export type SharingAttributes = Pick<
CreateThirdPartyPostRequest,
"providerId" | "providerTeamId" | "channelId"
> & {
providerTeamName?: string;
channelName?: string;
};
const EMPTY_HASH = {};
export const SharingControls = React.memo(
(props: {
onChangeValues: (values?: SharingAttributes) => void;
showToggle?: boolean;
repoId?: string;
}) => {
const dispatch = useDispatch();
const derivedState = useSelector((state: CodeStreamState) => {
const currentTeamId = state.context.currentTeamId;
const preferencesForTeam = state.preferences[currentTeamId] || {};
const defaultChannels = preferencesForTeam.defaultChannel || {};
const defaultChannel = props.repoId && defaultChannels[props.repoId];
// this is what we've persisted in the server as the last selection the user made
const lastShareAttributes: SharingAttributes | undefined =
preferencesForTeam.lastShareAttributes;
const shareTargets = getConnectedSharingTargets(state);
const selectedShareTarget = shareTargets.find(
target =>
target.teamId ===
(state.context.shareTargetTeamId ||
(defaultChannel && defaultChannel.providerTeamId) ||
(lastShareAttributes && lastShareAttributes.providerTeamId))
);
const team = state.teams[state.context.currentTeamId];
const teamSettings = team.settings || (EMPTY_HASH as CSTeamSettings);
return {
currentTeamId,
on: shareTargets.length > 0 && Boolean(preferencesForTeam.shareCodemarkEnabled),
slackConfig: getProviderConfig(state, "slack"),
msTeamsConfig: getProviderConfig(state, "msteams"),
isConnectedToSlack: isConnected(state, { name: "slack" }),
isConnectedToMSTeams: isConnected(state, { name: "msteams" }),
shareTargets,
selectedShareTarget: selectedShareTarget || shareTargets[0],
lastSelectedChannelId: lastShareAttributes && lastShareAttributes.channelId,
repos: state.repos,
defaultChannelId: defaultChannel && defaultChannel.channelId,
defaultChannels,
teamSettings
};
});
const [authenticationState, setAuthenticationState] = React.useState<{
isAuthenticating: boolean;
label: string;
}>({ isAuthenticating: false, label: "" });
const [isFetchingData, setIsFetchingData] = React.useState<boolean>(false);
const [editingChannels, setEditingChannels] = React.useState<boolean>(false);
const [currentChannel, setCurrentChannel] = React.useState<ThirdPartyChannel | undefined>(
undefined
);
useDidMount(() => {
if (
!derivedState.selectedShareTarget ||
(!derivedState.isConnectedToSlack && !derivedState.isConnectedToMSTeams)
) {
dispatch(setUserPreference([derivedState.currentTeamId, "shareCodemarkEnabled"], false));
}
});
const selectedShareTargetTeamId = safe(() => derivedState.selectedShareTarget.teamId) as
| string
| undefined;
const data = useDataForTeam(
derivedState.slackConfig
? derivedState.slackConfig.id
: derivedState.msTeamsConfig
? derivedState.msTeamsConfig.id
: "",
selectedShareTargetTeamId
);
const setCheckbox = value =>
dispatch(setUserPreference([derivedState.currentTeamId, "shareCodemarkEnabled"], value));
const toggleCheckbox = () => setCheckbox(!derivedState.on);
const setSelectedShareTarget = target => {
setCheckbox(true);
dispatch(setContext({ shareTargetTeamId: target.teamId }));
};
useUpdates(() => {
const numberOfTargets = derivedState.shareTargets.length;
if (numberOfTargets === 0) return;
// when the first share target is connected, turn on sharing
if (numberOfTargets === 1 && !derivedState.on) toggleCheckbox();
// if we're waiting on something to be added, this is it so make it the current selection
if (authenticationState && authenticationState.isAuthenticating) {
const newShareTarget = getLast(derivedState.shareTargets)!;
setSelectedShareTarget(newShareTarget);
setAuthenticationState({ isAuthenticating: false, label: "" });
}
}, [derivedState.shareTargets.length]);
// when selected share target changes, fetch channels
React.useEffect(() => {
const { selectedShareTarget } = derivedState;
if (selectedShareTarget) {
if (data.get().channels.length === 0) setIsFetchingData(true);
void (async () => {
try {
const response = await HostApi.instance.send(FetchThirdPartyChannelsRequestType, {
providerId: selectedShareTarget.providerId,
providerTeamId: selectedShareTarget.teamId
});
/*
if we know the channel the user last selected for this target
AND the webview doesn't currently have one selected,
use the last selected one if it still exists
*/
const channelIdToSelect =
derivedState.defaultChannelId || derivedState.lastSelectedChannelId;
const channelToSelect =
channelIdToSelect != undefined
? response.channels.find(c => c.id === channelIdToSelect)
: undefined;
data.set(teamData => ({
...teamData,
channels: response.channels,
lastSelectedChannel: channelToSelect || teamData.lastSelectedChannel
}));
setCurrentChannel(undefined);
} catch (error) {
} finally {
setIsFetchingData(false);
}
})();
}
}, [selectedShareTargetTeamId]);
const selectedChannel = React.useMemo(() => {
const { channels, lastSelectedChannel } = data.get();
// if the user has picked a channel this session, return it
if (currentChannel != undefined) return currentChannel;
// otherwise, if there is a default for this repo, return that
if (derivedState.defaultChannelId != undefined) {
const channel = channels.find(c => c.id === derivedState.defaultChannelId);
if (channel) return channel;
}
// otherwise, return the last selected channel (saved on server in preferences)
return lastSelectedChannel;
}, [currentChannel, derivedState.defaultChannelId, data]);
React.useEffect(() => {
const shareTarget = derivedState.selectedShareTarget;
if (shareTarget && selectedChannel) {
props.onChangeValues({
providerId: shareTarget.providerId,
providerTeamId: shareTarget.teamId,
providerTeamName: shareTarget.teamName,
channelId: selectedChannel && selectedChannel.id,
channelName: selectedChannel && formatChannelName(selectedChannel)
});
dispatch(
setUserPreference([derivedState.currentTeamId, "lastShareAttributes"], {
channelId: selectedChannel.id,
providerId: shareTarget.providerId,
providerTeamId: shareTarget.teamId
})
);
} else props.onChangeValues(undefined);
}, [
derivedState.selectedShareTarget && derivedState.selectedShareTarget.teamId,
selectedChannel && selectedChannel.id,
// hack[?] for asserting this hook runs after the data has changed.
// for some reason selectedChannel updating is not making this hook
// re-run
isFetchingData
]);
const { teamSettings } = derivedState;
const providers = teamSettings.messagingProviders || {};
const showSlack = !teamSettings.limitMessaging || providers["slack*com"];
const showTeams = !teamSettings.limitMessaging || providers["login*microsoftonline*com"];
const shareProviderMenuItems = React.useMemo(() => {
const targetItems = derivedState.shareTargets.map(target => ({
key: target.teamId,
icon: <Icon name={target.icon} />,
label: target.teamName,
action: () => setSelectedShareTarget(target)
}));
if (derivedState.slackConfig || derivedState.msTeamsConfig) {
targetItems.push({ label: "-" } as any);
if (showSlack && derivedState.slackConfig)
targetItems.push({
key: "add-slack",
icon: <Icon name="slack" />,
label: "Add Slack workspace",
action: (() => {
authenticateWithSlack();
}) as any
});
if (showTeams && derivedState.msTeamsConfig) {
targetItems.push({
key: "add-msteams",
icon: <Icon name="msteams" />,
label: "Add Teams organization",
action: (() => {
authenticateWithMSTeams();
}) as any
} as any);
}
}
return targetItems;
}, [derivedState.shareTargets, derivedState.slackConfig, derivedState.msTeamsConfig]);
const getChannelMenuItems = action => {
// return React.useMemo(() => {
if (derivedState.selectedShareTarget == undefined) return [];
const dataForTeam = data.get();
if (dataForTeam.channels == undefined) return [];
const { dms, others } = dataForTeam.channels.reduce(
(group, channel) => {
const channelName = formatChannelName(channel);
const item = {
key: channel.name,
label: channelName,
searchLabel: channelName,
action: () => action(channel)
};
if (channel.type === "direct") {
group.dms.push(item);
} else group.others.push(item);
return group;
},
{ dms: [], others: [] } as { dms: any[]; others: any[] }
);
const search =
dataForTeam.channels.length > 5
? [{ type: "search", placeholder: "Search..." }, { label: "-" }]
: [];
if (dms && dms.length) {
return [...search, ...others, { label: "-" }, ...dms];
} else {
return [...search, ...others];
}
// }, [data.get().channels]);
};
const setChannel = channel => {
if (props.showToggle) setCheckbox(true);
setCurrentChannel(channel);
data.set(teamData => ({ ...teamData, lastSelectedChannel: channel }));
};
const authenticateWithSlack = () => {
setAuthenticationState({ isAuthenticating: true, label: "Slack" });
dispatch(connectProvider(derivedState.slackConfig!.id, "Compose Modal"));
};
const authenticateWithMSTeams = () => {
setAuthenticationState({ isAuthenticating: true, label: "MS Teams" });
dispatch(connectProvider(derivedState.msTeamsConfig!.id, "Compose Modal"));
};
if (derivedState.slackConfig == undefined) return null;
if (authenticationState && authenticationState.isAuthenticating)
return (
<Root>
<Icon name="sync" className="spin" />{" "}
{authenticationState.label == "MS Teams"
? "Setting up MS Teams bot"
: `Authenticating with ${authenticationState.label}`}
...{" "}
<a
onClick={e => {
e.preventDefault();
setAuthenticationState({ isAuthenticating: false, label: "" });
}}
>
cancel
</a>
</Root>
);
if (isFetchingData)
return (
<Root>
<Icon name="sync" className="spin" /> Fetching channels...{" "}
<a
onClick={e => {
e.preventDefault();
setIsFetchingData(false);
}}
>
cancel
</a>
</Root>
);
if (
!derivedState.selectedShareTarget ||
(!derivedState.isConnectedToSlack && !derivedState.isConnectedToMSTeams)
) {
if (!showSlack && !showTeams) return null;
return (
<Root>
Share on{" "}
{showSlack && (
<TextButton
onClick={async e => {
e.preventDefault();
authenticateWithSlack();
}}
>
<Icon name="slack" /> Slack
</TextButton>
)}
{derivedState.msTeamsConfig != undefined && showTeams && (
<>
{" "}
{showSlack && <>or </>}
<TextButton
onClick={e => {
e.preventDefault();
authenticateWithMSTeams();
}}
>
<Icon name="msteams" /> MS Teams
</TextButton>
</>
)}
</Root>
);
}
const setDefaultChannel = (repoId, providerTeamId, channelId) => {
const value = { providerTeamId, channelId };
dispatch(setUserPreference([derivedState.currentTeamId, "defaultChannel", repoId], value));
};
const getChannelById = id => {
return data.get().channels.find(c => c.id == id);
};
const renderDefaultChannels = () => {
const { repos, defaultChannels } = derivedState;
return (
<Root>
<ChannelTable>
<thead>
<tr>
<td>Repo</td>
<td>Default</td>
</tr>
<tr>
<td colSpan={2}>
<hr />
</td>
</tr>
</thead>
<tbody>
{Object.keys(repos)
.sort((a, b) => repos[a].name.localeCompare(repos[b].name))
.map(key => {
const defaultSettings = defaultChannels[key];
const defaultChannel = defaultSettings
? getChannelById(defaultSettings.channelId)
: undefined;
return (
<tr>
<td>
<Icon name="repo" /> {repos[key].name}
</td>
<td>
<InlineMenu
items={getChannelMenuItems(channel =>
setDefaultChannel(
key,
derivedState.selectedShareTarget!.teamId,
channel.id
)
)}
title={`Default Channel for ${repos[key].name}`}
>
{defaultChannel == undefined
? "last channel used "
: formatChannelName(defaultChannel)}
</InlineMenu>
</td>
</tr>
);
})}
</tbody>
</ChannelTable>
<div style={{ textAlign: "center", margin: "20px auto" }}>
<Button onClick={e => setEditingChannels(false)}>Done</Button>
</div>
</Root>
);
};
if (editingChannels) {
return <Modal onClose={() => setEditingChannels(false)}>{renderDefaultChannels()}</Modal>;
}
const hasRepos = derivedState.repos && Object.keys(derivedState.repos).length > 0;
const channelTitleIcon = hasRepos ? (
<Icon
name="gear"
title="Set Default Channels"
placement="top"
onClick={e => setEditingChannels(!editingChannels)}
/>
) : null;
return (
<Root>
{props.showToggle && (
<>
<input type="checkbox" checked={derivedState.on} onChange={toggleCheckbox} />
</>
)}
Share on{" "}
<InlineMenu items={shareProviderMenuItems}>
<Icon name={derivedState.selectedShareTarget!.icon} />{" "}
{derivedState.selectedShareTarget!.teamName}
</InlineMenu>{" "}
in{" "}
<InlineMenu
items={getChannelMenuItems(channel => setChannel(channel))}
title="Post to..."
titleIcon={channelTitleIcon}
>
{selectedChannel == undefined ? "select a channel" : formatChannelName(selectedChannel)}
</InlineMenu>
</Root>
);
}
); | the_stack |
import {
AgEvent,
Autowired,
Component,
MenuItemDef,
PostConstruct,
CustomTooltipFeature,
PopupService,
IComponent,
KeyCode,
ITooltipParams,
_
} from "@ag-grid-community/core";
import { MenuList } from './menuList';
import { MenuPanel } from './menuPanel';
export interface MenuItemSelectedEvent extends AgEvent {
name: string;
disabled?: boolean;
shortcut?: string;
action?: () => void;
checked?: boolean;
icon?: HTMLElement | string;
subMenu?: (MenuItemDef | string)[] | IComponent<any>;
cssClasses?: string[];
tooltip?: string;
event: MouseEvent | KeyboardEvent;
}
export interface MenuItemActivatedEvent extends AgEvent {
menuItem: MenuItemComponent;
}
export interface MenuItemComponentParams extends MenuItemDef {
isCompact?: boolean;
isAnotherSubMenuOpen: () => boolean;
}
export class MenuItemComponent extends Component {
@Autowired('popupService') private readonly popupService: PopupService;
public static EVENT_MENU_ITEM_SELECTED = 'menuItemSelected';
public static EVENT_MENU_ITEM_ACTIVATED = 'menuItemActivated';
public static ACTIVATION_DELAY = 80;
private isActive = false;
private tooltip: string;
private hideSubMenu: (() => void) | null;
private subMenuIsOpen = false;
private activateTimeoutId: number;
private deactivateTimeoutId: number;
constructor(private readonly params: MenuItemComponentParams) {
super();
this.setTemplate(/* html */`<div class="${this.getClassName()}" tabindex="-1" role="treeitem"></div>`);
}
@PostConstruct
private init() {
this.addIcon();
this.addName();
this.addShortcut();
this.addSubMenu();
this.addTooltip();
const eGui = this.getGui();
if (this.params.disabled) {
this.addCssClass(this.getClassName('disabled'));
_.setAriaDisabled(eGui, true);
} else {
this.addGuiEventListener('click', e => this.onItemSelected(e));
this.addGuiEventListener('keydown', (e: KeyboardEvent) => {
if (e.keyCode === KeyCode.ENTER || e.keyCode === KeyCode.SPACE) {
e.preventDefault();
this.onItemSelected(e);
}
});
this.addGuiEventListener('mouseenter', () => this.onMouseEnter());
this.addGuiEventListener('mouseleave', () => this.onMouseLeave());
}
if (this.params.cssClasses) {
this.params.cssClasses.forEach(it => _.addCssClass(eGui, it));
}
}
public isDisabled(): boolean {
return !!this.params.disabled;
}
public openSubMenu(activateFirstItem = false): void {
this.closeSubMenu();
if (!this.params.subMenu) { return; }
const ePopup = _.loadTemplate(/* html */`<div class="ag-menu" role="presentation"></div>`);
let destroySubMenu: () => void;
if (this.params.subMenu instanceof Array) {
const currentLevel = _.getAriaLevel(this.getGui());
const nextLevel = isNaN(currentLevel) ? 1 : (currentLevel + 1);
const childMenu = this.createBean(new MenuList(nextLevel));
childMenu.setParentComponent(this);
childMenu.addMenuItems(this.params.subMenu);
ePopup.appendChild(childMenu.getGui());
// bubble menu item selected events
this.addManagedListener(childMenu, MenuItemComponent.EVENT_MENU_ITEM_SELECTED, e => this.dispatchEvent(e));
childMenu.addGuiEventListener('mouseenter', () => this.cancelDeactivate());
destroySubMenu = () => this.destroyBean(childMenu);
if (activateFirstItem) {
setTimeout(() => childMenu.activateFirstItem(), 0);
}
} else {
const { subMenu } = this.params;
const menuPanel = this.createBean(new MenuPanel(subMenu));
menuPanel.setParentComponent(this);
const subMenuGui = menuPanel.getGui();
const mouseEvent = 'mouseenter';
const mouseEnterListener = () => this.cancelDeactivate();
subMenuGui.addEventListener(mouseEvent, mouseEnterListener);
destroySubMenu = () => subMenuGui.removeEventListener(mouseEvent, mouseEnterListener);
ePopup.appendChild(subMenuGui);
if (subMenu.afterGuiAttached) {
setTimeout(() => subMenu.afterGuiAttached!(), 0);
}
}
const eGui = this.getGui();
const positionCallback = this.popupService.positionPopupForMenu.bind(this.popupService,
{ eventSource: eGui, ePopup });
const translate = this.gridOptionsWrapper.getLocaleTextFunc();
const addPopupRes = this.popupService.addPopup({
modal: true,
eChild: ePopup,
positionCallback: positionCallback,
anchorToElement: eGui,
ariaLabel: translate('ariaLabelSubMenu', 'SubMenu')
});
this.subMenuIsOpen = true;
_.setAriaExpanded(eGui, true);
this.hideSubMenu = () => {
if (addPopupRes) {
addPopupRes.hideFunc();
}
this.subMenuIsOpen = false;
_.setAriaExpanded(eGui, false);
destroySubMenu();
};
}
public closeSubMenu(): void {
if (!this.hideSubMenu) { return; }
this.hideSubMenu();
this.hideSubMenu = null;
_.setAriaExpanded(this.getGui(), false);
}
public isSubMenuOpen(): boolean {
return this.subMenuIsOpen;
}
public activate(openSubMenu?: boolean): void {
this.cancelActivate();
if (this.params.disabled) { return; }
this.isActive = true;
this.addCssClass(this.getClassName('active'));
this.getGui().focus();
if (openSubMenu && this.params.subMenu) {
window.setTimeout(() => {
if (this.isAlive() && this.isActive) {
this.openSubMenu();
}
}, 300);
}
this.onItemActivated();
}
public deactivate() {
this.cancelDeactivate();
this.removeCssClass(this.getClassName('active'));
this.isActive = false;
if (this.subMenuIsOpen) {
this.hideSubMenu!();
}
}
private addIcon(): void {
if (!this.params.checked && !this.params.icon && this.params.isCompact) { return; }
const icon = _.loadTemplate(/* html */
`<span ref="eIcon" class="${this.getClassName('part')} ${this.getClassName('icon')}" role="presentation"></span>`
);
if (this.params.checked) {
icon.appendChild(_.createIconNoSpan('check', this.gridOptionsWrapper)!);
} else if (this.params.icon) {
if (_.isNodeOrElement(this.params.icon)) {
icon.appendChild(this.params.icon as HTMLElement);
} else if (typeof this.params.icon === 'string') {
icon.innerHTML = this.params.icon;
} else {
console.warn('AG Grid: menu item icon must be DOM node or string');
}
}
this.getGui().appendChild(icon);
}
private addName(): void {
if (!this.params.name && this.params.isCompact) { return; }
const name = _.loadTemplate(/* html */
`<span ref="eName" class="${this.getClassName('part')} ${this.getClassName('text')}">${this.params.name || ''}</span>`
);
this.getGui().appendChild(name);
}
private addTooltip(): void {
if (!this.params.tooltip) { return; }
this.tooltip = this.params.tooltip;
if (this.gridOptionsWrapper.isEnableBrowserTooltips()) {
this.getGui().setAttribute('title', this.tooltip);
} else {
this.createManagedBean(new CustomTooltipFeature(this));
}
}
public getTooltipParams(): ITooltipParams {
return {
location: 'menu',
value: this.tooltip
};
}
private addShortcut(): void {
if (!this.params.shortcut && this.params.isCompact) { return; }
const shortcut = _.loadTemplate(/* html */
`<span ref="eShortcut" class="${this.getClassName('part')} ${this.getClassName('shortcut')}">${this.params.shortcut || ''}</span>`
);
this.getGui().appendChild(shortcut);
}
private addSubMenu(): void {
if (!this.params.subMenu && this.params.isCompact) { return; }
const pointer = _.loadTemplate(/* html */
`<span ref="ePopupPointer" class="${this.getClassName('part')} ${this.getClassName('popup-pointer')}"></span>`
);
const eGui = this.getGui();
if (this.params.subMenu) {
const iconName = this.gridOptionsWrapper.isEnableRtl() ? 'smallLeft' : 'smallRight';
_.setAriaExpanded(eGui, false);
pointer.appendChild(_.createIconNoSpan(iconName, this.gridOptionsWrapper)!);
}
eGui.appendChild(pointer);
}
private onItemSelected(event: MouseEvent | KeyboardEvent): void {
if (this.params.action) {
this.params.action();
} else {
this.openSubMenu(event && event.type === 'keydown');
}
if (this.params.subMenu && !this.params.action) { return; }
const e: MenuItemSelectedEvent = {
type: MenuItemComponent.EVENT_MENU_ITEM_SELECTED,
action: this.params.action,
checked: this.params.checked,
cssClasses: this.params.cssClasses,
disabled: this.params.disabled,
icon: this.params.icon,
name: this.params.name,
shortcut: this.params.shortcut,
subMenu: this.params.subMenu,
tooltip: this.params.tooltip,
event
};
this.dispatchEvent(e);
}
private onItemActivated(): void {
const event: MenuItemActivatedEvent = {
type: MenuItemComponent.EVENT_MENU_ITEM_ACTIVATED,
menuItem: this,
};
this.dispatchEvent(event);
}
private cancelActivate(): void {
if (this.activateTimeoutId) {
window.clearTimeout(this.activateTimeoutId);
this.activateTimeoutId = 0;
}
}
private cancelDeactivate(): void {
if (this.deactivateTimeoutId) {
window.clearTimeout(this.deactivateTimeoutId);
this.deactivateTimeoutId = 0;
}
}
private onMouseEnter(): void {
this.cancelDeactivate();
if (this.params.isAnotherSubMenuOpen()) {
// wait to see if the user enters the open sub-menu
this.activateTimeoutId = window.setTimeout(() => this.activate(true), MenuItemComponent.ACTIVATION_DELAY);
} else {
// activate immediately
this.activate(true);
}
}
private onMouseLeave(): void {
this.cancelActivate();
if (this.isSubMenuOpen()) {
// wait to see if the user enters the sub-menu
this.deactivateTimeoutId = window.setTimeout(() => this.deactivate(), MenuItemComponent.ACTIVATION_DELAY);
} else {
// de-activate immediately
this.deactivate();
}
}
private getClassName(suffix?: string) {
const prefix = this.params.isCompact ? 'ag-compact-menu-option' : 'ag-menu-option';
return suffix ? `${prefix}-${suffix}` : prefix;
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.