text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import React, {useEffect, useState} from 'react';
import Form, {FormComponentProps} from 'antd/lib/form';
import {AutoComplete, Card, Col, Icon, Input, Popconfirm, Row, Select} from 'antd';
import {AlarmTrigger} from '@/pages/device/alarm/data';
interface Props extends FormComponentProps {
trigger: Partial<AlarmTrigger>;
save: Function;
remove: Function;
position: number;
metaData?: string;
}
interface State {
triggerType: string;
messageType: string;
parameters: any[];
trigger: any;
filters: any[];
dataSource: any[];
}
const Trigger: React.FC<Props> = props => {
const initState: State = {
triggerType: '',
messageType: '',
parameters: props.trigger.parameters ? (props.trigger.parameters.length > 0 ? props.trigger.parameters
: [{_id: 0}]) : [{_id: 0}],
trigger: props.trigger,
filters: props.trigger.filters ? (props.trigger.filters.length > 0 ? props.trigger.filters : [{_id: 0}]) : [{_id: 0}],
dataSource: [],
};
const [triggerType, setTriggerType] = useState(initState.triggerType);
const [messageType, setMessageType] = useState(initState.messageType);
const [parameters, setParameters] = useState(initState.parameters);
const [filters, setFilters] = useState(initState.filters);
const [dataSource, setDataSource] = useState(initState.dataSource);
const [trigger, setTrigger] = useState(initState.trigger);
useEffect(() => {
setTriggerType(trigger.trigger);
setMessageType(trigger.type);
let data: any;
if (props.metaData) {
let metadata = JSON.parse(props.metaData);
if (trigger.type === 'event') {
data = metadata['events'];
} else if (trigger.type === 'function') {
data = metadata['functions'];
} else {
data = metadata[trigger.type];
}
if (data) {
dataSource.length = 0;
dataSource.push(trigger.modelId);
data.map((item: any) => {
if (item.id === trigger.modelId) {
setDataSourceValue(trigger.type, item, trigger.modelId);
} else {
setDataSource([]);
}
});
}
}
}, []);
const submitData = () => {
props.save({
...trigger,
});
};
const setDataSourceValue = (type: string, data: any, value: string) => {
dataSource.length = 0;
dataSource.push(value);
if (type === 'function') {
if (data.output.type === 'object') {
data.valueType?.properties.map((p: any) => {
dataSource.push(`${value}.${p.id}`);
});
}
} else if (type === 'event') {
dataSource.push('this');
if (data.valueType.type === 'object') {
data.valueType?.properties.map((p: any) => {
dataSource.push(`${p.id}`);
});
}
} else if (type === 'properties') {
if (data.valueType.type === 'object') {
data.valueType?.properties.map((p: any) => {
dataSource.push(`${value}.${p.id}`);
});
}
}
setDataSource([...dataSource]);
};
const renderType = () => {
switch (messageType) {
case 'properties':
return (
<Col span={6} style={{paddingBottom: 10, paddingLeft: 3, paddingRight: 9}}>
<Select placeholder="物模型属性" defaultValue={trigger.modelId}
onChange={(value: string, data: any) => {
setDataSourceValue('properties', data.props.data, value);
trigger.modelId = value;
setTrigger(trigger);
submitData();
}}
>
{JSON.parse(props.metaData || '[]').properties?.map((item: any) => (
<Select.Option key={item.id} data={item}>{`${item.name}(${item.id})`}</Select.Option>
))}
</Select>
</Col>
);
case 'event':
return (
<Col span={6} style={{paddingBottom: 10, paddingLeft: 3, paddingRight: 9}}>
<Select placeholder="物模型事件" defaultValue={trigger.modelId}
onChange={(value: string, data: any) => {
setDataSourceValue('event', data.props.data, value);
trigger.modelId = value;
setTrigger(trigger);
submitData();
}}
>
{JSON.parse(props.metaData || '[]').events?.map((item: any) => (
<Select.Option key={item.id} data={item}>{`${item.name}(${item.id})`}</Select.Option>
))}
</Select>
</Col>
);
case 'function':
return (
<Col span={6} style={{paddingBottom: 10, paddingLeft: 3, paddingRight: 9}}>
<Select placeholder="物模型功能" defaultValue={trigger.modelId}
onChange={(value: string, data: any) => {
setDataSourceValue('function', data.props.data, value);
trigger.modelId = value;
setTrigger(trigger);
submitData();
}}
>
{JSON.parse(props.metaData).functions?.map((item: any) => (
<Select.Option key={item.id} data={item}>{`${item.name}(${item.id})`}</Select.Option>
))}
</Select>
</Col>
);
default:
return null;
}
};
const renderDataType = () => {
switch (triggerType) {
case 'device':
return (
<div>
<Col span={24}>
<Col span={6} style={{paddingBottom: 10, paddingLeft: -1, paddingRight: 12}}>
<Select placeholder="选择类型,如:属性/事件" defaultValue={trigger.type}
onChange={(value: string) => {
setMessageType(() => value);
trigger.type = value;
setTrigger(trigger);
submitData();
}}>
<Select.Option value="online">上线</Select.Option>
<Select.Option value="offline">离线</Select.Option>
{props.metaData && JSON.parse(props.metaData).properties && (
<Select.Option value="properties">属性</Select.Option>
)}
{props.metaData && JSON.parse(props.metaData).events && (
<Select.Option value="event">事件</Select.Option>
)}
{props.metaData && JSON.parse(props.metaData).functions && (
<Select.Option value="function">功能</Select.Option>
)}
</Select>
</Col>
{renderType()}
</Col>
<Col span={24}>
{filters.map((item: any, index: number) => (
<div className="ant-row" key={index}>
<Col span={6} style={{paddingLeft: -1, paddingRight: 12, paddingBottom: 10}}>
<AutoComplete dataSource={dataSource} placeholder="过滤条件KEY" children={item.key}
defaultValue={item.key}
onBlur={value => {
filters[index].key = value;
trigger.filters = filters;
setTrigger(trigger);
submitData();
}}
/*onChange={value => {
filters[index].key = value;
trigger.filters = filters;
setTrigger(trigger);
submitData();
}}*/
filterOption={(inputValue, option) =>
option?.props?.children?.toUpperCase()?.indexOf(inputValue.toUpperCase()) !== -1
}
/>
</Col>
<Col span={6} style={{paddingLeft: 3, paddingRight: 9, paddingBottom: 10}}>
<Select placeholder="操作符" defaultValue={item.operator}
onChange={(value: string) => {
filters[index].operator = value;
trigger.filters = filters;
setTrigger(trigger);
submitData();
}}>
<Select.Option value="eq">等于(=)</Select.Option>
<Select.Option value="not">不等于(!=)</Select.Option>
<Select.Option value="gt">大于(>)</Select.Option>
<Select.Option value="lt">小于(<)</Select.Option>
<Select.Option value="gte">大于等于(>=)</Select.Option>
<Select.Option value="lte">小于等于(<=)</Select.Option>
<Select.Option value="like">模糊(%)</Select.Option>
</Select>
</Col>
<Col span={7} style={{paddingLeft: 7, paddingRight: 3, paddingBottom: 10}}>
<Input placeholder="过滤条件值" defaultValue={item.value}
onChange={event => {
filters[index].value = event.target.value;
trigger.filters = filters;
setTrigger(trigger);
submitData();
}}
/>
</Col>
<Col span={5} style={{textAlign: 'right', marginTop: 6, paddingBottom: 10}}>
<a style={{paddingLeft: 10, paddingTop: 7}}
onClick={() => {
filters.splice(index, 1);
setFilters([...filters]);
trigger.filters = filters;
setTrigger({...trigger});
submitData();
}}
>删除</a>
</Col>
</div>
))}
</Col>
<Col span={24}>
<div>
<a onClick={() => {
setFilters([...filters, {_id: Math.round(Math.random() * 100000)}]);
}}>添加</a>
</div>
</Col>
</div>
);
case 'timer':
return (
<div>
<Col span={6} style={{paddingBottom: 10}}>
<Input placeholder="cron表达式" defaultValue={trigger.cron} key="cron"
onBlur={event => {
trigger.cron = event.target.value;
setTrigger(trigger);
submitData();
}}
/>
</Col>
<Col span={24}>
<Col span={6} style={{paddingBottom: 10, paddingLeft: -1, paddingRight: 12}}>
<Select placeholder="选择类型,如:属性/事件" defaultValue={trigger.type}
onChange={(value: string) => {
setMessageType(() => value);
trigger.type = value;
setTrigger(trigger);
submitData();
}}>
{props.metaData && JSON.parse(props.metaData).properties && (
<Select.Option value="properties">属性</Select.Option>
)}
{/* {props.metaData && JSON.parse(props.metaData).events && (
<Select.Option value="event">事件</Select.Option>
)} */}
{props.metaData && JSON.parse(props.metaData).functions && (
<Select.Option value="function">功能</Select.Option>
)}
</Select>
</Col>
{renderType()}
</Col>
{triggerType === 'timer' && messageType === 'function' && (
<Col span={24} style={{backgroundColor: '#F5F5F6', paddingBottom: 10}}>
{parameters.map((item: any, index: number) => (
<Row style={{paddingBottom: 5, paddingTop: 5}} key={index}>
<Col span={7}>
<Input placeholder="请输入属性" value={item.property}
onChange={event => {
parameters[index].property = event.target.value;
setParameters([...parameters]);
trigger.parameters = parameters;
setTrigger({...trigger});
submitData();
}}
/>
</Col>
<Col span={1} style={{textAlign: 'center'}}/>
<Col span={7}>
<Input placeholder="请输入别名" value={item.alias}
onChange={event => {
parameters[index].alias = event.target.value;
setParameters([...parameters]);
trigger.parameters = parameters;
setTrigger({...trigger});
submitData();
}}
/>
</Col>
<Col span={1} style={{textAlign: 'center'}}>
{index === 0 ? (
<Row>
<Icon type="plus-circle" title="新增转换"
style={{fontSize: 20, paddingTop: 7}}
onClick={() => {
setParameters([...parameters, {_id: Math.round(Math.random() * 100000)}]);
}}
/>
<Icon style={{paddingLeft: 10, paddingTop: 7, fontSize: 20}}
type="minus-circle" title="删除转换"
onClick={() => {
parameters.splice(index, 1);
setParameters([...parameters]);
trigger.parameters = parameters;
setTrigger({...trigger});
submitData();
}}
/>
</Row>
) : (
<Icon type="minus-circle" title="删除转换"
style={{fontSize: 20, paddingTop: 7}}
onClick={() => {
parameters.splice(index, 1);
setParameters([...parameters]);
trigger.parameters = parameters;
setTrigger({...trigger});
submitData();
}}
/>
)}
</Col>
</Row>
))}
</Col>
)}
<Col span={24}>
{filters.map((item: any, index: number) => (
<div className="ant-row" key={index}>
<Col span={6} style={{paddingLeft: -1, paddingRight: 12, paddingBottom: 10}}>
<AutoComplete dataSource={dataSource} placeholder="过滤条件KEY" children={item.key}
defaultValue={item.key}
onBlur={value => {
filters[index].key = value;
trigger.filters = filters;
setTrigger(trigger);
submitData();
}}
/*onChange={value => {
filters[index].key = value;
trigger.filters = filters;
setTrigger(trigger);
submitData();
}}*/
filterOption={(inputValue, option) =>
option?.props?.children?.toUpperCase()?.indexOf(inputValue.toUpperCase()) !== -1
}
/>
</Col>
<Col span={6} style={{paddingLeft: 3, paddingRight: 9, paddingBottom: 10}}>
<Select placeholder="操作符" defaultValue={item.operator}
onChange={(value: string) => {
filters[index].operator = value;
trigger.filters = filters;
setTrigger(trigger);
submitData();
}}>
<Select.Option value="eq">等于(=)</Select.Option>
<Select.Option value="not">不等于(!=)</Select.Option>
<Select.Option value="gt">大于(>)</Select.Option>
<Select.Option value="lt">小于(<)</Select.Option>
<Select.Option value="gte">大于等于(>=)</Select.Option>
<Select.Option value="lte">小于等于(<=)</Select.Option>
<Select.Option value="like">模糊(%)</Select.Option>
</Select>
</Col>
<Col span={7} style={{paddingLeft: 7, paddingRight: 3, paddingBottom: 10}}>
<Input placeholder="过滤条件值" defaultValue={item.value}
onBlur={event => {
filters[index].value = event.target.value;
trigger.filters = filters;
setTrigger(trigger);
submitData();
}}
/*onChange={event => {
filters[index].value = event.target.value;
trigger.filters = filters;
setTrigger(trigger);
submitData();
}}*/
/>
</Col>
<Col span={5} style={{textAlign: 'right', marginTop: 6, paddingBottom: 10}}>
<a style={{paddingLeft: 10, paddingTop: 7}}
onClick={() => {
filters.splice(index, 1);
setFilters([...filters]);
if (filters.length > 0) {
trigger.filters = filters;
setTrigger({...trigger});
}
submitData();
}}
>删除</a>
</Col>
</div>
))}
</Col>
<Col span={24}>
<div>
<a onClick={() => {
setFilters([...filters, {_id: Math.round(Math.random() * 100000)}]);
}}>添加</a>
</div>
</Col>
</div>
);
default:
return null;
}
};
return (
<div style={{paddingBottom: 5}}>
<Card size="small" bordered={false} style={{backgroundColor: '#F5F5F6'}}>
<Row style={{marginLeft: -2}}>
<span>触发器: {props.position + 1}</span>
<Popconfirm
title="确认删除此触发器?"
onConfirm={() => {
props.remove(props.position);
}}
>
<a style={{paddingLeft: 30}}>删除</a>
</Popconfirm>
</Row>
<Row gutter={16} style={{paddingLeft: 10}}>
<Col span={6} style={{paddingBottom: 10}}>
<Select
placeholder="选择触发器类型"
value={trigger.trigger}
onChange={(value: string) => {
setTriggerType(() => value);
trigger.trigger = value;
submitData();
}}
>
<Select.Option value="device">设备触发</Select.Option>
<Select.Option value="timer">定时触发</Select.Option>
</Select>
</Col>
{renderDataType()}
</Row>
</Card>
</div>
);
};
export default Form.create<Props>()(Trigger); | the_stack |
import { observable, action } from 'mobx';
import { FsApi, File } from '../services/Fs';
import { FileTransfer } from './fileTransfer';
import { Deferred } from '../utils/deferred';
import { getLocalizedError } from '../locale/error';
import { Readable } from 'stream';
import { getSelectionRange } from '../utils/fileUtils';
import { isWin } from '../utils/platform';
const MAX_TRANSFERS = 2;
const MAX_ERRORS = 5;
const RENAME_SUFFIX = '_';
type Status = 'started' | 'queued' | 'error' | 'done' | 'cancelled' | 'calculating';
export class Batch {
static maxId = 1;
public srcFs: FsApi;
public dstFs: FsApi;
public dstPath: string;
public srcPath: string;
public id: number;
public srcName: string;
public dstName: string;
public startDate: Date = new Date();
public errors = 0;
@observable
public size = 0;
public elements = observable<FileTransfer>([]);
public streams = new Array<Readable>();
@observable
public status: Status = 'queued';
@observable
public progress = 0;
get isStarted(): boolean {
return !this.status.match(/error|done/);
}
get hasEnded(): boolean {
return !!this.status.match(/done|error/);
}
public isExpanded = false;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private transferDef: Deferred<any>;
private slotsAvailable: number = MAX_TRANSFERS;
private transfersDone = 0;
constructor(srcFs: FsApi, dstFs: FsApi, srcPath: string, dstPath: string) {
this.status = 'calculating';
this.srcFs = srcFs;
this.dstFs = dstFs;
this.dstPath = dstPath;
this.srcPath = srcPath;
// build batch src/dst names
this.srcName = this.getLastPathPart(srcPath);
this.dstName = this.getLastPathPart(dstPath);
this.id = Batch.maxId++;
}
@action
onEndTransfer = (): Promise<boolean> => {
// console.log('transfer ended ! duration=', Math.round((new Date().getTime() - this.startDate.getTime()) / 1000), 'sec(s)');
// console.log('destroy batch, new maxId', Batch.maxId);
this.status = 'done';
return Promise.resolve(this.errors === 0);
};
@action
start(): Promise<boolean | void> {
console.log('Starting batch');
if (this.status === 'queued') {
this.slotsAvailable = MAX_TRANSFERS;
this.status = 'started';
this.transferDef = new Deferred();
this.startDate = new Date();
this.queueNextTransfers();
}
// return this.transferDef.promise;
return this.transferDef.promise.then(this.onEndTransfer).catch((err: Error) => {
console.log('error transfer', err);
this.status = 'error';
return Promise.reject(err);
});
}
@action
updatePendingTransfers(subDir: string, newFilename: string, cancel = false): void {
// TODO: escape '(' & ')' in subDir if needed
const escapedSubDir = isWin ? subDir.replace(/\\/g, '\\\\') : subDir;
const regExp = new RegExp(`^(${escapedSubDir})`);
const elements = this.elements.filter((element) => element.subDirectory.match(regExp) !== null);
// destination directory for these files could not be created: we cancel these transfers
if (cancel) {
for (const el of elements) {
el.status = 'cancelled';
this.transfersDone++;
}
} else {
let newPrefix = '';
// need to rename
if (!subDir.match(new RegExp(newFilename + '$'))) {
const parts = subDir.split('/');
parts[parts.length - 1] = newFilename;
newPrefix = parts.join('/');
}
for (const transfer of elements) {
// enable files inside this directory
if (transfer.subDirectory === subDir) {
transfer.ready = true;
}
// for all files (ie. this directory & subdirectories)
// rename this part if needed
if (newPrefix) {
transfer.newSub = transfer.subDirectory.replace(regExp, newPrefix);
}
}
}
}
getNextTransfer(): FileTransfer {
return this.elements.find((el) => el.ready && el.status === 'queued');
}
/**
* Gets the next transfer(s) and starts them, where:
* num transfers = min(MAX_TRANSFERS, slotsAvailable)
*
*/
queueNextTransfers(): void {
const max = Math.min(MAX_TRANSFERS, this.slotsAvailable);
for (let i = 0; i < max; ++i) {
const transfer = this.getNextTransfer();
if (transfer) {
this.startTransfer(transfer);
}
}
}
@action
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onTransferError = (transfer: FileTransfer, err: any): void => {
// console.log('transfer error', transfer.file.fullname, err);
transfer.status = 'error';
transfer.error = getLocalizedError(err);
this.errors++;
// return this.transferDef.reject(err);
};
removeStream(stream: Readable): void {
const index = this.streams.findIndex((item) => item === stream);
if (index > -1) {
this.streams.splice(index, 1);
}
}
@action
/**
* Immediately initiates a file transfer, queues the next transfer when it's done
*/
async startTransfer(transfer: FileTransfer): Promise<void> {
this.slotsAvailable--;
transfer.status = 'started';
const dstFs = this.dstFs;
const srcFs = this.srcFs;
const fullDstPath = dstFs.join(this.dstPath, transfer.newSub);
const srcPath = srcFs.join(this.srcPath, transfer.subDirectory);
const wantedName = transfer.file.fullname;
const isDir = transfer.file.isDir;
const isSym = transfer.file.isSym;
let newFilename = '';
let stream = null;
try {
// if (transfer.file.isSym) {
// debugger;
// }
newFilename = await this.renameOrCreateDir(transfer, fullDstPath);
} catch (err) {
console.log('error creating directory', err);
this.onTransferError(transfer, err);
}
if (this.status === 'cancelled') {
console.warn('startTransfer while cancelled (1)');
}
if (!isDir) {
if (isSym) {
const linkPath = dstFs.join(fullDstPath, newFilename);
try {
await srcFs.makeSymlink(transfer.file.target, linkPath, this.id);
transfer.status = 'done';
} catch (err) {
this.onTransferError(transfer, err);
}
} else {
try {
// if (transfer.file.isSym) {
// debugger;
// }
// console.log('getting stream', srcPath, wantedName);
stream = await srcFs.getStream(srcPath, wantedName, this.id);
this.streams.push(stream);
// console.log('sending to stream', dstFs.join(fullDstPath, newFilename));
// we have to listen for errors that may appear during the transfer: socket closed, timeout,...
// and throw an error in this case because the putStream won't throw in this case:
// it will just stall
// stream.on('error', (err) => {
// console.log('error on read stream');
// this.onTransferError(transfer, err);
// // destroy stream so that put stream resolves ?
// stream.destroy();
// });
await dstFs.putStream(
stream,
dstFs.join(fullDstPath, newFilename),
(bytesRead: number) => {
this.onData(transfer, bytesRead);
},
this.id,
);
console.log('endPutStream', fullDstPath);
this.removeStream(stream);
transfer.status = 'done';
} catch (err) {
console.log('error with streams', err);
this.removeStream(stream);
// transfer.status = 'error';
// return Promise.reject(err);
// generate transfer error, but do not stop transfer unless errors > MAX_TRANSFER_ERRORS
// TODO: transfer.errors++
// if (transfer.errors > MAX) {
// set remaining transfers to cancel
// return ?
//}
this.onTransferError(transfer, err);
if (this.errors > MAX_ERRORS) {
console.warn('Maximum errors occurred: cancelling upcoming file transfers');
this.status = 'error';
this.cancelFiles();
}
}
}
} else {
// console.log('isDir', fullDstPath);
transfer.status = 'done';
// make transfers with this directory ready
this.updatePendingTransfers(
srcFs.join(transfer.subDirectory, wantedName),
newFilename,
(transfer as FileTransfer).status !== 'done',
);
}
if (this.status === 'cancelled') {
console.warn('startTransfer while cancelled (2)');
}
this.transfersDone++;
this.slotsAvailable++;
// console.log('finished', transfer.file.fullname, 'slotsAvailable', this.slotsAvailable, 'done', this.transfersDone);
if (this.status !== 'error' && this.transfersDone < this.elements.length) {
this.queueNextTransfers();
} else {
if (this.errors === this.elements.length) {
this.transferDef.reject({
code: '',
});
} else {
this.transferDef.resolve();
}
}
}
// TODO: do not infinite loop if directory cannot be created
// if not, reject and then we should set each file found inside
// that directory to error
async renameOrCreateDir(transfer: FileTransfer, dstPath: string): Promise<string> {
const isDir = transfer.file.isDir;
const dstFs = this.dstFs;
// create directory if does not exist
const wantedName = transfer.file.fullname;
const dirPath = dstFs.join(dstPath, wantedName);
let newName = wantedName;
let stats = null;
let exists = false;
try {
stats = await this.dstFs.stat(dirPath, this.id);
exists = true;
} catch (err) {
// TODO: handle permission denied and other errors ?
exists = false;
}
let i = 1;
// create directory if needed
if (isDir) {
// directory already exists: for now, simply use it
if (!exists) {
try {
await dstFs.makedir(dstPath, newName, this.id);
} catch (err) {
return Promise.reject(err);
}
} else if (!stats.isDir) {
// exists but is a file: attempt to create a directory with newName
let success = false;
while (!success && this.status !== 'cancelled') {
newName = wantedName + RENAME_SUFFIX + i++;
try {
await dstFs.makedir(dstPath, newName, this.id);
success = true;
} catch (err) {
return Promise.reject(err);
}
}
}
} else {
if (exists) {
newName = await this.getNewName(wantedName, dstPath);
}
}
return Promise.resolve(newName);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async getNewName(wantedName: string, path: string): Promise<string> {
let i = 1;
let exists = true;
let newName = wantedName;
// put suffix before the extension, so foo.txt will be renamed foo_1.txt to preserve the extension
// TODO: avoid endless loop, give up after max tries
while (exists) {
const range = getSelectionRange(wantedName);
const prefix = wantedName.startsWith('.') ? wantedName : wantedName.substring(range.start, range.end);
const suffix = wantedName.startsWith('.') ? '' : wantedName.substring(range.end);
newName = prefix + RENAME_SUFFIX + i++ + suffix;
const tmpPath = this.dstFs.join(this.dstPath, newName);
try {
exists = await this.dstFs.exists(tmpPath, this.id);
} catch (err) {
exists = false;
}
}
return Promise.resolve(newName);
}
@action
cancelFiles(): void {
const todo = this.elements.filter((el) => !!el.status.match(/queued/));
for (const el of todo) {
this.errors++;
el.status = 'cancelled';
}
}
@action
destroyRunningStreams(): void {
for (const stream of this.streams) {
stream.destroy();
}
}
@action
cancel(): void {
if (this.status !== 'done') {
this.status = 'cancelled';
this.cancelFiles();
this.destroyRunningStreams();
}
// otherwise there is nothing to do
}
@action
calcTotalSize(): void {
let size = 0;
for (const fileTransfer of this.elements) {
// directory's length is the space used for dir meta data: we don't need (nor copy) that
if (!fileTransfer.file.isDir) {
size += fileTransfer.file.length;
}
}
this.size = size;
}
getLastPathPart(path: string): string {
const parts = path.split('/');
const lastPart = parts[parts.length - 1];
// return `… / ${lastPart}`;
return lastPart;
}
async getFileList(srcFiles: File[], subDirectory = ''): Promise<FileTransfer[]> {
// console.log('getting file list');
const dirs = srcFiles.filter((file) => file.isDir);
const files = srcFiles.filter((file) => !file.isDir);
let transfers: FileTransfer[] = [];
// add files
for (const file of files) {
transfers.push({
file,
status: 'queued',
progress: 0,
subDirectory,
newSub: subDirectory,
ready: subDirectory === '',
});
}
// dir: need to call list for each directry to get files
for (const dir of dirs) {
const transfer: FileTransfer = {
file: dir,
status: 'queued',
progress: 0,
subDirectory,
newSub: subDirectory,
ready: subDirectory === '',
};
transfers.push(transfer);
// get directory listing
const currentPath = this.srcFs.join(dir.dir, dir.fullname);
// note: this is needed for FTP only: since Ftp.list(path) has to ignore the path
// and lists the contents of the CWD (which is changed by calling Ftp.cd())
let subFiles: File[] = null;
// /note
try {
await this.srcFs.cd(currentPath);
subFiles = await this.srcFs.list(currentPath);
const subDir = this.srcFs.join(subDirectory, dir.fullname);
transfers = transfers.concat(await this.getFileList(subFiles, subDir));
} catch (err) {
// TODO: set the transfer to error/skip
// then, simply skip it when doing the transfer
this.onTransferError(transfer, { code: 'ENOENT' });
this.transfersDone++;
console.log('could not get directory content for', currentPath);
console.log('directory was still added to transfer list for consistency');
}
}
return Promise.resolve(transfers);
}
@action
async setFileList(files: File[]): Promise<void> {
return this.getFileList(files)
.then((transfers) => {
console.log('got files', transfers);
// transfers.forEach(t => console.log(`[${t.status}] ${t.file.dir}/${t.file.fullname}:${t.file.isDir}, ${t.subDirectory} (${t.newSub})`))
this.elements.replace(transfers);
})
.catch((err) => {
return Promise.reject(err);
});
}
@action
onData(file: FileTransfer, bytesRead: number): void {
// console.log('dataThrottled', bytesRead);
const previousProgress = file.progress;
file.progress = bytesRead;
this.progress += previousProgress ? bytesRead - previousProgress : bytesRead;
// console.log('progress', this.progress, this.progress === this.size ? -1 : this.progress/this.size);
// remote.getCurrentWindow().setProgressBar(this.progress === this.size ? -1 : this.progress / this.size);
}
} | the_stack |
import { dsvFormat as d3dsvFormat } from 'd3-dsv';
import { GET_CHROM_SIZES } from '../../core/utils/assembly';
import { sampleSize } from 'lodash-es';
import { Assembly, FilterTransform } from '../../core/gosling.schema';
import { filterData } from '../../core/utils/data-transform';
/**
* HiGlass data fetcher specific for Gosling which ultimately will accept any types of data other than CSV files.
*/
function CSVDataFetcher(HGC: any, ...args: any): any {
if (!new.target) {
throw new Error('Uncaught TypeError: Class constructor cannot be invoked without "new"');
}
class CSVDataFetcherClass {
// @ts-ignore
private dataConfig: GeminiDataConfig;
// @ts-ignore
private tilesetInfoLoading: boolean;
private dataPromise: Promise<any> | undefined;
private chromSizes: any;
private values: any;
private assembly: Assembly;
private filter: FilterTransform[] | undefined;
constructor(params: any[]) {
const [dataConfig] = params;
this.dataConfig = dataConfig;
this.tilesetInfoLoading = false;
this.assembly = this.dataConfig.assembly;
this.filter = this.dataConfig.filter;
if (!dataConfig.url) {
console.error('Please provide the `url` of the data');
return;
}
// Prepare chromosome interval information
const chromosomeSizes: { [k: string]: number } = GET_CHROM_SIZES(this.assembly).size;
const chromosomeCumPositions: { id: number; chr: string; pos: number }[] = [];
const chromosomePositions: { [k: string]: { id: number; chr: string; pos: number } } = {};
let prevEndPosition = 0;
Object.keys(GET_CHROM_SIZES(this.assembly).size).forEach((chrStr, i) => {
const positionInfo = {
id: i,
chr: chrStr,
pos: prevEndPosition
};
chromosomeCumPositions.push(positionInfo);
chromosomePositions[chrStr] = positionInfo;
prevEndPosition += GET_CHROM_SIZES(this.assembly).size[chrStr];
});
this.chromSizes = {
chrToAbs: (chrom: string, chromPos: number) => this.chromSizes.chrPositions[chrom].pos + chromPos,
cumPositions: chromosomeCumPositions,
chrPositions: chromosomePositions,
totalLength: prevEndPosition,
chromLengths: chromosomeSizes
};
if (dataConfig.data) {
// we have raw data that we can use right away
this.values = dataConfig.data;
} else {
this.dataPromise = this.fetchCSV();
}
}
fetchCSV() {
const {
url,
chromosomeField,
genomicFields,
quantitativeFields,
headerNames,
chromosomePrefix,
longToWideId,
genomicFieldsToConvert
} = this.dataConfig;
const separator = this.dataConfig.separator ?? ',';
return fetch(url)
.then(response => {
return response.ok ? response.text() : Promise.reject(response.status);
})
.then(text => {
const textWithHeader = headerNames ? `${headerNames.join(separator)}\n${text}` : text;
return d3dsvFormat(separator).parse(textWithHeader, (row: any) => {
let successfullyGotChrInfo = true;
// !!! Experimental
if (genomicFieldsToConvert) {
// This spec is used when multiple chromosomes are stored in a single row
genomicFieldsToConvert.forEach((d: any) => {
const cField = d.chromosomeField;
d.genomicFields.forEach((g: string) => {
try {
if (this.assembly !== 'unknown') {
// This means we need to use the relative position considering the start position of individual chr.
const chr = chromosomePrefix
? row[cField].replace(chromosomePrefix, 'chr')
: row[cField].includes('chr')
? row[cField]
: `chr${row[cField]}`;
row[g] = GET_CHROM_SIZES(this.assembly).interval[chr][0] + +row[g];
} else {
// In this case, we use the genomic position as it is w/o adding the cumulative length of chr.
// So, nothing to do additionally.
}
} catch (e) {
// genomic position did not parse properly
successfullyGotChrInfo = false;
}
});
});
} else {
genomicFields.forEach((g: string) => {
if (!row[chromosomeField]) {
// TODO:
return;
}
try {
const chr = chromosomePrefix
? row[chromosomeField].replace(chromosomePrefix, 'chr')
: row[chromosomeField].includes('chr')
? row[chromosomeField]
: `chr${row[chromosomeField]}`;
row[g] = GET_CHROM_SIZES(this.assembly).interval[chr][0] + +row[g];
} catch (e) {
// genomic position did not parse properly
successfullyGotChrInfo = false;
}
});
}
if (!successfullyGotChrInfo) {
// store row only when chromosome information is correctly parsed
return undefined;
}
quantitativeFields?.forEach((q: string) => {
row[q] = +row[q];
});
return row;
});
})
.then(json => {
if (longToWideId && json[0]?.[longToWideId]) {
// rows having identical IDs are juxtaposed horizontally
const keys = Object.keys(json[0]);
const newJson: { [k: string]: { [k: string]: string | number } } = {};
json.forEach(d => {
if (!newJson[d[longToWideId]]) {
newJson[d[longToWideId]] = JSON.parse(JSON.stringify(d));
} else {
keys.forEach(k => {
newJson[d[longToWideId]][`${k}_2`] = d[k];
});
}
});
this.values = Object.keys(newJson).map(k => newJson[k]);
} else {
this.values = json;
}
})
.catch(error => {
console.error('[Gosling Data Fetcher] Error fetching data', error);
});
}
generateTilesetInfo(callback?: any) {
this.tilesetInfoLoading = false;
const TILE_SIZE = 1024;
const totalLength = this.chromSizes.totalLength;
const retVal = {
tile_size: TILE_SIZE,
max_zoom: Math.ceil(Math.log(totalLength / TILE_SIZE) / Math.log(2)),
max_width: totalLength,
min_pos: [0, 0],
max_pos: [totalLength, totalLength]
};
if (callback) {
callback(retVal);
}
return retVal;
}
tilesetInfo(callback?: any) {
if (!this.dataPromise) {
// data promise is not prepared yet
return;
}
this.tilesetInfoLoading = true;
return this.dataPromise
.then(() => this.generateTilesetInfo(callback))
.catch(err => {
this.tilesetInfoLoading = false;
console.error('[Gosling Data Fetcher] Error parsing data:', err);
});
}
fetchTilesDebounced(receivedTiles: any, tileIds: any) {
const tiles: { [k: string]: any } = {};
const validTileIds: any[] = [];
const tilePromises = [];
for (const tileId of tileIds) {
const parts = tileId.split('.');
const z = parseInt(parts[0], 10);
const x = parseInt(parts[1], 10);
const y = parseInt(parts[2], 10);
if (Number.isNaN(x) || Number.isNaN(z)) {
console.warn('[Gosling Data Fetcher] Invalid tile zoom or position:', z, x, y);
continue;
}
validTileIds.push(tileId);
tilePromises.push(this.tile(z, x, y));
}
Promise.all(tilePromises).then(values => {
values.forEach((value, i) => {
const validTileId = validTileIds[i];
tiles[validTileId] = value;
tiles[validTileId].tilePositionId = validTileId;
});
receivedTiles(tiles);
});
return tiles;
}
tile(z: any, x: any, y: any) {
return this.tilesetInfo()?.then((tsInfo: any) => {
const tileWidth = +tsInfo.max_width / 2 ** +z;
// get the bounds of the tile
const minX = tsInfo.min_pos[0] + x * tileWidth;
const maxX = tsInfo.min_pos[0] + (x + 1) * tileWidth;
// filter the data so that only the visible data is sent to tracks
let tabularData = this.values.filter((d: any) => {
if (this.dataConfig.genomicFields) {
return this.dataConfig.genomicFields.find((g: any) => minX < d[g] && d[g] <= maxX);
} else {
const allGenomicFields: string[] = [];
this.dataConfig.genomicFieldsToConvert.forEach((d: any) =>
allGenomicFields.push(...d.genomicFields)
);
return allGenomicFields.find((g: any) => minX < d[g] && d[g] <= maxX);
}
});
// filter data based on the `DataTransform` spec
this.filter?.forEach(f => {
tabularData = filterData(f, tabularData);
});
const sizeLimit = this.dataConfig.sampleLength ?? 1000;
return {
// sample the data to make it managable for visualization components
tabularData: tabularData.length > sizeLimit ? sampleSize(tabularData, sizeLimit) : tabularData,
server: null,
tilePos: [x, y],
zoomLevel: z
};
});
}
}
return new CSVDataFetcherClass(args);
}
CSVDataFetcher.config = {
type: 'csv'
};
export default CSVDataFetcher; | the_stack |
import {GridOptions} from "../entities/gridOptions";
import {GridApi} from "../gridApi";
import {Events} from "../events";
import {Utils as _} from "../utils";
import {ColumnApi} from "../columnController/columnController";
export class ComponentUtil {
// all the events are populated in here AFTER this class (at the bottom of the file).
public static EVENTS: string[] = [];
// function below fills this with onXXX methods, based on the above events
private static EVENT_CALLBACKS: string[];
public static STRING_PROPERTIES = [
'sortingOrder', 'rowClass', 'rowSelection', 'overlayLoadingTemplate',
'overlayNoRowsTemplate', 'headerCellTemplate', 'quickFilterText', 'rowModelType',
'editType'];
public static OBJECT_PROPERTIES = [
'rowStyle','context','groupColumnDef','localeText','icons','datasource','viewportDatasource',
'groupRowRendererParams', 'aggFuncs', 'fullWidthCellRendererParams','defaultColGroupDef','defaultColDef'
//,'cellRenderers','cellEditors'
];
public static ARRAY_PROPERTIES = [
'slaveGrids','rowData','floatingTopRowData','floatingBottomRowData','columnDefs'
];
public static NUMBER_PROPERTIES = [
'rowHeight','rowBuffer','colWidth','headerHeight','groupDefaultExpanded',
'minColWidth','maxColWidth','viewportRowModelPageSize','viewportRowModelBufferSize',
'layoutInterval','autoSizePadding','maxPagesInCache','maxConcurrentDatasourceRequests',
'paginationOverflowSize','paginationPageSize','paginationInitialRowCount'
];
public static BOOLEAN_PROPERTIES = [
'toolPanelSuppressRowGroups','toolPanelSuppressValues','toolPanelSuppressPivots', 'toolPanelSuppressPivotMode',
'suppressRowClickSelection','suppressCellSelection','suppressHorizontalScroll','debug',
'enableColResize','enableCellExpressions','enableSorting','enableServerSideSorting',
'enableFilter','enableServerSideFilter','angularCompileRows','angularCompileFilters',
'angularCompileHeaders','groupSuppressAutoColumn','groupSelectsChildren',
'groupIncludeFooter','groupUseEntireRow','groupSuppressRow','groupSuppressBlankHeader','forPrint',
'suppressMenuHide','rowDeselection','unSortIcon','suppressMultiSort','suppressScrollLag',
'singleClickEdit','suppressLoadingOverlay','suppressNoRowsOverlay','suppressAutoSize',
'suppressParentsInRowNodes','showToolPanel','suppressColumnMoveAnimation','suppressMovableColumns',
'suppressFieldDotNotation','enableRangeSelection','suppressEnterprise','rowGroupPanelShow',
'pivotPanelShow',
'suppressContextMenu','suppressMenuFilterPanel','suppressMenuMainPanel','suppressMenuColumnPanel',
'enableStatusBar','rememberGroupStateWhenNewData', 'enableCellChangeFlash', 'suppressDragLeaveHidesColumns',
'suppressMiddleClickScrolls','suppressPreventDefaultOnMouseWheel', 'suppressUseColIdForGroups',
'suppressCopyRowsToClipboard','pivotMode', 'suppressAggFuncInHeader', 'suppressColumnVirtualisation',
'suppressFocusAfterRefresh', 'functionsPassive', 'functionsReadOnly'
];
public static FUNCTION_PROPERTIES = ['headerCellRenderer', 'localeTextFunc', 'groupRowInnerRenderer',
'groupRowRenderer', 'isScrollLag', 'isExternalFilterPresent', 'getRowHeight',
'doesExternalFilterPass', 'getRowClass','getRowStyle', 'getHeaderCellTemplate', 'traverseNode',
'getContextMenuItems', 'getMainMenuItems', 'processRowPostCreate', 'processCellForClipboard',
'getNodeChildDetails', 'groupRowAggNodes', 'getRowNodeId', 'isFullWidthCell', 'fullWidthCellRenderer',
'doesDataFlower', 'processSecondaryColDef','processSecondaryColGroupDef'];
public static ALL_PROPERTIES = ComponentUtil.ARRAY_PROPERTIES
.concat(ComponentUtil.OBJECT_PROPERTIES)
.concat(ComponentUtil.STRING_PROPERTIES)
.concat(ComponentUtil.NUMBER_PROPERTIES)
.concat(ComponentUtil.FUNCTION_PROPERTIES)
.concat(ComponentUtil.BOOLEAN_PROPERTIES);
public static getEventCallbacks(): string[] {
if (!ComponentUtil.EVENT_CALLBACKS) {
ComponentUtil.EVENT_CALLBACKS = [];
ComponentUtil.EVENTS.forEach( (eventName: string)=> {
ComponentUtil.EVENT_CALLBACKS.push(ComponentUtil.getCallbackForEvent(eventName));
});
}
return ComponentUtil.EVENT_CALLBACKS;
}
public static copyAttributesToGridOptions(gridOptions: GridOptions, component: any): GridOptions {
checkForDeprecated(component);
// create empty grid options if none were passed
if (typeof gridOptions !== 'object') {
gridOptions = <GridOptions> {};
}
// to allow array style lookup in TypeScript, take type away from 'this' and 'gridOptions'
var pGridOptions = <any>gridOptions;
// add in all the simple properties
ComponentUtil.ARRAY_PROPERTIES
.concat(ComponentUtil.STRING_PROPERTIES)
.concat(ComponentUtil.OBJECT_PROPERTIES)
.concat(ComponentUtil.FUNCTION_PROPERTIES)
.forEach( (key)=> {
if (typeof (component)[key] !== 'undefined') {
pGridOptions[key] = component[key];
}
});
ComponentUtil.BOOLEAN_PROPERTIES.forEach( (key)=> {
if (typeof (component)[key] !== 'undefined') {
pGridOptions[key] = ComponentUtil.toBoolean(component[key]);
}
});
ComponentUtil.NUMBER_PROPERTIES.forEach( (key)=> {
if (typeof (component)[key] !== 'undefined') {
pGridOptions[key] = ComponentUtil.toNumber(component[key]);
}
});
ComponentUtil.getEventCallbacks().forEach( (funcName) => {
if (typeof (component)[funcName] !== 'undefined') {
pGridOptions[funcName] = component[funcName];
}
});
return gridOptions;
}
public static getCallbackForEvent(eventName: string): string {
if (!eventName || eventName.length < 2) {
return eventName;
} else {
return 'on' + eventName[0].toUpperCase() + eventName.substr(1);
}
}
// change this method, the caller should know if it's initialised or not, plus 'initialised'
// is not relevant for all component types. maybe pass in the api and columnApi instead???
public static processOnChange(changes: any, gridOptions: GridOptions, api: GridApi, columnApi: ColumnApi): void {
//if (!component._initialised || !changes) { return; }
if (!changes) { return; }
checkForDeprecated(changes);
// to allow array style lookup in TypeScript, take type away from 'this' and 'gridOptions'
var pGridOptions = <any> gridOptions;
// check if any change for the simple types, and if so, then just copy in the new value
ComponentUtil.ARRAY_PROPERTIES
.concat(ComponentUtil.OBJECT_PROPERTIES)
.concat(ComponentUtil.STRING_PROPERTIES)
.forEach( (key)=> {
if (changes[key]) {
pGridOptions[key] = changes[key].currentValue;
}
});
ComponentUtil.BOOLEAN_PROPERTIES.forEach( (key)=> {
if (changes[key]) {
pGridOptions[key] = ComponentUtil.toBoolean(changes[key].currentValue);
}
});
ComponentUtil.NUMBER_PROPERTIES.forEach( (key)=> {
if (changes[key]) {
pGridOptions[key] = ComponentUtil.toNumber(changes[key].currentValue);
}
});
ComponentUtil.getEventCallbacks().forEach( (funcName)=> {
if (changes[funcName]) {
pGridOptions[funcName] = changes[funcName].currentValue;
}
});
if (changes.showToolPanel) {
api.showToolPanel(ComponentUtil.toBoolean(changes.showToolPanel.currentValue));
}
if (changes.quickFilterText) {
api.setQuickFilter(changes.quickFilterText.currentValue);
}
if (changes.rowData) {
api.setRowData(changes.rowData.currentValue);
}
if (changes.floatingTopRowData) {
api.setFloatingTopRowData(changes.floatingTopRowData.currentValue);
}
if (changes.floatingBottomRowData) {
api.setFloatingBottomRowData(changes.floatingBottomRowData.currentValue);
}
if (changes.columnDefs) {
api.setColumnDefs(changes.columnDefs.currentValue);
}
if (changes.datasource) {
api.setDatasource(changes.datasource.currentValue);
}
if (changes.headerHeight) {
api.setHeaderHeight(ComponentUtil.toNumber(changes.headerHeight.currentValue));
}
if (changes.pivotMode) {
columnApi.setPivotMode(ComponentUtil.toBoolean(changes.pivotMode.currentValue));
}
}
public static toBoolean(value: any): boolean {
if (typeof value === 'boolean') {
return value;
} else if (typeof value === 'string') {
// for boolean, compare to empty String to allow attributes appearing with
// not value to be treated as 'true'
return value.toUpperCase() === 'TRUE' || value=='';
} else {
return false;
}
}
public static toNumber(value: any): number {
if (typeof value === 'number') {
return value;
} else if (typeof value === 'string') {
return Number(value);
} else {
return undefined;
}
}
}
_.iterateObject(Events, function(key, value) {
ComponentUtil.EVENTS.push(value);
});
function checkForDeprecated(changes: any): void {
if (changes.ready || changes.onReady) {
console.warn('ag-grid: as of v3.3 ready event is now called gridReady, so the callback should be onGridReady');
}
if (changes.rowDeselected || changes.onRowDeselected) {
console.warn('ag-grid: as of v3.4 rowDeselected no longer exists. Please check the docs.');
}
} | the_stack |
import React, { useContext, useEffect, useState, useRef, forwardRef } from 'react';
// MATERIAL UI METHODS
import {
IconButton,
Modal,
Card,
CardHeader,
CardContent,
Button,
Typography
} from '@material-ui/core';
import { Theme, makeStyles } from '@material-ui/core/styles';
import { BaseCSSProperties } from '@material-ui/core/styles/withStyles';
// MATERIAL UI ICONS
import MoreVertIcon from '@material-ui/icons/MoreVert';
import AddCircleOutlineTwoToneIcon from '@material-ui/icons/AddCircleOutlineTwoTone';
import DeleteForeverOutlinedIcon from '@material-ui/icons/DeleteForeverOutlined';
import HighlightOffIcon from '@material-ui/icons/HighlightOff';
import ListIcon from '@material-ui/icons/List';
import SearchIcon from '@material-ui/icons/Search';
import DashboardIcon from '@material-ui/icons/Dashboard';
import NotificationsIcon from '@material-ui/icons/Notifications';
import Badge from '@material-ui/core/Badge';
import PersonIcon from '@material-ui/icons/Person';
import UpdateIcon from '@material-ui/icons/Update';
// MODALS
import AddModal from '../modals/AddModal';
import AddsModal from '../modals/AddsModal';
import ServicesModal from '../modals/ServicesModal';
// STYLESHEETS
// import '../stylesheets/Occupied.scss';
import '../stylesheets/Occupied.scss';
// DASHBOARD CONTEXT
import { DashboardContext } from '../context/DashboardContext';
import { ApplicationContext } from '../context/ApplicationContext';
import { CommsContext } from '../context/CommsContext';
// TYPESCRIPT
interface StyleProps {
root: BaseCSSProperties;
}
type ClickEvent = React.MouseEvent<HTMLElement>;
const Occupied = React.memo(() => {
const { setServicesData } = useContext(ApplicationContext);
const { applications, getApplications, deleteApp, mode, getMode } = useContext(DashboardContext);
const { commsData, setCommsData, fetchCommsData } = useContext(CommsContext);
const [open, setOpen] = useState<boolean>(false);
const [addOpen, setAddOpen] = useState<boolean>(false);
const [addsOpen, setAddsOpen] = useState<boolean>(false);
const [index, setIndex] = useState<number>(0);
const [app, setApp] = useState<string>('');
const [searchTerm, setSearchTerm] = useState<string>('');
const [clickedAt, setClickedAt] = useState<string>('2000-01-01T00:00:00Z'); // init at year 2000
// Dynamic refs
const delRef = useRef<any>([]);
useEffect(() => {
setServicesData([]);
getApplications();
}, []);
// Ask user for deletetion confirmation
const confirmDelete = (event: ClickEvent, app: string, i: number) => {
const message = `The application '${app}' will be permanently deleted. Continue?`;
if (confirm(message)) deleteApp(i);
};
// Handle clicks on Application cards
const handleClick = (event: ClickEvent, selectedApp: string, i: number) => {
if (delRef.current[i] && !delRef.current[i].contains(event.target)) {
setIndex(i);
setApp(selectedApp);
setServicesData([]);
setOpen(true);
}
};
//Conditional Rendering of UI Modals for Light and Dark Mode
const useStylesDark = makeStyles<Theme, StyleProps>(theme => ({
// ALL CARDS
paper: {
display: 'flex',
flexDirection: 'column',
alignContent: 'center',
alignItems: 'center',
position: 'relative',
overflow: 'visible',
height: 280,
width: 280,
textAlign: 'center',
color: '#888888',
whiteSpace: 'nowrap',
backgroundColor: 'lightgray', // dark mode
borderRadius: 3,
border: '0',
boxShadow: '0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19)', // dark mode
'&:hover, &.Mui-focusVisible': {
backgroundColor: 'rgba(255, 255, 255, 0.2)', // dark mode
color: '#ffffff',
fontWeight: 600,
},
},
iconbutton: {
boxShadow: 'none',
color: 'none',
visibility: 'hidden',
},
btnStyle: {
position: 'absolute',
top: -10,
left: -72,
margin: '0',
color: '#eeeeee',
borderRadius: '0',
backgroundColor: 'none',
visibility: 'visible',
},
icon: {
width: '75px',
height: '75px',
boxShadow: 'none',
},
// ALL CARDS: CONTENT
fontStyles: {
fontSize: '18px',
fontFamily: 'Roboto',
fontWeight: 300,
color: '#444d56',
// color: '#ffffff', // dark mode
}
}));
const useStylesLight = makeStyles<Theme, StyleProps>(theme => ({
// ALL CARDS
paper: {
display: 'flex',
flexDirection: 'column',
alignContent: 'center',
alignItems: 'center',
position: 'relative',
overflow: 'visible',
height: 280,
width: 280,
textAlign: 'center',
color: '#888888',
whiteSpace: 'nowrap',
backgroundColor: 'white',
borderRadius: 3,
border: '0',
boxShadow:
'0 6px 6px 0 rgba(153, 153, 153, 0.14), 0 6px 6px -2px rgba(153, 153, 153, 0.2), 0 6px 8px 0 rgba(153, 153, 153, 0.12)',
'&:hover, &.Mui-focusVisible': {
backgroundColor: `#3788fc`,
color: '#ffffff',
fontWeight: 600,
},
},
iconbutton: {
boxShadow: 'none',
color: 'none',
visibility: 'hidden',
},
btnStyle: {
position: 'absolute',
top: -10,
left: -72,
margin: '0',
color: '#eeeeee',
borderRadius: '0',
backgroundColor: 'none',
visibility: 'visible',
},
icon: {
width: '75px',
height: '75px',
boxShadow: 'none',
},
// ALL CARDS: CONTENT
fontStyles: {
fontSize: '18px',
fontFamily: 'Roboto',
fontWeight: 300,
color: '#444d56',
}
}));
let classes = (mode === 'light mode')? useStylesLight({} as StyleProps) : useStylesDark({} as StyleProps) ;
// update notification count based on statuscode >= 400
const notification = commsData.filter((item: { responsestatus: number; }) => item.responsestatus >= 400)
.filter((item: { time: string; }) => {
const d1 = new Date(item.time);
const d2 = new Date(clickedAt);
return d1 > d2;
});
const updateNotification = () => {
const timestamp = new Date();
setClickedAt(timestamp.toISOString())
}
return (
<div className="entireArea">
<div className="dashboardArea">
<header className="mainHeader">
<section className="header" id="leftHeader">
<span>
<ListIcon className="icon" id="listIcon" />
</span>
<span>
<p id="dashboard">Dashboard</p>
</span>
</section>
<section className="header" id="rightHeader">
<form className="form" onSubmit={e => e.preventDefault()}>
<label className="inputContainer">
<input className="form" id="textInput" placeholder={'Search...'} onChange={e => setSearchTerm(e.target.value)} type="text" name="search" />
<hr />
</label>
<button className="form" id="submitBtn" type="submit">
<SearchIcon className="icon" id="searchIcon" />
</button>
</form>
<div className="dashboardIconArea">
<span className="dashboardTooltip">You have {applications.length} active databases</span>
<DashboardIcon className="navIcon" id="dashboardIcon" />
</div>
<div className="notificationsIconArea" onClick={updateNotification}>
<span className="notificationsTooltip">You have {notification ? notification.length : 0} new alerts</span>
< NotificationsIcon className="navIcon" id="notificationsIcon" />
<Badge badgeContent={notification ? notification.length : 0} color="secondary"/>
</div>
<Button className= "personTooltip" onClick={() => setAddsOpen(true)}>Logged In
<PersonIcon className="navIcon" id="personIcon" />
</Button>
</section>
</header>
<div className="cardContainer">
<div className="card" id={`card-add`}>
<Button className={classes.paper} onClick={() => setAddOpen(true)}>
<AddCircleOutlineTwoToneIcon className={classes.icon} />
</Button>
</div>
{applications.filter((db: any) => db[0].toLowerCase().includes(searchTerm.toLowerCase()))
.map((app: string[], i: number | any | string | undefined) => (
<div className="card" key={`card-${i}`} id={`card-${app[1]}`}>
<Card
key={`card-${i}`}
className={classes.paper}
variant="outlined"
onClick={event => handleClick(event, app[0], i)}
>
<div className="databaseIconContainer">
<div className="databaseIconHeader">
{
app[1] === "SQL" ?
<img className="databaseIcon" alt="SQL"/> :
<img className="databaseIcon" alt="MongoDB"/>
}
</div>
</div>
<CardHeader
avatar={
<IconButton
id="iconButton"
ref={element => (delRef.current[i] = element)}
className={classes.iconbutton}
aria-label="Delete"
onClick={event => confirmDelete(event, app[0], i)}
>
<HighlightOffIcon
className={classes.btnStyle}
id="deleteIcon"
ref={element => (delRef.current[i] = element)}
/>
</IconButton>
}
>
</CardHeader>
<CardContent>
<p id="databaseName">Database Name:</p>
<Typography className={classes.fontStyles}>{app[0]}</Typography>
</CardContent>
<hr className="cardLine"/>
<div className="cardFooter">
<UpdateIcon className="cardFooterIcon"/>
<em><p id="cardFooterText">{app[3]}</p></em>
</div>
</Card>
</div>
))}
<Modal open={addOpen} onClose={() => setAddOpen(false)}>
<AddModal setOpen={setAddOpen} />
</Modal>
<Modal open={addsOpen} onClose={() => setAddsOpen(false)}>
<AddsModal setOpen={setAddsOpen} />
</Modal>
<Modal open={open} onClose={() => setOpen(false)}>
<ServicesModal key={`key-${index}`} i={index} app={app} />
</Modal>
</div>
</div>
</div>
);
});
export default Occupied; | the_stack |
import { fetch } from "../fetcher";
import {
File,
UploadRequestInit,
WithResourceInfo,
Url,
UrlString,
hasResourceInfo,
WithServerResourceInfo,
} from "../interfaces";
import { internal_toIriString } from "../interfaces.internal";
import { getSourceIri, FetchError } from "./resource";
import {
internal_cloneResource,
internal_isUnsuccessfulResponse,
internal_parseResourceInfo,
} from "./resource.internal";
/**
* Options when fetching a file from a Pod.
*
* Available options:
* - `fetch`: A custom `fetch` function with the same signature as
* [`window.fetch`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch).
* This will be used to execute the actual requests. This option can be used to, for example,
* attach credentials to requests that need authentication.
*/
export type GetFileOptions = {
fetch: typeof window.fetch;
/** @internal */
init: UploadRequestInit;
};
const defaultGetFileOptions = {
fetch: fetch,
};
const RESERVED_HEADERS = ["Slug", "If-None-Match", "Content-Type"];
/**
* Some of the headers must be set by the library, rather than directly.
*/
function containsReserved(header: Record<string, string>): boolean {
return RESERVED_HEADERS.some((reserved) => header[reserved] !== undefined);
}
/**
* ```{note} This function is still experimental and subject to change, even in a non-major release.
* ```
*
* Retrieves a file from a URL and returns the file as a blob.
*
* For example:
*
* ```
* const fileBlob = await getFile("https://pod.example.com/some/file", { fetch: fetch });
* ```
*
* For additional examples, see
* [Read/Write Files](https://docs.inrupt.com/developer-tools/javascript/client-libraries/tutorial/read-write-files/#retrieve-a-file).
*
* @param url The URL of the file to return
* @param options Fetching options: a custom fetcher and/or headers.
* @returns The file as a blob.
*/
export async function getFile(
input: Url | UrlString,
options: Partial<GetFileOptions> = defaultGetFileOptions
): Promise<File & WithServerResourceInfo> {
const config = {
...defaultGetFileOptions,
...options,
};
const url = internal_toIriString(input);
const response = await config.fetch(url, config.init);
if (internal_isUnsuccessfulResponse(response)) {
throw new FetchError(
`Fetching the File failed: [${response.status}] [${response.statusText}].`,
response
);
}
const resourceInfo = internal_parseResourceInfo(response);
const data = await response.blob();
const fileWithResourceInfo: File & WithServerResourceInfo = Object.assign(
data,
{
internal_resourceInfo: resourceInfo,
}
);
return fileWithResourceInfo;
}
/**
* ```{note} This function is still experimental and subject to change, even in a non-major release.
* ```
* Deletes a file at a given URL.
*
* For example:
*
* ```
* await deleteFile( "https://pod.example.com/some/file", { fetch: fetch });
* ```
*
* For additional examples, see
* [Read/Write Files](https://docs.inrupt.com/developer-tools/javascript/client-libraries/tutorial/read-write-files/#delete-a-file).
*
* @param file The URL of the file to delete
*/
export async function deleteFile(
file: Url | UrlString | WithResourceInfo,
options: Partial<GetFileOptions> = defaultGetFileOptions
): Promise<void> {
const config = {
...defaultGetFileOptions,
...options,
};
const url = hasResourceInfo(file)
? internal_toIriString(getSourceIri(file))
: internal_toIriString(file);
const response = await config.fetch(url, {
...config.init,
method: "DELETE",
});
if (internal_isUnsuccessfulResponse(response)) {
throw new FetchError(
`Deleting the file at [${url}] failed: [${response.status}] [${response.statusText}].`,
response
);
}
}
/**
* ```{note} This type is still experimental and subject to change, even in a
* non-major release.
* ```
* Options available when saving a file (extends the options available when
* writing a file: [[WriteFileOptions]]).
*
*/
type SaveFileOptions = WriteFileOptions & {
/**
* This option can be used as a hint to the server in how to name a new file.
* Note: the server is still free to choose a completely different, unrelated
* name if it chooses.
*/
slug?: string;
};
/**
* ```{note} This function is still experimental and subject to change, even in a non-major release.
* ```
*
* Saves a file in an existing folder/Container associated with the given URL.
*
* For example:
*
* ```
* const savedFile = await saveFileInContainer(
* "https://pod.example.com/some/existing/container/",
* new Blob(["This is a plain piece of text"], { type: "plain/text" }),
* { slug: "suggestedFileName.txt", contentType: "text/plain", fetch: fetch }
* );
* ```
*
* For additional example, see
* [Read/Write Files](https://docs.inrupt.com/developer-tools/javascript/client-libraries/tutorial/read-write-files/#save-a-file-into-an-existing-container).
*
* In the `options` parameter,
*
* - You can suggest a file name in the `slug` field. However, the Solid
* Server may or may not use the suggested `slug` as the file name.
*
* - *Recommended:* You can specify the [media type](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type)
* of the file in the `contentType`. If unspecified, the function uses the default type of
* `application/octet-stream`, indicating a binary data file.
*
* The function saves a file into an *existing* Container. If the
* Container does not exist, either:
* - Create the Container first using [[createContainerAt]], and then
* use the function, or
* - Use [[overwriteFile]] to save the file. [[overwriteFile]] creates
* the Containers in the saved file path as needed.
*
* Users who only have `Append` but not `Write` access to a Container
* can use [[saveFileInContainer]] to save new files to the Container.
* That is, [[saveFileInContainer]] is useful in situations where users
* can add new files to a Container but not change existing files in
* the Container, such as users given access to send notifications to
* another's Pod but not to view or delete existing notifications in that Pod.
*
* Users with `Write` access to the given folder/Container may prefer to
* use [[overwriteFile]].
*
* @param folderUrl The URL of an existing folder where the new file is saved.
* @param file The file to be written.
* @param options Additional parameters for file creation (e.g. a slug).
* @returns A Promise that resolves to the saved file, if available, or `null` if the current user does not have Read access to the newly-saved file. It rejects if saving fails.
*/
export async function saveFileInContainer<FileExt extends File | Buffer>(
folderUrl: Url | UrlString,
file: FileExt,
options: Partial<SaveFileOptions> = defaultGetFileOptions
): Promise<FileExt & WithResourceInfo> {
const folderUrlString = internal_toIriString(folderUrl);
const response = await writeFile(folderUrlString, file, "POST", options);
if (internal_isUnsuccessfulResponse(response)) {
throw new FetchError(
`Saving the file in [${folderUrl}] failed: [${response.status}] [${response.statusText}].`,
response
);
}
const locationHeader = response.headers.get("Location");
if (locationHeader === null) {
throw new Error(
"Could not determine the location of the newly saved file."
);
}
const fileIri = new URL(locationHeader, new URL(folderUrlString).origin).href;
const blobClone = internal_cloneResource(file);
const resourceInfo: WithResourceInfo = {
internal_resourceInfo: {
isRawData: true,
sourceIri: fileIri,
contentType: getContentType(file, options.contentType),
},
};
return Object.assign(blobClone, resourceInfo);
}
/**
* ```{note} This function is still experimental and subject to change, even in a non-major release.
* ```
*
* Options available when writing a file.
*/
export type WriteFileOptions = GetFileOptions & {
/**
* Allows a file's content type to be provided explicitly, if known. Value is
* expected to be a valid
* [media type](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type).
* For example, if you know your file is a JPEG image, then you should provide
* the media type `image/jpeg`. If you don't know, or don't provide a media
* type, a default type of `application/octet-stream` will be applied (which
* indicates that the file should be regarded as pure binary data).
*/
contentType: string;
};
/**
* ```{note} This function is still experimental and subject to change, even in a non-major release.
* ```
*
* Saves a file at a given URL. If a file already exists at the URL,
* the function overwrites the existing file.
*
* For example:
*
* ```
* const savedFile = await overwriteFile(
* "https://pod.example.com/some/container/myFile.txt",
* new Blob(["This is a plain piece of text"], { type: "plain/text" }),
* { contentType: "text/plain", fetch: fetch }
* );
* ```
*
* For additional example, see
* [Read/Write Files](https://docs.inrupt.com/developer-tools/javascript/client-libraries/tutorial/read-write-files/#write-a-file-to-a-specific-url).
*
* *Recommended:* In the `options` parameter, you can specify the
* [media type](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type)
* of the file in the `contentType`. If unspecified, the function uses the default type of
* `application/octet-stream`, indicating a binary data file.
*
* When saving a file with [[overwriteFile]], the Solid server creates any
* intermediary Containers as needed; i.e., the Containers do not
* need to be created in advance. For example, when saving a file to the target URL of
* https://example.pod/container/resource, if https://example.pod/container/ does not exist,
* the container is created as part of the save.
*
* @param fileUrl The URL where the file is saved.
* @param file The file to be written.
* @param options Additional parameters for file creation (e.g., media type).
*/
export async function overwriteFile<FileExt extends File | Buffer>(
fileUrl: Url | UrlString,
file: FileExt,
options: Partial<WriteFileOptions> = defaultGetFileOptions
): Promise<FileExt & WithResourceInfo> {
const fileUrlString = internal_toIriString(fileUrl);
const response = await writeFile(fileUrlString, file, "PUT", options);
if (internal_isUnsuccessfulResponse(response)) {
throw new FetchError(
`Overwriting the file at [${fileUrlString}] failed: [${response.status}] [${response.statusText}].`,
response
);
}
const blobClone = internal_cloneResource(file);
const resourceInfo = internal_parseResourceInfo(response);
resourceInfo.sourceIri = fileUrlString;
resourceInfo.isRawData = true;
return Object.assign(blobClone, { internal_resourceInfo: resourceInfo });
}
function isHeadersArray(
headers: Headers | Record<string, string> | string[][]
): headers is string[][] {
return Array.isArray(headers);
}
/**
* The return type of this function is misleading: it should ONLY be used to check
* whether an object has a forEach method that returns <key, value> pairs.
*
* @param headers A headers object that might have a forEach
*/
function hasHeadersObjectForEach(
headers: Headers | Record<string, string> | string[][]
): headers is Headers {
return typeof (headers as Headers).forEach === "function";
}
/**
* @hidden
* This function feels unnecessarily complicated, but is required in order to
* have Headers according to type definitions in both Node and browser environments.
* This might require a fix upstream to be cleaned up.
*
* @param headersToFlatten A structure containing headers potentially in several formats
*/
export function flattenHeaders(
headersToFlatten: Headers | Record<string, string> | string[][] | undefined
): Record<string, string> {
if (typeof headersToFlatten === "undefined") {
return {};
}
let flatHeaders: Record<string, string> = {};
if (isHeadersArray(headersToFlatten)) {
headersToFlatten.forEach(([key, value]) => {
flatHeaders[key] = value;
});
// Note that the following line must be a elsif, because string[][] has a forEach,
// but it returns string[] instead of <key, value>
} else if (hasHeadersObjectForEach(headersToFlatten)) {
headersToFlatten.forEach((value: string, key: string) => {
flatHeaders[key] = value;
});
} else {
// If the headers are already a Record<string, string>,
// they can directly be returned.
flatHeaders = headersToFlatten;
}
return flatHeaders;
}
/**
* Internal function that performs the actual write HTTP query, either POST
* or PUT depending on the use case.
*
* @param fileUrl The URL where the file is saved
* @param file The file to be written
* @param method The HTTP method
* @param options Additional parameters for file creation (e.g. a slug, or media type)
*/
async function writeFile(
targetUrl: UrlString,
file: File | Buffer,
method: "PUT" | "POST",
options: Partial<SaveFileOptions>
): Promise<Response> {
const config = {
...defaultGetFileOptions,
...options,
};
const headers = flattenHeaders(config.init?.headers ?? {});
if (containsReserved(headers)) {
throw new Error(
`No reserved header (${RESERVED_HEADERS.join(
", "
)}) should be set in the optional RequestInit.`
);
}
// If a slug is in the parameters, set the request headers accordingly
if (config.slug !== undefined) {
headers["Slug"] = config.slug;
}
headers["Content-Type"] = getContentType(file, options.contentType);
const targetUrlString = internal_toIriString(targetUrl);
return await config.fetch(targetUrlString, {
...config.init,
headers,
method,
body: file,
});
}
function getContentType(
file: File | Buffer,
contentTypeOverride?: string
): string {
if (typeof contentTypeOverride === "string") {
return contentTypeOverride;
}
const fileType =
typeof file === "object" &&
file !== null &&
typeof (file as Blob).type === "string" &&
(file as Blob).type.length > 0
? (file as Blob).type
: undefined;
return fileType ?? "application/octet-stream";
} | the_stack |
* @module iModelHubClient
*/
import { AccessToken, GuidString, Id64, Id64String, Logger } from "@itwin/core-bentley";
import { request, Response } from "../itwin-client/Request";
import { ECJsonTypeMap, WsgInstance } from "../wsg/ECJsonTypeMap";
import { IModelHubClientLoggerCategory } from "../IModelHubClientLoggerCategories";
import { IModelBaseHandler } from "./BaseHandler";
import { CodeState } from "./Codes";
import { ArgumentCheck } from "./Errors";
import {
BaseEventSAS, EventBaseHandler, EventListener, GetEventOperationToRequestType, IModelHubBaseEvent, ListenerSubscription,
} from "./EventsBase";
import { LockLevel, LockType } from "./Locks";
/* eslint-disable @typescript-eslint/no-shadow */
const loggerCategory: string = IModelHubClientLoggerCategory.IModelHub;
/** Type of [[IModelHubEvent]]. Event type is used to define which events you wish to receive from your [[EventSubscription]]. See [[EventSubscriptionHandler.create]] and [[EventSubscriptionHandler.update]].
* @public
*/
export enum IModelHubEventType {
/** Sent when one or more [[Lock]]s are updated. See [[LockEvent]].
* @internal
*/
LockEvent = "LockEvent",
/** Sent when all [[Lock]]s for a [[Briefcase]] are deleted. See [[AllLocksDeletedEvent]].
* @internal
*/
AllLocksDeletedEvent = "AllLocksDeletedEvent",
/** Sent when a [[ChangeSet]] is successfully pushed. See [[ChangeSetPostPushEvent]]. */
ChangeSetPostPushEvent = "ChangeSetPostPushEvent",
/** Sent when a [[ChangeSet]] push has started. See [[ChangeSetPrePushEvent]]. */
ChangeSetPrePushEvent = "ChangeSetPrePushEvent",
/** Sent when one or more [Code]($common)s are updated. See [[CodeEvent]].
* @internal
*/
CodeEvent = "CodeEvent",
/** Sent when all [Code]($common)s for a [[Briefcase]] are deleted. See [[AllCodesDeletedEvent]].
* @internal
*/
AllCodesDeletedEvent = "AllCodesDeletedEvent",
/** Sent when a [[Briefcase]] is deleted. See [[BriefcaseDeletedEvent]].
* @internal
*/
BriefcaseDeletedEvent = "BriefcaseDeletedEvent",
/** Sent when an iModel is deleted. See [[iModelDeletedEvent]]. */
iModelDeletedEvent = "iModelDeletedEvent",
/** Sent when a new named [[Version]] is created. See [[VersionEvent]]. */
VersionEvent = "VersionEvent",
/**
* Sent when a new [[Checkpoint]] is generated. See [[CheckpointCreatedEvent]].
* @internal
*/
CheckpointCreatedEvent = "CheckpointCreatedEvent",
/**
* Sent when a new [[CheckpointV2]] is generated. See [[CheckpointV2CreatedEvent]].
* @internal
*/
CheckpointV2CreatedEvent = "CheckpointV2CreatedEvent",
}
/* eslint-enable @typescript-eslint/no-shadow */
/** @internal @deprecated Use [[IModelHubEventType]] instead */
export type EventType = "LockEvent" | "AllLocksDeletedEvent" | "ChangeSetPostPushEvent" | "ChangeSetPrePushEvent" | "CodeEvent" | "AllCodesDeletedEvent" | "BriefcaseDeletedEvent" | "iModelDeletedEvent" | "VersionEvent" | "CheckpointCreatedEvent" | "CheckpointV2CreatedEvent";
/** Base type for all iModelHub events.
* @public
*/
export abstract class IModelHubEvent extends IModelHubBaseEvent {
/** Id of the iModel where the event occurred. */
public iModelId?: GuidString;
/** Construct this event from object instance.
* @param obj Object instance.
* @internal
*/
public override fromJson(obj: any) {
super.fromJson(obj);
this.iModelId = this.eventTopic;
}
}
/** Base type for iModelHub events that have BriefcaseId.
* @public
*/
export abstract class BriefcaseEvent extends IModelHubEvent {
/** Id of the [[Briefcase]] involved in this event. */
public briefcaseId: number;
/** Construct this event from object instance.
* @param obj Object instance.
* @internal
*/
public override fromJson(obj: any) {
super.fromJson(obj);
this.briefcaseId = obj.BriefcaseId;
}
}
/** Sent when one or more [[Lock]]s are updated. Lock updates can be very frequent, so it's recommended to not to subscribe to LockEvents, if it's not necessary.
* @internal
*/
export class LockEvent extends BriefcaseEvent {
/** [[LockType]] of the updated Locks. */
public lockType: LockType;
/** [[LockLevel]] of the updated Locks. */
public lockLevel: LockLevel;
/** Id's of the updated Locks. */
public objectIds: Id64String[];
/** Id of the [[ChangeSet]] Locks were released with. */
public releasedWithChangeSet?: string;
/** Construct this event from object instance.
* @param obj Object instance.
* @internal
*/
public override fromJson(obj: any) {
super.fromJson(obj);
this.lockType = LockType[obj.LockType as keyof typeof LockType];
this.lockLevel = LockLevel[obj.LockLevel as keyof typeof LockLevel];
this.objectIds = (obj.ObjectIds as string[]).map((value: string) => Id64.fromJSON(value));
this.releasedWithChangeSet = obj.ReleasedWithChangeSet;
}
}
/** Sent when all [[Lock]]s for a [[Briefcase]] are deleted. Can occur when calling [[LockHandler.deleteAll]] or [[BriefcaseHandler.delete]].
* @internal
*/
export class AllLocksDeletedEvent extends BriefcaseEvent {
}
/** Sent when a [[ChangeSet]] is successfully pushed. See [[ChangeSetHandler.create]]. It's sent when a new [[ChangeSet]] is successfully pushed to an iModel. See [[ChangeSetPrePushEvent]] for the event indicating the start of a ChangeSet push.
* @public
*/
export class ChangeSetPostPushEvent extends BriefcaseEvent {
/** Id of the ChangeSet that was pushed. */
public changeSetId: string;
/** Index of the ChangeSet that was pushed. */
public changeSetIndex: string;
/** Construct this event from object instance.
* @param obj Object instance.
* @internal
*/
public override fromJson(obj: any) {
super.fromJson(obj);
this.changeSetId = obj.ChangeSetId;
this.changeSetIndex = obj.ChangeSetIndex;
}
}
/** Sent when a [[ChangeSet]] push has started. See [[ChangeSetHandler.create]]. ChangeSetPrePushEvent indicates that iModelHub allowed one of the [[Briefcase]]s to push a ChangeSet and all other push attempts will fail, until this push times out or succeeds. See [[ChangeSetPostPushEvent]] for an event indicating a successful push.
* @public
*/
export class ChangeSetPrePushEvent extends IModelHubEvent {
}
/** Sent when one or more [Code]($common)s are updated. See [[CodeHandler.update]]. Code updates can be very frequent, so it's recommended to not to subscribe to CodeEvents, if it's not necessary.
* @internal
*/
export class CodeEvent extends BriefcaseEvent {
/** Id of the [CodeSpec]($common) for the updated Codes. */
public codeSpecId: Id64String;
/** Scope of the updated Codes. */
public codeScope: string;
/** Array of the updated Code values. */
public values: string[];
/** State Codes were updated to. */
public state: CodeState = CodeState.Reserved;
/** Construct this event from object instance.
* @param obj Object instance.
* @internal
*/
public override fromJson(obj: any) {
super.fromJson(obj);
this.codeSpecId = Id64.fromJSON(obj.CodeSpecId);
this.codeScope = obj.CodeScope;
this.values = obj.Values;
this.state = obj.State;
}
}
/** Sent when all [Code]($common)s for a [[Briefcase]] are deleted. Can occur when calling [[CodeHandler.deleteAll]] or [[BriefcaseHandler.delete]].
* @internal
*/
export class AllCodesDeletedEvent extends BriefcaseEvent {
}
/** Sent when a [[Briefcase]] is deleted. See [[BriefcaseHandler.delete]].
* @internal
*/
export class BriefcaseDeletedEvent extends BriefcaseEvent {
}
/** Sent when an iModel is deleted. See [[IModelHandler.delete]]. [[EventSubscription]] will be deleted 5 minutes after iModel is deleted, removing all events from subscription queues, making it possible for this event to be missed if not retrieved immediately.
* @public
*/
export class IModelDeletedEvent extends IModelHubEvent {
}
/** Sent when a new named [[Version]] is created. See [[VersionHandler.create]].
* @public
*/
export class VersionEvent extends IModelHubEvent {
/** Id of the created Version. */
public versionId: GuidString;
/** Name of the created Version. */
public versionName: string;
/** Id of the [[ChangeSet]] that this Version was created for. */
public changeSetId: string;
/** Construct this event from object instance.
* @param obj Object instance.
* @internal
*/
public override fromJson(obj: any) {
super.fromJson(obj);
this.versionId = obj.VersionId;
this.versionName = obj.VersionName;
this.changeSetId = obj.ChangeSetId;
}
}
/** Sent when a new [[Checkpoint]] is generated. [[Checkpoint]]s can be generated daily when there are new [[ChangeSet]]s pushed or when a new [[Version]] is created.
* @internal
*/
export class CheckpointCreatedEvent extends IModelHubEvent {
/** Index of the [[ChangeSet]] this [[Checkpoint]] was created for. */
public changeSetIndex: string;
/** Id of the [[ChangeSet]] this [[Checkpoint]] was created for. */
public changeSetId: string;
/** Id of the [[Version]] this [[Checkpoint]] was created for. */
public versionId?: GuidString;
/** Construct this event from object instance.
* @param obj Object instance.
* @internal
*/
public override fromJson(obj: any) {
super.fromJson(obj);
this.changeSetIndex = obj.ChangeSetIndex;
this.changeSetId = obj.ChangeSetId;
this.versionId = obj.VersionId;
}
}
/** Sent when a new [[CheckpointV2]] is generated. [[CheckpointV2]] might be created for every [[ChangeSet]].
* @internal
*/
export class CheckpointV2CreatedEvent extends IModelHubEvent {
/** Index of the [[ChangeSet]] this [[CheckpointV2]] was created for. */
public changeSetIndex: string;
/** Id of the [[ChangeSet]] this [[CheckpointV2]] was created for. */
public changeSetId: string;
/** Id of the [[Version]] this [[CheckpointV2]] was created for. */
public versionId?: GuidString;
/** Construct this event from object instance.
* @param obj Object instance.
* @internal
*/
public override fromJson(obj: any) {
super.fromJson(obj);
this.changeSetIndex = obj.ChangeSetIndex;
this.changeSetId = obj.ChangeSetId;
this.versionId = obj.VersionId;
}
}
/** Get EventConstructor which can be used to construct IModelHubEvent
* @internal
*/
type EventConstructor = (new () => IModelHubEvent);
/** Get constructor from EventType name.
* @internal
*/
export function constructorFromEventType(type: IModelHubEventType): EventConstructor {
switch (type) {
case IModelHubEventType.LockEvent:
return LockEvent;
case IModelHubEventType.AllLocksDeletedEvent:
return AllLocksDeletedEvent;
case IModelHubEventType.ChangeSetPostPushEvent:
return ChangeSetPostPushEvent;
case IModelHubEventType.ChangeSetPrePushEvent:
return ChangeSetPrePushEvent;
case IModelHubEventType.CodeEvent:
return CodeEvent;
case IModelHubEventType.AllCodesDeletedEvent:
return AllCodesDeletedEvent;
case IModelHubEventType.BriefcaseDeletedEvent:
return BriefcaseDeletedEvent;
case IModelHubEventType.iModelDeletedEvent:
return IModelDeletedEvent;
case IModelHubEventType.VersionEvent:
return VersionEvent;
case IModelHubEventType.CheckpointCreatedEvent:
return CheckpointCreatedEvent;
case IModelHubEventType.CheckpointV2CreatedEvent:
return CheckpointV2CreatedEvent;
}
}
/** Parse [[IModelHubEvent]] from response object.
* @param response Response object to parse.
* @returns Appropriate event object.
* @internal
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
export function ParseEvent(response: Response) {
const constructor: EventConstructor = constructorFromEventType(response.header["content-type"]);
const event = new constructor();
event.fromJson(response.body);
return event;
}
/** Subscription to receive [[IModelHubEvent]]s. Each subscription has a separate queue for events that it hasn't read yet. Subscriptions are deleted, if they are inactive for an hour. Use wsgId of this instance for the methods that require subscriptionId. See [[EventSubscriptionHandler]].
* @internal
*/
@ECJsonTypeMap.classToJson("wsg", "iModelScope.EventSubscription", { schemaPropertyName: "schemaName", classPropertyName: "className" })
export class EventSubscription extends WsgInstance {
/** Types of the [[IModelHubEvent]]s that this subscription listens to. */
@ECJsonTypeMap.propertyToJson("wsg", "properties.EventTypes")
public eventTypes?: IModelHubEventType[];
}
/** Shared access signature token for getting [[IModelHubEvent]]s. It's used to authenticate for [[EventHandler.getEvent]]. To receive an instance call [[EventHandler.getSASToken]].
* @internal
*/
@ECJsonTypeMap.classToJson("wsg", "iModelScope.EventSAS", { schemaPropertyName: "schemaName", classPropertyName: "className" })
export class EventSAS extends BaseEventSAS {
}
/** Handler for managing [[EventSubscription]]s. Use [[EventHandler.Subscriptions]] to get an instance of this class.
* @internal
*/
export class EventSubscriptionHandler {
private _handler: IModelBaseHandler;
/** Constructor for EventSubscriptionHandler.
* @param handler Handler for WSG requests.
*/
constructor(handler: IModelBaseHandler) {
this._handler = handler;
}
/** Get relative url for EventSubscription requests.
* @param iModelId Id of the iModel. See [[HubIModel]].
* @param instanceId Id of the subscription.
*/
private getRelativeUrl(iModelId: GuidString, instanceId?: string) {
return `/Repositories/iModel--${iModelId}/iModelScope/EventSubscription/${instanceId || ""}`;
}
/** Create an [[EventSubscription]].
* @param iModelId Id of the iModel. See [[HubIModel]].
* @param events Array of IModelHubEventTypes to subscribe to.
* @return Created EventSubscription instance.
* @throws [Common iModelHub errors]($docs/learning/iModelHub/CommonErrors)
*/
public async create(accessToken: AccessToken, iModelId: GuidString, events: IModelHubEventType[]): Promise<EventSubscription>;
/**
* Create an [[EventSubscription]].
* @param iModelId Id of the iModel. See [[HubIModel]].
* @param events Array of EventTypes to subscribe to.
* @return Created EventSubscription instance.
* @throws [Common iModelHub errors]($docs/learning/iModelHub/CommonErrors)
* @internal @deprecated Use IModelHubEventType enum for `events` instead.
*/
public async create(accessToken: AccessToken, iModelId: GuidString, events: EventType[]): Promise<EventSubscription>; // eslint-disable-line @typescript-eslint/unified-signatures, deprecation/deprecation
public async create(accessToken: AccessToken, iModelId: GuidString, events: IModelHubEventType[] | EventType[]) { // eslint-disable-line deprecation/deprecation
Logger.logInfo(loggerCategory, "Creating event subscription on iModel", () => ({ iModelId }));
ArgumentCheck.validGuid("iModelId", iModelId);
ArgumentCheck.nonEmptyArray("events", events);
let subscription = new EventSubscription();
subscription.eventTypes = events as IModelHubEventType[];
subscription = await this._handler.postInstance<EventSubscription>(accessToken, EventSubscription, this.getRelativeUrl(iModelId), subscription);
Logger.logTrace(loggerCategory, "Created event subscription on iModel", () => ({ iModelId }));
return subscription;
}
/** Update an [[EventSubscription]]. Can change the [[EventType]]s specified in the subscription. Must be a valid subscription that was previously created with [[EventSubscriptionHandler.create]] that hasn't expired.
* @param iModelId Id of the iModel. See [[HubIModel]].
* @param subscription Updated EventSubscription.
* @return EventSubscription instance from iModelHub after update.
* @throws [[IModelHubError]] with [IModelHubStatus.EventSubscriptionDoesNotExist]($bentley) if [[EventSubscription]] does not exist with the specified subscription.wsgId.
* @throws [Common iModelHub errors]($docs/learning/iModelHub/CommonErrors)
*/
public async update(accessToken: AccessToken, iModelId: GuidString, subscription: EventSubscription): Promise<EventSubscription> {
Logger.logInfo(loggerCategory, "Updating event subscription on iModel", () => ({ iModelId }));
ArgumentCheck.validGuid("iModelId", iModelId);
ArgumentCheck.defined("subscription", subscription);
ArgumentCheck.validGuid("subscription.wsgId", subscription.wsgId);
const updatedSubscription = await this._handler.postInstance<EventSubscription>(accessToken, EventSubscription, this.getRelativeUrl(iModelId, subscription.wsgId), subscription);
Logger.logTrace(loggerCategory, "Updated event subscription on iModel", () => ({ iModelId }));
return updatedSubscription;
}
/** Delete an [[EventSubscription]].
* @param iModelId Id of the iModel. See [[HubIModel]].
* @param eventSubscriptionId Id of the EventSubscription.
* @returns Resolves if the EventSubscription has been successfully deleted.
* @throws [[IModelHubError]] with [IModelHubStatus.EventSubscriptionDoesNotExist]($bentley) if EventSubscription does not exist with the specified subscription.wsgId.
* @throws [Common iModelHub errors]($docs/learning/iModelHub/CommonErrors)
*/
public async delete(accessToken: AccessToken, iModelId: GuidString, eventSubscriptionId: string): Promise<void> {
Logger.logInfo(loggerCategory, `Deleting event subscription ${eventSubscriptionId} from iModel`, () => ({ iModelId }));
ArgumentCheck.validGuid("iModelId", iModelId);
ArgumentCheck.validGuid("eventSubscriptionId", eventSubscriptionId);
await this._handler.delete(accessToken, this.getRelativeUrl(iModelId, eventSubscriptionId));
Logger.logTrace(loggerCategory, `Deleted event subscription ${eventSubscriptionId} from iModel`, () => ({ iModelId }));
}
}
/** Handler for receiving [[IModelHubEvent]]s. Use [[IModelClient.Events]] to get an instance of this class.
* @internal
*/
export class EventHandler extends EventBaseHandler {
private _subscriptionHandler: EventSubscriptionHandler | undefined;
/** Constructor for EventHandler.
* @param handler Handler for WSG requests.
* @internal
*/
constructor(handler: IModelBaseHandler) {
super();
this._handler = handler;
}
/** Get a handler for managing [[EventSubscription]]s. */
public get subscriptions(): EventSubscriptionHandler {
if (!this._subscriptionHandler) {
this._subscriptionHandler = new EventSubscriptionHandler(this._handler);
}
return this._subscriptionHandler;
}
/** Get relative url for EventSAS requests.
* @param iModelId Id of the iModel. See [[HubIModel]].
*/
private getEventSASRelativeUrl(iModelId: GuidString): string {
return `/Repositories/iModel--${iModelId}/iModelScope/EventSAS/`;
}
/** Get event SAS Token. Used to authenticate for [[EventHandler.getEvent]].
* @param iModelId Id of the iModel. See [[HubIModel]].
* @return SAS Token to connect to the topic.
* @throws [Common iModelHub errors]($docs/learning/iModelHub/CommonErrors)
*/
public async getSASToken(accessToken: AccessToken, iModelId: GuidString): Promise<EventSAS> {
Logger.logInfo(loggerCategory, "Getting event SAS token from iModel", () => ({ iModelId }));
ArgumentCheck.validGuid("iModelId", iModelId);
const eventSAS = await this._handler.postInstance<EventSAS>(accessToken, EventSAS, this.getEventSASRelativeUrl(iModelId), new EventSAS());
Logger.logTrace(loggerCategory, "Got event SAS token from iModel", () => ({ iModelId }));
return eventSAS;
}
/** Get absolute url for event requests.
* @param baseAddress Base address for the serviceBus.
* @param subscriptionId Id of the subscription.
* @param timeout Optional timeout for long polling.
*/
private getEventUrl(baseAddress: string, subscriptionId: string, timeout?: number): string {
let url: string = `${baseAddress}/Subscriptions/${subscriptionId}/messages/head`;
if (timeout) {
url = `${url}?timeout=${timeout}`;
}
return url;
}
/** Get [[IModelHubEvent]] from the [[EventSubscription]]. You can use long polling timeout, to have requests return when events are available (or request times out), rather than returning immediately when no events are found.
* @param sasToken SAS Token used to authenticate. See [[EventSAS.sasToken]].
* @param baseAddress Address for the events. See [[EventSAS.baseAddress]].
* @param subscriptionId Id of the subscription to the topic. See [[EventSubscription]].
* @param timeout Optional timeout duration in seconds for request, when using long polling.
* @return IModelHubEvent if it exists, undefined otherwise.
* @throws [[IModelHubClientError]] with [IModelHubStatus.UndefinedArgumentError]($bentley) or [IModelHubStatus.InvalidArgumentError]($bentley) if one of the arguments is undefined or has an invalid value.
* @throws [ResponseError]($itwin-client) if request has failed.
*/
public async getEvent(sasToken: string, baseAddress: string, subscriptionId: string, timeout?: number): Promise<IModelHubEvent | undefined> {
Logger.logInfo(loggerCategory, "Getting event from subscription", () => ({ subscriptionId }));
ArgumentCheck.defined("sasToken", sasToken);
ArgumentCheck.defined("baseAddress", baseAddress);
ArgumentCheck.validGuid("subscriptionId", subscriptionId);
const options = await this.getEventRequestOptions(GetEventOperationToRequestType.GetDestructive, sasToken, timeout);
const result = await request(this.getEventUrl(baseAddress, subscriptionId, timeout), options);
if (result.status === 204) {
Logger.logTrace(loggerCategory, "No events found on subscription", () => ({ subscriptionId }));
return undefined;
}
const event = ParseEvent(result);
Logger.logTrace(loggerCategory, "Got event from subscription", () => ({ subscriptionId }));
return event;
}
/** Create a listener for long polling events from an [[EventSubscription]]. When event is received from the subscription, every registered listener callback is called. This continuously waits for events until all created listeners for that subscriptionId are deleted.
* @param subscriptionId Id of EventSubscription.
* @param iModelId Id of the iModel. See [[HubIModel]].
* @param listener Callback that is called when an [[IModelHubEvent]] is received.
* @returns Function that deletes the created listener.
* @throws [[IModelHubClientError]] with [IModelHubStatus.UndefinedArgumentError]($bentley) or [IModelHubStatus.InvalidArgumentError]($bentley) if one of the arguments is undefined or has an invalid value.
*/
public createListener<T extends IModelHubEvent>(authenticationCallback: () => Promise<AccessToken | undefined>, subscriptionId: string, iModelId: GuidString, listener: (event: T) => void): () => void {
ArgumentCheck.defined("authenticationCallback", authenticationCallback);
ArgumentCheck.validGuid("subscriptionId", subscriptionId);
ArgumentCheck.validGuid("iModelId", iModelId);
const subscription = new ListenerSubscription();
subscription.authenticationCallback = authenticationCallback;
subscription.getEvent = async (sasToken: string, baseAddress: string, id: string, timeout?: number) =>
this.getEvent(sasToken, baseAddress, id, timeout);
subscription.getSASToken = async (accessToken: AccessToken) => this.getSASToken(accessToken, iModelId);
subscription.id = subscriptionId;
return EventListener.create(subscription, listener as (e: IModelHubBaseEvent) => void);
}
} | the_stack |
import {MetaUtils} from "../metadata/utils";
import * as Utils from "../utils";
import * as mongooseUtils from '../../mongoose/utils';
import {MetaData} from '../metadata/metadata';
import {ExportTypes} from '../constants/decorators';
import {IDynamicRepository, DynamicRepository} from '../dynamic/dynamic-repository';
import {InstanceService} from '../services/instance-service';
import {ParamTypeCustom} from '../metadata/param-type-custom';
import {searchUtils} from "../../search/elasticSearchUtils";
//var Config = Utils.config();
import {Decorators} from '../constants';
import {IRepositoryParams} from '../decorators/interfaces';
import {repositoryMap} from '../exports/repositories';
import {ISchemaGenerator} from '../interfaces/schema-generator';
import * as Enumerable from 'linq';
import {repoFromModel} from '../dynamic/model-entity';
export var mongooseNameSchemaMap: { [key: string]: any } = {};
import * as securityImpl from '../dynamic/security-impl';
var domain = require('domain');
import {inject} from '../../di/decorators/inject';
import {Messenger} from '../../mongoose/pubsub/messenger';
import {PrincipalContext} from '../../security/auth/principalContext';
import {Session} from '../../models/session';
import * as configUtils from '../utils';
import {repoMap} from './initialize-repositories';
import {getQueryOptionsFromQuery} from '../interfaces/queryOptions';
import * as Q from 'q';
const uuidv4 = require('uuid/v4');
import {IWorkerProcessService} from "../services/workerProcessService";
import {IWorkerProcess} from "../../models/IWorkerProcess";
import {IAutherizationParam} from "../../security/auth/autherizationParam";
import {allAutherizationRules, allAutherizationRulesMap, workerProcessService, mainMessenger, channleMessangerMap} from "./initialize-messengers";
export var messageBraodcastOnMessenger: (repo: IDynamicRepository, message: any,collection?:any) => void;
export var socketConnector: () => void;
export class InitializeScokets {
private _schemaGenerator: ISchemaGenerator;
private socketClientholder: { socket: any, clients: Array<any>, messenger: any } = { socket: {}, clients: [], messenger: {} };
private socketChannelGroups: any = {}; // key is channel name and values array of groups
private sessionSocketIdMap = {}; //need to be handled the disconnection {userId}.{socket.id}:true
private socket: any;
private io:any = undefined;
private serverId = uuidv4();
// name.role :{ role: string, accessmask: number, acl?: boolean }
constructor(server?: any) {
allAutherizationRules.forEach((rule) => {
this.socketChannelGroups[rule.name] = {};
});
this.initializeSocketServer(server);
}
public schemaGenerator(schemaGenerator: ISchemaGenerator) {
this._schemaGenerator = schemaGenerator;
}
private checkIfRepoForMessenger = (meta: MetaData): boolean =>
meta && (meta.params.exportType == ExportTypes.ALL ||
(this.io && (((meta.params.exportType & ExportTypes.WS) == ExportTypes.WS) ||
((meta.params.exportType & ExportTypes.WS_BROAD_CAST) == ExportTypes.WS_BROAD_CAST) ||
((meta.params.exportType & ExportTypes.PUB_SUB) == ExportTypes.PUB_SUB)))
)
private initializeSocketServer(server?: any) {
let self = this;
let io:any = self.io;
this.socketClientholder.socket = io;
let joinNormalChannels = (socket):any => {
let session = socket.handshake.query.curSession;
if (!session.userId) { return; }
if (!self.sessionSocketIdMap[session.userId]) { self.sessionSocketIdMap[session.userId] = {}; }
self.sessionSocketIdMap[session.userId][socket.id] = true;
if (socket.handshake.query && socket.handshake.query.applicableChannels
&& socket.handshake.query.applicableChannels.length) {
socket.handshake.query.applicableChannels.forEach((room) => {
if (room && room.name) {
if (!self.socketChannelGroups[room.name]) { self.socketChannelGroups[room.name] = {}; }
}
});
}
if (socket.handshake.query && socket.handshake.query.channels) {
let channelArr: Array<string> = socket.handshake.query.channels.split(",");
if (channelArr && channelArr.length) {
channelArr.forEach((room) => {
//console.log("joined room ", room);
socket.join(room);
});
}
}
return socket;
}
let joinRealiableChannels = (socket) => {
if (socket.handshake.query && socket.handshake.query.broadcastChannels
&& socket.handshake.query.broadcastChannels.length) {
socket.handshake.query.broadcastChannels.forEach((room) => {
if (room && room.name && room.group) {
if (socket.handshake.query && socket.handshake.query.reliableChannles) {
let channelArr: Array<string> = socket.handshake.query.reliableChannles.split(",");
if (channelArr.indexOf(room.name) > -1) {
//console.log("joined room group with reliable session", room.name + "_" + room.group + "_RC");
socket.join(room.name + "_" + room.group + "_RC");
if (!self.socketChannelGroups[room.name][room.group + "_RC"]) { self.socketChannelGroups[room.name][room.group + "_RC"] = true }
return;
}
}
//console.log("joined room group", room.name + "_" + room.group);
if (!self.socketChannelGroups[room.name][room.group]) { self.socketChannelGroups[room.name][room.group] = false }
socket.join(room.name + "_" + room.group);
}
else if (room) {
//console.log("joined room ", room);
socket.join(room);
}
});
}
return socket;
}
let createWorkerOnConnect = (socket) => {
let session = socket.handshake.query.curSession;
if (socket.handshake.query && socket.handshake.query.reliableChannles) {
var Config = Utils.config();
if (Config.Path && Config.Path.ackChannelName) {
socket.on(Config.Path.ackChannelName, function (data) {
//console.log("acknowledgement recieved", data);
// update last ask in session
securityImpl.updateSession({
netsessionid: socket.handshake.query.netsessionid,
channelName: data.message.channel,
lastack: new Date(data.message.timestamp),
}, session);
})
}
let channelArr: Array<string> = socket.handshake.query.reliableChannles.split(",");
if (channelArr && channelArr.length) {
let newWorker: IWorkerProcess = {
serverId: self.serverId, workerId: socket.id,
status: "connected", channels: channelArr, sessionId: session.sessionId, role: session.role
};
workerProcessService.createWorker(newWorker);
}
}
return socket;
}
let sendPendingMesagesOnConnect = (socket) => {
if (socket.handshake.query && socket.handshake.query.reliableChannles) {
let channelArr: Array<string> = socket.handshake.query.reliableChannles.split(",");
channelArr.forEach((rechannel) => {
if (socket.handshake.query.isAckRequired === "true" || socket.handshake.query.isAckRequired === true) {
securityImpl.getSessionLastAckForChannel(socket.handshake.query, rechannel).then((lastack) => {
if (lastack && channleMessangerMap && channleMessangerMap[rechannel]) {
//for each chnnel ask messeger the send an array of pending message
channleMessangerMap[rechannel].sendPendingMessage(rechannel, lastack, socket.id);
//use socket.emitt to send previous message
}
}).catch((error) => {
console.log("error in securityImpl.getSessionLastAckForChannel", error);
});
}
else {
securityImpl.getSessionLastTimeStampForChannel(socket.handshake.query, rechannel).then((lastemit) => {
if (lastemit && channleMessangerMap && channleMessangerMap[rechannel]) {
//for each chnnel ask messeger the send an array of pending message
channleMessangerMap[rechannel].sendPendingMessage(rechannel, lastemit, socket.id);
//use socket.emitt to send previous message
}
}).catch((error) => {
console.log("error in securityImpl.getSessionLastTimeStampForChannel", error);
});
}
}
)
}
return socket;
}
let updateWorkerService = (socket) => {
if (socket.handshake.query && socket.handshake.query.reliableChannles) {
let channelArr: Array<string> = socket.handshake.query.reliableChannles.split(",");
if (channelArr && channelArr.length) {
let newWorker: IWorkerProcess = { serverId: self.serverId, workerId: socket.id, status: "disconnected", channels: channelArr };
workerProcessService.updateWorker(newWorker);
}
}
return socket;
}
let updateSocketServer = (socket) => {
if (socket.handshake.query.curSession && socket.handshake.query.curSession.userId) {
let userId = socket.handshake.query.curSession.userId;
delete self.sessionSocketIdMap[userId][socket.id];
if (Object.keys(self.sessionSocketIdMap[userId]).length == 0) {
delete self.sessionSocketIdMap[userId];
}
}
return socket;
}
//const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)))
const compose = (...functions) => data =>
functions.reduce((value, func) => func(value), data)
//const compose = (...functions) => data =>
// functions.reduceRight((value, func) => func(value), data)
let onSocketConnection = (socket) => { sendPendingMesagesOnConnect(createWorkerOnConnect(joinRealiableChannels(joinNormalChannels(socket)))) };
//let onSocketConnection = (socket) => compose(joinNormalChannels , joinRealiableChannels , createWorkerOnConnect , sendPendingMesagesOnConnect)
//let onSocketDisConnection = (socket) => compose(updateWorkerService , updateSocketServer)
let onSocketDisConnection = (socket) => { updateWorkerService(updateSocketServer(socket)) }
let arrOfReadAction = ["findAll", "findWhere", "countWhere", "distinctWhere", "findOne","searchAll","count"];
let executefun = (parsedData, repo,socket) => {
try {
if (parsedData && parsedData.action && parsedData.message) {
if (securityImpl.isAuthorize(parsedData, repo, parsedData.action)) {
let resultpromise: any;
if (parsedData.action == "searchAll") {
parsedData.action = "findWhere";
}
if (parsedData.action == "count") {
parsedData.action = "countWhere";
}
if (parsedData.action == "findWhere" || parsedData.action == "countWhere") {
let resultquerydata = getQueryOptionsFromQuery(repo,parsedData.message);
resultpromise = repo[parsedData.action](resultquerydata.queryObj, null, resultquerydata.options);
} else {
resultpromise = repo[parsedData.action](parsedData.message);
}
if (arrOfReadAction.indexOf(parsedData.action) > -1) {
resultpromise.then((result) => socket.emit(repo.modelName(), result));
}
}
}
} catch (exceptio) {
//console.log(exceptio);
}
};
let onRepoMessageReceoved1 = (socket,data,repo)=> {
var d = domain.create();
d.run(() => {
//check if current session can be used
if (data && data.headers && data.headers.netsessionid &&
socket.handshake.query.curSession && socket.handshake.query.curSession.sessionId &&
data.headers.netsessionid == socket.handshake.query.curSession.sessionId) {
PrincipalContext.User = securityImpl.getContextObjectFromSession(socket.handshake.query.curSession);
executefun(data, repo,socket);
return
}
let curExecuteFun = () => { executefun(data, repo, socket); };
let result = (<any>(securityImpl.ensureLoggedIn()(data, undefined, curExecuteFun)));
if (result && result.catch) {
result.catch((err) => { console.log(err); });
}
});
};
let socketConector = () => {
if (!io && server) {
self.io = require('socket.io')(server, { 'transports': ['websocket', 'polling'] });
io = self.io;
}
if (!io) { return;}
io.on('connection',
function (socket) {
// this.socketClientholder.clients.push(client);
//console.log('client connected', socket.id);
if (socket.handshake.query) {
securityImpl.getSession(socket.handshake.query).then((session: Session) => {
socket.handshake.query.curSession = session;
onSocketConnection(socket);
}).catch((error) => {
//console.log("error in getSession", error);
});
}
//emitt pending messages
//fetch last timestam of client for each reliable channel
socket.on('disconnect', function () {
//console.log('client disconnected', socket.id);
onSocketDisConnection(socket);
});
for (let key in repoMap) {
let repo = repoMap[key].repo;
let meta: MetaData = repo.getMetaData();
if (meta && ((meta.params.exportType & ExportTypes.WS) == ExportTypes.WS)) {
socket.on(key, function (data, callback) {
if (callback) {
callback("success");
}
onRepoMessageReceoved1(socket, data, repo);
})
}
}
}
)
}
socketConnector = socketConector;
let messageOnMessenger = (repo: IDynamicRepository, message: any,collection?:any) =>
{
let key = repo.modelName();
let messenger:Messenger = repo.getMessanger();
let meta: MetaData = repo.getMetaData();
if (!messenger) {
return;
}
//console.log("message received on ", key);
if ((meta.params.exportType & ExportTypes.PUB_SUB) == ExportTypes.PUB_SUB) {
// messenger.sendMessageOnRepo(repo, message);
if (collection && collection.length) {
collection.forEach((msg) => {
messenger.sendMessageOnRepo(repo, msg);
});
} else {
messenger.sendMessageOnRepo(repo, message);
}
}
if (!io) {
return;
}
//handle if repo is completly broadcast
let broadcastToAll = (castType: string) => {
io.sockets.emit(key, message);
let channelRoom:any = io.sockets.adapter.rooms[key];
if (channelRoom) {
var roomclients = channelRoom.length;
//io.sockets.emit(key, message);
//io.to(key).emit(key, message);
//io.broadcast.to(key).emit(key, message);
console.log("WS_BROAD_CAST", { "channel": key, "no_of_broadcasts": roomclients });
}
}
if (meta.params.broadCastType && meta.params.broadCastType == ExportTypes.WS_BROAD_CAST) {
broadcastToAll("WS_BROAD_CAST");
// io.to(key).emit(message);
return;
}
// io.in(key).emit(key, message);
//NO aACL define
if (!allAutherizationRulesMap[key]) {
broadcastToAll("BROAD_CAST_NO_RULE");
return;
}
let messageSendStatistics: any = {};
let connectedClients = 0;
let broadCastClients = 0;
let reliableClients = 0;
let individualClients = 0;
let singelEmittClients = 0;
//handle broad cast group ..acl ==false
if (!self.socketChannelGroups[key]) {
return;
}
let updateReliableChannelSettings = (client) => {
if (!client) { return; }
if (!client.handshake) { return; }
if (!client.handshake.query) { return; }
if (!client.handshake.query.curSession) { return; }
reliableClients++;
let query = client.handshake.query;
let curSession = client.handshake.query.curSession;
console.log("updating session timstamp for ", query && query.name);
securityImpl.updateSession({
netsessionid: query.netsessionid,
channelName: key,
lastemit: messenger.lastMessageTimestamp,
status: 'active'
}, curSession);
}
for (let channleGroup in self.socketChannelGroups[key]) {
let isRealiableChannel = false;
let groupName = key + "_" + channleGroup; //channleGroup is {role} , {role_RC} , key is repo name matchedorder_ROLE_ADMIN
if (self.socketChannelGroups[key][channleGroup]) {
isRealiableChannel = self.socketChannelGroups[key][channleGroup];
//groupName += "_RC";
}
let channelRoom = io.sockets.adapter.rooms[groupName];
if (!channelRoom) {
continue;
}
var roomclients = channelRoom.sockets;
let broadcastClients: Array<any> = new Array<any>();
let addAllclientsInRoom = () => {
if (isRealiableChannel &&
message.singleWorkerOnRole) {
return;
}
for (let channelId in roomclients) {
if (message.receiver && message.receiver != channelId) {
continue;
}
if (message.receiver) {
delete message.receiver;
}
let client = io.sockets.connected[channelId];
if (!client) {
continue;
}
broadcastClients.push(client);
broadCastClients++
connectedClients++;
//under reliable channel
if (isRealiableChannel) {
updateReliableChannelSettings(client);
}
}
}
if (isRealiableChannel &&
message.singleWorkerOnRole && message.singleWorkerOnRole[channleGroup] &&
message.singleWorkerOnRole[channleGroup].serverId == self.serverId &&
roomclients[message.singleWorkerOnRole[channleGroup].workerId]) {
let client = io.sockets.connected[message.singleWorkerOnRole[channleGroup].workerId];
if (!client) {
continue;
}
//console.log("single emitter recieved on broadcasting", client.id)
broadcastClients.push(client);
broadCastClients++
connectedClients++;
singelEmittClients++;
updateReliableChannelSettings(client);
}
else {
addAllclientsInRoom();
}
if (broadcastClients && broadcastClients.length) {
messenger.sendMessageToclient(broadcastClients[0], repo, message, broadcastClients,collection);
}
}
//individual messages
let individualUsers: Array<string> = messenger.getAllUsersForNotification(message);
if (individualUsers && individualUsers.length) {
individualUsers.forEach((user: string) => {
if (self.sessionSocketIdMap[user]) {
for (let channelId in self.sessionSocketIdMap[user]) {
let client = io.sockets.connected[channelId];
if (!client) {
continue;
}
//check if already broadcasted
if (client.handshake.query && client.handshake.query.broadcastChannels) {
let channelArr: Array<string> = client.handshake.query.broadcastChannels.filter((x) => { return x.name==key });
if (channelArr && channelArr.length) {
continue;
}
}
connectedClients++;
individualClients++;
messenger.sendMessageToclient(client, repo, message,undefined,collection);
if (client.handshake.query && client.handshake.query.reliableChannles) {
let channelArr: Array<string> = client.handshake.query.reliableChannles.split(",");
if (channelArr.indexOf(key) > -1) {
updateReliableChannelSettings(client);
}
}
}
}
});
}
messageSendStatistics.connectedClients = connectedClients;
messageSendStatistics.broadCastClients = broadCastClients;
messageSendStatistics.reliableClients = reliableClients;
messageSendStatistics.individualClients = individualClients;
messageSendStatistics.singelEmittClients = singelEmittClients;
messageSendStatistics.channel = key;
messageSendStatistics.id = message._id && message._id.toString();
//console.log("pub-sub message sent ", messageSendStatistics);
};
messageBraodcastOnMessenger = messageOnMessenger;
}
} | the_stack |
import {Program, Library, RawValue, RawEAV, RawMap, handleTuples, asValue, libraries} from "../../ts";
import {Instance as HTMLInstance} from "../html/html";
function ixComparator(idMap:{[key:string]:{ix:number}}) {
return (a:string, b:string) => {
return idMap[a].ix - idMap[b].ix;
}
}
let operationFields:{[type:string]: string[]} = {
moveTo: ["x", "y"],
lineTo: ["x", "y"],
bezierQuadraticCurveTo: ["cp1x", "cp1y", "cp2x", "cp2y", "x", "y"],
quadraticCurveTo: ["cpx", "cpy", "x", "y"],
arc: ["x", "y", "radius", "startAngle", "endAngle", "anticlockwise"],
arcTo: ["x1", "y1", "x2", "y2", "radius"],
ellipse: ["x", "y", "radiusX", "radiusY", "rotation", "startAngle", "endAngle", "anticlockwise"],
rect: ["x", "y", "width", "height"],
closePath: []
};
let defaultOperationFieldValue:{[field:string]: any} = {
rotation: 0,
startAngle: 0,
endAngle: 2 * Math.PI,
anticlockwise: false
};
function isOperationType(val:RawValue): val is OperationType {
return !!operationFields[val];
}
const EMPTY_OBJ = {};
const EMPTY:never[] = [];
type CanvasInstance = HTMLCanvasElement & HTMLInstance;
export type OperationType = keyof Path2D;
export interface Operation {type: OperationType, args:any, paths:RawValue[]};
// {fillStyle: "#000000", strokeStyle: "#000000", lineWidth: 1, lineCap: "butt", lineJoin: "miter"}
export interface PathStyle {[key:string]: RawValue|undefined, fillStyle?:string, strokeStyle?:string, lineWidth?:number, lineCap?:string, lineJoin?: string };
export class Canvas extends Library {
static id = "canvas";
//////////////////////////////////////////////////////////////////////
// Implementation
//////////////////////////////////////////////////////////////////////
html:libraries.HTML;
canvases:RawMap<RawValue[]|undefined> = {};
paths:RawMap<RawValue[]|undefined> = {};
operations:RawMap<Operation|undefined> = {};
canvasPaths:RawMap<RawValue[]|undefined> = {};
pathToCanvases:RawMap<RawValue[]|undefined> = {};
pathStyles:RawMap<PathStyle|undefined> = {};
pathCache:RawMap<Path2D|undefined> = {};
dirty:RawMap<boolean|undefined> = {};
setup() {
this.html = this.program.attach("html") as libraries.HTML;
}
addCanvasInstance(canvasId:RawValue, instanceId:RawValue) {
let instances = this.canvases[canvasId] = this.canvases[canvasId] || [];
instances.push(instanceId);
}
clearCanvasInstance(canvasId:RawValue, instanceId:RawValue) {
let instances = this.canvases[canvasId];
if(!instances) return; // @FIXME: Seems like an error though
let ix = instances.indexOf(instanceId);
if(ix !== -1) {
instances.splice(ix, 1);
if(!instances.length) this.canvases[canvasId] = undefined;
}
}
getCanvasInstances(canvasId:RawValue) {
let instances = this.canvases[canvasId];
if(!instances) throw new Error(`Missing canvas instance(s) for ${canvasId}`);
return instances;
}
getCanvasPaths(canvasId:RawValue) {
return this.canvasPaths[canvasId];
}
addPath(id:RawValue) {
if(this.paths[id]) throw new Error(`Recreating path instance ${id}`);
this.pathStyles[id] = {};
this.dirty[id] = true;
return this.paths[id] = [];
}
clearPath(id:RawValue) {
if(!this.paths[id]) throw new Error(`Missing path instance ${id}`);
this.pathStyles[id] = undefined;
this.paths[id] = undefined;
this.dirty[id] = true;
}
getPath(id:RawValue) {
let path = this.paths[id];
if(!path) throw new Error(`Missing path instance ${id}`);
return path;
}
addOperation(id:RawValue, type:RawValue) {
if(this.operations[id]) throw new Error(`Recreating operation instance ${id}`);
if(!isOperationType(type)) throw new Error(`Invalid operation type ${type}`);
return this.operations[id] = {type, args: {}, paths: []};
}
clearOperation(id:RawValue) {
if(!this.operations[id]) { throw new Error(`Missing operation instance ${id}`); }
this.operations[id] = undefined;
}
getOperation(id:RawValue) {
let operation = this.operations[id];
if(!operation) throw new Error(`Missing operation instance ${id}`);
return operation;
}
getOperationArgs(operation:Operation) {
let {type, args} = operation;
let fields:string[] = operationFields[type as string];
let input = [];
let restOptional = false;
for(let field of fields) {
let value = asValue(args[field]);
if(value === undefined) value = defaultOperationFieldValue[field];
if(value === undefined) return;
input.push(value);
}
return input;
}
updateCache(dirtyPaths:RawValue[]) {
for(let id of dirtyPaths) {
if(!this.dirty[id]) continue;
let path = this.paths[id];
if(!path) continue;
let path2d = this.pathCache[id] = new window.Path2D();
for(let opId of path) {
if(opId === undefined) continue;
let operation = this.getOperation(opId);
let input = this.getOperationArgs(operation);
if(input === undefined) {
console.warn(`Skipping incomplete or invalid operation ${opId}`, operation.type, operation.args);
continue;
}
if(!path2d[operation.type]) {
console.warn(`Skipping unavailable operation type ${operation.type}. Check your browser's Path2D compatibility.`);
continue;
}
(path2d[operation.type] as (...args:any[]) => void)(...input);
}
}
}
rerender(dirtyPaths:RawValue[]) {
let dirtyCanvases:RawMap<boolean|undefined> = {};
for(let id of dirtyPaths) {
let canvasIds = this.pathToCanvases[id];
if(!canvasIds) continue;
for(let canvasId of canvasIds) {
dirtyCanvases[canvasId] = true;
}
}
for(let canvasId of Object.keys(dirtyCanvases)) {
let pathIds = this.canvasPaths[canvasId];
for(let instanceId of this.getCanvasInstances(canvasId)) {
let canvas = this.html.getInstance(instanceId) as CanvasInstance;
let ctx = canvas.getContext("2d")!;
ctx.clearRect(0, 0, canvas.width, canvas.height);
if(!pathIds) continue;
for(let id of pathIds) {
let cached = this.pathCache[id];
if(!cached) continue // This thing isn't a path (yet?)
let style = this.pathStyles[id] || EMPTY_OBJ as PathStyle;
let {fillStyle = "#000000", strokeStyle = "#000000", lineWidth = 1, lineCap = "butt", lineJoin = "miter"} = style;
ctx.fillStyle = fillStyle;
ctx.strokeStyle = strokeStyle;
ctx.lineWidth = lineWidth;
ctx.lineCap = lineCap;
ctx.lineJoin = lineJoin;
if(style.strokeStyle) ctx.stroke(cached);
if(style.fillStyle || !style.strokeStyle) ctx.fill(cached);
}
}
}
}
_isChanging = false;
changed = () => {
let dirtyPaths = Object.keys(this.dirty);
this.updateCache(dirtyPaths);
this.rerender(dirtyPaths);
this.dirty = {};
this._isChanging = false;
}
changing() {
if(!this._isChanging) {
this._isChanging = true;
setImmediate(this.changed);
}
}
//////////////////////////////////////////////////////////////////////
// Handlers
//////////////////////////////////////////////////////////////////////
handlers = {
"export instances": handleTuples(({adds, removes}) => {
for(let [canvasId, instanceId] of removes || EMPTY) this.clearCanvasInstance(canvasId, instanceId);
for(let [canvasId, instanceId] of adds || EMPTY) this.addCanvasInstance(canvasId, instanceId);
this.changing();
}),
"export paths": handleTuples(({adds, removes}) => {
for(let [pathId] of removes || EMPTY) this.clearPath(pathId);
for(let [pathId] of adds || EMPTY) this.addPath(pathId);
}),
"export operations": handleTuples(({adds, removes}) => {
for(let [operationId] of removes || EMPTY) this.clearOperation(operationId);
for(let [operationId, kind] of adds || EMPTY) this.addOperation(operationId, kind);
}),
"export canvas paths": handleTuples(({adds, removes}) => {
for(let [canvasId, pathId, ix] of removes || EMPTY) {
if(typeof ix !== "number") continue;
let instances = this.canvases[canvasId];
let paths = this.canvasPaths[canvasId];
if(!paths || !instances) continue;
paths[ix - 1] = undefined as any;
let canvases = this.pathToCanvases[pathId]!;
canvases.splice(canvases.indexOf(canvasId), 1);
// @FIXME: need a proper way to indicate dirtyness when an unchanged path is added a canvas.
// This hack just marks the path dirty, which will rerender any other canvases containing it o_o
this.dirty[pathId] = true;
}
for(let [canvasId, pathId, ix] of adds || EMPTY) {
if(typeof ix !== "number") continue;
let instances = this.canvases[canvasId];
let paths = this.canvasPaths[canvasId] = this.canvasPaths[canvasId] || [];
paths[ix - 1] = pathId;
let canvases = this.pathToCanvases[pathId] = this.pathToCanvases[pathId] || [];
canvases.push(canvasId);
// @FIXME: need a proper way to indicate dirtyness when an unchanged path is added a canvas.
// This hack just marks the path dirty, which will rerender any other canvases containing it o_o
this.dirty[pathId] = true;
}
this.changing();
}),
"export path operations": handleTuples(({adds, removes}) => {
for(let [pathId, operationId, ix] of removes || EMPTY) {
if(typeof ix !== "number") continue;
let path = this.paths[pathId];
let operation = this.operations[operationId];
if(path) path[ix - 1] = undefined as any;
if(operation) operation.paths.splice(operation.paths.indexOf(pathId), 1);
this.dirty[pathId] = true;
}
for(let [pathId, operationId, ix] of adds || EMPTY) {
if(typeof ix !== "number") continue;
let path = this.getPath(pathId);
let operation = this.getOperation(operationId);
path[ix - 1] = operationId;
operation.paths.push(pathId);
this.dirty[pathId] = true;
}
this.changing();
}),
"export operation attributes": handleTuples(({adds, removes}) => {
for(let [operationId, attribute, value] of removes || EMPTY) {
let operation = this.operations[operationId];
if(!operation) continue;
operation.args[attribute] = undefined;
for(let pathId of operation.paths) this.dirty[pathId] = true;
}
for(let [operationId, attribute, value] of adds || EMPTY) {
let operation = this.operations[operationId];
if(!operation) throw new Error(`Missing operation ${operationId} for AV ${attribute}: ${value}`);
if(operation.args[attribute]) throw new Error(`Attempting to overwrite existing attribute ${attribute} of ${operationId}: ${operation.args[attribute]} => ${value}`);
operation.args[attribute] = value;
for(let pathId of operation.paths) this.dirty[pathId] = true;
}
this.changing();
}),
"export path styles": handleTuples(({adds, removes}) => {
for(let [pathId, attribute, value] of removes || EMPTY) {
let pathStyle = this.pathStyles[pathId];
if(!pathStyle) continue;
pathStyle[attribute] = undefined;
this.dirty[pathId] = true;
}
for(let [pathId, attribute, value] of adds || EMPTY) {
let pathStyle = this.pathStyles[pathId];
if(!pathStyle) throw new Error(`Missing path style for ${pathId}.`);
pathStyle[attribute] = value;
this.dirty[pathId] = true;
}
this.changing();
})
}
}
Library.register(Canvas.id, Canvas); | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [waf](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awswaf.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Waf extends PolicyStatement {
public servicePrefix = 'waf';
/**
* Statement provider for service [waf](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awswaf.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Grants permission to create a ByteMatchSet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_CreateByteMatchSet.html
*/
public toCreateByteMatchSet() {
return this.to('CreateByteMatchSet');
}
/**
* Grants permission to create a GeoMatchSet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_CreateGeoMatchSet.html
*/
public toCreateGeoMatchSet() {
return this.to('CreateGeoMatchSet');
}
/**
* Grants permission to create an IPSet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_CreateIPSet.html
*/
public toCreateIPSet() {
return this.to('CreateIPSet');
}
/**
* Grants permission to create a RateBasedRule for limiting the volume of requests from a single IP address
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_CreateRateBasedRule.html
*/
public toCreateRateBasedRule() {
return this.to('CreateRateBasedRule');
}
/**
* Grants permission to create a RegexMatchSet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_CreateRegexMatchSet.html
*/
public toCreateRegexMatchSet() {
return this.to('CreateRegexMatchSet');
}
/**
* Grants permission to create a RegexPatternSet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_CreateRegexPatternSet.html
*/
public toCreateRegexPatternSet() {
return this.to('CreateRegexPatternSet');
}
/**
* Grants permission to create a Rule for filtering web requests
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_CreateRule.html
*/
public toCreateRule() {
return this.to('CreateRule');
}
/**
* Grants permission to create a RuleGroup, which is a collection of predefined rules that you can use in a WebACL
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_CreateRuleGroup.html
*/
public toCreateRuleGroup() {
return this.to('CreateRuleGroup');
}
/**
* Grants permission to create a SizeConstraintSet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_CreateSizeConstraintSet.html
*/
public toCreateSizeConstraintSet() {
return this.to('CreateSizeConstraintSet');
}
/**
* Grants permission to create an SqlInjectionMatchSet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_CreateSqlInjectionMatchSet.html
*/
public toCreateSqlInjectionMatchSet() {
return this.to('CreateSqlInjectionMatchSet');
}
/**
* Grants permission to create a WebACL, which contains rules for filtering web requests
*
* Access Level: Permissions management
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_CreateWebACL.html
*/
public toCreateWebACL() {
return this.to('CreateWebACL');
}
/**
* Grants permission to create a CloudFormation web ACL template in an S3 bucket for the purposes of migrating the web ACL from AWS WAF Classic to AWS WAF v2
*
* Access Level: Write
*
* Dependent actions:
* - s3:PutObject
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_CreateWebACLMigrationStack.html
*/
public toCreateWebACLMigrationStack() {
return this.to('CreateWebACLMigrationStack');
}
/**
* Grants permission to create an XssMatchSet, which you use to detect requests that contain cross-site scripting attacks
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_CreateXssMatchSet.html
*/
public toCreateXssMatchSet() {
return this.to('CreateXssMatchSet');
}
/**
* Grants permission to delete a ByteMatchSet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_DeleteByteMatchSet.html
*/
public toDeleteByteMatchSet() {
return this.to('DeleteByteMatchSet');
}
/**
* Grants permission to delete a GeoMatchSet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_DeleteGeoMatchSet.html
*/
public toDeleteGeoMatchSet() {
return this.to('DeleteGeoMatchSet');
}
/**
* Grants permission to delete an IPSet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_DeleteIPSet.html
*/
public toDeleteIPSet() {
return this.to('DeleteIPSet');
}
/**
* Grants permission to delete the LoggingConfiguration from a web ACL
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_DeleteLoggingConfiguration.html
*/
public toDeleteLoggingConfiguration() {
return this.to('DeleteLoggingConfiguration');
}
/**
* Grants permission to delete an IAM policy from a rule group
*
* Access Level: Permissions management
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_DeletePermissionPolicy.html
*/
public toDeletePermissionPolicy() {
return this.to('DeletePermissionPolicy');
}
/**
* Grants permission to delete a RateBasedRule
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_DeleteRateBasedRule.html
*/
public toDeleteRateBasedRule() {
return this.to('DeleteRateBasedRule');
}
/**
* Grants permission to delete a RegexMatchSet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_DeleteRegexMatchSet.html
*/
public toDeleteRegexMatchSet() {
return this.to('DeleteRegexMatchSet');
}
/**
* Grants permission to delete a RegexPatternSet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_DeleteRegexPatternSet.html
*/
public toDeleteRegexPatternSet() {
return this.to('DeleteRegexPatternSet');
}
/**
* Grants permission to delete a Rule
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_DeleteRule.html
*/
public toDeleteRule() {
return this.to('DeleteRule');
}
/**
* Grants permission to delete a RuleGroup
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_DeleteRuleGroup.html
*/
public toDeleteRuleGroup() {
return this.to('DeleteRuleGroup');
}
/**
* Grants permission to delete a SizeConstraintSet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_DeleteSizeConstraintSet.html
*/
public toDeleteSizeConstraintSet() {
return this.to('DeleteSizeConstraintSet');
}
/**
* Grants permission to delete an SqlInjectionMatchSet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_DeleteSqlInjectionMatchSet.html
*/
public toDeleteSqlInjectionMatchSet() {
return this.to('DeleteSqlInjectionMatchSet');
}
/**
* Grants permission to delete a WebACL
*
* Access Level: Permissions management
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_DeleteWebACL.html
*/
public toDeleteWebACL() {
return this.to('DeleteWebACL');
}
/**
* Grants permission to delete an XssMatchSet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_DeleteXssMatchSet.html
*/
public toDeleteXssMatchSet() {
return this.to('DeleteXssMatchSet');
}
/**
* Grants permission to retrieve a ByteMatchSet
*
* Access Level: Read
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_GetByteMatchSet.html
*/
public toGetByteMatchSet() {
return this.to('GetByteMatchSet');
}
/**
* Grants permission to retrieve a change token to use in create, update, and delete requests
*
* Access Level: Read
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_GetChangeToken.html
*/
public toGetChangeToken() {
return this.to('GetChangeToken');
}
/**
* Grants permission to retrieve the status of a change token
*
* Access Level: Read
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_GetChangeTokenStatus.html
*/
public toGetChangeTokenStatus() {
return this.to('GetChangeTokenStatus');
}
/**
* Grants permission to retrieve a GeoMatchSet
*
* Access Level: Read
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_GetGeoMatchSet.html
*/
public toGetGeoMatchSet() {
return this.to('GetGeoMatchSet');
}
/**
* Grants permission to retrieve an IPSet
*
* Access Level: Read
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_GetIPSet.html
*/
public toGetIPSet() {
return this.to('GetIPSet');
}
/**
* Grants permission to retrieve a LoggingConfiguration for a web ACL
*
* Access Level: Read
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_GetLoggingConfiguration.html
*/
public toGetLoggingConfiguration() {
return this.to('GetLoggingConfiguration');
}
/**
* Grants permission to retrieve an IAM policy for a rule group
*
* Access Level: Read
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_GetPermissionPolicy.html
*/
public toGetPermissionPolicy() {
return this.to('GetPermissionPolicy');
}
/**
* Grants permission to retrieve a RateBasedRule
*
* Access Level: Read
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_GetRateBasedRule.html
*/
public toGetRateBasedRule() {
return this.to('GetRateBasedRule');
}
/**
* Grants permission to retrieve the array of IP addresses that are currently being blocked by a RateBasedRule
*
* Access Level: Read
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_GetRateBasedRuleManagedKeys.html
*/
public toGetRateBasedRuleManagedKeys() {
return this.to('GetRateBasedRuleManagedKeys');
}
/**
* Grants permission to retrieve a RegexMatchSet
*
* Access Level: Read
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_GetRegexMatchSet.html
*/
public toGetRegexMatchSet() {
return this.to('GetRegexMatchSet');
}
/**
* Grants permission to retrieve a RegexPatternSet
*
* Access Level: Read
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_GetRegexPatternSet.html
*/
public toGetRegexPatternSet() {
return this.to('GetRegexPatternSet');
}
/**
* Grants permission to retrieve a Rule
*
* Access Level: Read
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_GetRule.html
*/
public toGetRule() {
return this.to('GetRule');
}
/**
* Grants permission to retrieve a RuleGroup
*
* Access Level: Read
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_GetRuleGroup.html
*/
public toGetRuleGroup() {
return this.to('GetRuleGroup');
}
/**
* Grants permission to retrieve detailed information about a sample set of web requests
*
* Access Level: Read
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_GetSampledRequests.html
*/
public toGetSampledRequests() {
return this.to('GetSampledRequests');
}
/**
* Grants permission to retrieve a SizeConstraintSet
*
* Access Level: Read
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_GetSizeConstraintSet.html
*/
public toGetSizeConstraintSet() {
return this.to('GetSizeConstraintSet');
}
/**
* Grants permission to retrieve an SqlInjectionMatchSet
*
* Access Level: Read
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_GetSqlInjectionMatchSet.html
*/
public toGetSqlInjectionMatchSet() {
return this.to('GetSqlInjectionMatchSet');
}
/**
* Grants permission to retrieve a WebACL
*
* Access Level: Read
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_GetWebACL.html
*/
public toGetWebACL() {
return this.to('GetWebACL');
}
/**
* Grants permission to retrieve an XssMatchSet
*
* Access Level: Read
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_GetXssMatchSet.html
*/
public toGetXssMatchSet() {
return this.to('GetXssMatchSet');
}
/**
* Grants permission to retrieve an array of ActivatedRule objects
*
* Access Level: List
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_ListActivatedRulesInRuleGroup.html
*/
public toListActivatedRulesInRuleGroup() {
return this.to('ListActivatedRulesInRuleGroup');
}
/**
* Grants permission to retrieve an array of ByteMatchSetSummary objects
*
* Access Level: List
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_ListByteMatchSets.html
*/
public toListByteMatchSets() {
return this.to('ListByteMatchSets');
}
/**
* Grants permission to retrieve an array of GeoMatchSetSummary objects
*
* Access Level: List
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_ListGeoMatchSets.html
*/
public toListGeoMatchSets() {
return this.to('ListGeoMatchSets');
}
/**
* Grants permission to retrieve an array of IPSetSummary objects
*
* Access Level: List
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_ListIPSets.html
*/
public toListIPSets() {
return this.to('ListIPSets');
}
/**
* Grants permission to retrieve an array of LoggingConfiguration objects
*
* Access Level: List
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_ListLoggingConfigurations.html
*/
public toListLoggingConfigurations() {
return this.to('ListLoggingConfigurations');
}
/**
* Grants permission to retrieve an array of RuleSummary objects
*
* Access Level: List
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_ListRateBasedRules.html
*/
public toListRateBasedRules() {
return this.to('ListRateBasedRules');
}
/**
* Grants permission to retrieve an array of RegexMatchSetSummary objects
*
* Access Level: List
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_ListRegexMatchSets.html
*/
public toListRegexMatchSets() {
return this.to('ListRegexMatchSets');
}
/**
* Grants permission to retrieve an array of RegexPatternSetSummary objects
*
* Access Level: List
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_ListRegexPatternSets.html
*/
public toListRegexPatternSets() {
return this.to('ListRegexPatternSets');
}
/**
* Grants permission to retrieve an array of RuleGroup objects
*
* Access Level: List
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_ListRuleGroups.html
*/
public toListRuleGroups() {
return this.to('ListRuleGroups');
}
/**
* Grants permission to retrieve an array of RuleSummary objects
*
* Access Level: List
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_ListRules.html
*/
public toListRules() {
return this.to('ListRules');
}
/**
* Grants permission to retrieve an array of SizeConstraintSetSummary objects
*
* Access Level: List
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_ListSizeConstraintSets.html
*/
public toListSizeConstraintSets() {
return this.to('ListSizeConstraintSets');
}
/**
* Grants permission to retrieve an array of SqlInjectionMatchSet objects
*
* Access Level: List
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_ListSqlInjectionMatchSets.html
*/
public toListSqlInjectionMatchSets() {
return this.to('ListSqlInjectionMatchSets');
}
/**
* Grants permission to retrieve an array of RuleGroup objects that you are subscribed to
*
* Access Level: List
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_ListSubscribedRuleGroups.html
*/
public toListSubscribedRuleGroups() {
return this.to('ListSubscribedRuleGroups');
}
/**
* Grants permission to retrieve the tags for a resource
*
* Access Level: Read
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_ListTagsForResource.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to retrieve an array of WebACLSummary objects
*
* Access Level: List
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_ListWebACLs.html
*/
public toListWebACLs() {
return this.to('ListWebACLs');
}
/**
* Grants permission to retrieve an array of XssMatchSet objects
*
* Access Level: List
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_ListXssMatchSets.html
*/
public toListXssMatchSets() {
return this.to('ListXssMatchSets');
}
/**
* Grants permission to associate a LoggingConfiguration with a specified web ACL
*
* Access Level: Write
*
* Dependent actions:
* - iam:CreateServiceLinkedRole
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_PutLoggingConfiguration.html
*/
public toPutLoggingConfiguration() {
return this.to('PutLoggingConfiguration');
}
/**
* Grants permission to attach an IAM policy to a rule group, to share the rule group between accounts
*
* Access Level: Permissions management
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_PutPermissionPolicy.html
*/
public toPutPermissionPolicy() {
return this.to('PutPermissionPolicy');
}
/**
* Grants permission to add a Tag to a resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_TagResource.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to remove a Tag from a resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_UntagResource.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permission to insert or delete ByteMatchTuple objects in a ByteMatchSet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_UpdateByteMatchSet.html
*/
public toUpdateByteMatchSet() {
return this.to('UpdateByteMatchSet');
}
/**
* Grants permission to insert or delete GeoMatchConstraint objects in a GeoMatchSet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_UpdateGeoMatchSet.html
*/
public toUpdateGeoMatchSet() {
return this.to('UpdateGeoMatchSet');
}
/**
* Grants permission to insert or delete IPSetDescriptor objects in an IPSet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_UpdateIPSet.html
*/
public toUpdateIPSet() {
return this.to('UpdateIPSet');
}
/**
* Grants permission to modify a rate based rule
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_UpdateRateBasedRule.html
*/
public toUpdateRateBasedRule() {
return this.to('UpdateRateBasedRule');
}
/**
* Grants permission to insert or delete RegexMatchTuple objects in a RegexMatchSet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_UpdateRegexMatchSet.html
*/
public toUpdateRegexMatchSet() {
return this.to('UpdateRegexMatchSet');
}
/**
* Grants permission to insert or delete RegexPatternStrings in a RegexPatternSet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_UpdateRegexPatternSet.html
*/
public toUpdateRegexPatternSet() {
return this.to('UpdateRegexPatternSet');
}
/**
* Grants permission to modify a Rule
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_UpdateRule.html
*/
public toUpdateRule() {
return this.to('UpdateRule');
}
/**
* Grants permission to insert or delete ActivatedRule objects in a RuleGroup
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_UpdateRuleGroup.html
*/
public toUpdateRuleGroup() {
return this.to('UpdateRuleGroup');
}
/**
* Grants permission to insert or delete SizeConstraint objects in a SizeConstraintSet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_UpdateSizeConstraintSet.html
*/
public toUpdateSizeConstraintSet() {
return this.to('UpdateSizeConstraintSet');
}
/**
* Grants permission to insert or delete SqlInjectionMatchTuple objects in an SqlInjectionMatchSet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_UpdateSqlInjectionMatchSet.html
*/
public toUpdateSqlInjectionMatchSet() {
return this.to('UpdateSqlInjectionMatchSet');
}
/**
* Grants permission to insert or delete ActivatedRule objects in a WebACL
*
* Access Level: Permissions management
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_UpdateWebACL.html
*/
public toUpdateWebACL() {
return this.to('UpdateWebACL');
}
/**
* Grants permission to insert or delete XssMatchTuple objects in an XssMatchSet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_UpdateXssMatchSet.html
*/
public toUpdateXssMatchSet() {
return this.to('UpdateXssMatchSet');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"CreateByteMatchSet",
"CreateGeoMatchSet",
"CreateIPSet",
"CreateRateBasedRule",
"CreateRegexMatchSet",
"CreateRegexPatternSet",
"CreateRule",
"CreateRuleGroup",
"CreateSizeConstraintSet",
"CreateSqlInjectionMatchSet",
"CreateWebACLMigrationStack",
"CreateXssMatchSet",
"DeleteByteMatchSet",
"DeleteGeoMatchSet",
"DeleteIPSet",
"DeleteLoggingConfiguration",
"DeleteRateBasedRule",
"DeleteRegexMatchSet",
"DeleteRegexPatternSet",
"DeleteRule",
"DeleteRuleGroup",
"DeleteSizeConstraintSet",
"DeleteSqlInjectionMatchSet",
"DeleteXssMatchSet",
"PutLoggingConfiguration",
"UpdateByteMatchSet",
"UpdateGeoMatchSet",
"UpdateIPSet",
"UpdateRateBasedRule",
"UpdateRegexMatchSet",
"UpdateRegexPatternSet",
"UpdateRule",
"UpdateRuleGroup",
"UpdateSizeConstraintSet",
"UpdateSqlInjectionMatchSet",
"UpdateXssMatchSet"
],
"Permissions management": [
"CreateWebACL",
"DeletePermissionPolicy",
"DeleteWebACL",
"PutPermissionPolicy",
"UpdateWebACL"
],
"Read": [
"GetByteMatchSet",
"GetChangeToken",
"GetChangeTokenStatus",
"GetGeoMatchSet",
"GetIPSet",
"GetLoggingConfiguration",
"GetPermissionPolicy",
"GetRateBasedRule",
"GetRateBasedRuleManagedKeys",
"GetRegexMatchSet",
"GetRegexPatternSet",
"GetRule",
"GetRuleGroup",
"GetSampledRequests",
"GetSizeConstraintSet",
"GetSqlInjectionMatchSet",
"GetWebACL",
"GetXssMatchSet",
"ListTagsForResource"
],
"List": [
"ListActivatedRulesInRuleGroup",
"ListByteMatchSets",
"ListGeoMatchSets",
"ListIPSets",
"ListLoggingConfigurations",
"ListRateBasedRules",
"ListRegexMatchSets",
"ListRegexPatternSets",
"ListRuleGroups",
"ListRules",
"ListSizeConstraintSets",
"ListSqlInjectionMatchSets",
"ListSubscribedRuleGroups",
"ListWebACLs",
"ListXssMatchSets"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type bytematchset to the statement
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_ByteMatchSet.html
*
* @param id - Identifier for the id.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onBytematchset(id: string, account?: string, partition?: string) {
var arn = 'arn:${Partition}:waf::${Account}:bytematchset/${Id}';
arn = arn.replace('${Id}', id);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type ipset to the statement
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_IPSet.html
*
* @param id - Identifier for the id.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onIpset(id: string, account?: string, partition?: string) {
var arn = 'arn:${Partition}:waf::${Account}:ipset/${Id}';
arn = arn.replace('${Id}', id);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type ratebasedrule to the statement
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_RateBasedRule.html
*
* @param id - Identifier for the id.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onRatebasedrule(id: string, account?: string, partition?: string) {
var arn = 'arn:${Partition}:waf::${Account}:ratebasedrule/${Id}';
arn = arn.replace('${Id}', id);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type rule to the statement
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_Rule.html
*
* @param id - Identifier for the id.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onRule(id: string, account?: string, partition?: string) {
var arn = 'arn:${Partition}:waf::${Account}:rule/${Id}';
arn = arn.replace('${Id}', id);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type sizeconstraintset to the statement
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_SizeConstraintSet.html
*
* @param id - Identifier for the id.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onSizeconstraintset(id: string, account?: string, partition?: string) {
var arn = 'arn:${Partition}:waf::${Account}:sizeconstraintset/${Id}';
arn = arn.replace('${Id}', id);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type sqlinjectionmatchset to the statement
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_SqlInjectionMatchSet.html
*
* @param id - Identifier for the id.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onSqlinjectionmatchset(id: string, account?: string, partition?: string) {
var arn = 'arn:${Partition}:waf::${Account}:sqlinjectionset/${Id}';
arn = arn.replace('${Id}', id);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type webacl to the statement
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_WebACL.html
*
* @param id - Identifier for the id.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onWebacl(id: string, account?: string, partition?: string) {
var arn = 'arn:${Partition}:waf::${Account}:webacl/${Id}';
arn = arn.replace('${Id}', id);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type xssmatchset to the statement
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_XssMatchSet.html
*
* @param id - Identifier for the id.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onXssmatchset(id: string, account?: string, partition?: string) {
var arn = 'arn:${Partition}:waf::${Account}:xssmatchset/${Id}';
arn = arn.replace('${Id}', id);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type regexmatchset to the statement
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_RegexMatchSet.html
*
* @param id - Identifier for the id.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onRegexmatchset(id: string, account?: string, partition?: string) {
var arn = 'arn:${Partition}:waf::${Account}:regexmatch/${Id}';
arn = arn.replace('${Id}', id);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type regexpatternset to the statement
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_RegexPatternSet.html
*
* @param id - Identifier for the id.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onRegexpatternset(id: string, account?: string, partition?: string) {
var arn = 'arn:${Partition}:waf::${Account}:regexpatternset/${Id}';
arn = arn.replace('${Id}', id);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type geomatchset to the statement
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_GeoMatchSet.html
*
* @param id - Identifier for the id.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onGeomatchset(id: string, account?: string, partition?: string) {
var arn = 'arn:${Partition}:waf::${Account}:geomatchset/${Id}';
arn = arn.replace('${Id}', id);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type rulegroup to the statement
*
* https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_RuleGroup.html
*
* @param id - Identifier for the id.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onRulegroup(id: string, account?: string, partition?: string) {
var arn = 'arn:${Partition}:waf::${Account}:rulegroup/${Id}';
arn = arn.replace('${Id}', id);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
} | the_stack |
/// <reference types="node" />
import * as http from 'http';
import * as Buffer from 'buffer';
import * as https from 'https';
declare namespace core {
interface NeedleResponse extends http.IncomingMessage {
body: any;
raw: Buffer;
bytes: number;
cookies?: Cookies;
}
type ReadableStream = NodeJS.ReadableStream;
type NeedleCallback = (error: Error | null, response: NeedleResponse, body: any) => void;
interface Cookies {
[name: string]: any;
}
type NeedleOptions = RequestOptions & ResponseOptions & RedirectOptions & https.RequestOptions;
type NeedleReadonlyHttpVerbs = 'get' | 'head';
type NeedleReadWriteHttpVerbs = 'delete' | 'patch' | 'post' | 'put';
type NeedleHttpVerbs = NeedleReadonlyHttpVerbs | NeedleReadWriteHttpVerbs;
interface RequestOptions {
/**
* Returns error if connection takes longer than X milisecs to establish.
* Defaults to 10000 (10 secs). 0 means no timeout.
*/
open_timeout?: number;
/**
* Alias for open_timeout
*/
timeout?: RequestOptions['open_timeout'];
/**
* Returns error if data transfer takes longer than X milisecs,
* after connection is established. Defaults to 0 (no timeout).
*/
read_timeout?: number;
/**
* Number of redirects to follow. Defaults to 0.
*/
follow_max?: number;
/**
* Alias for follow_max
*/
follow?: RequestOptions['follow_max'];
/**
* Enables multipart/form-data encoding. Defaults to false.
* Use it when uploading files.
*/
multipart?: boolean;
/**
* Uses an http.Agent of your choice, instead of the global, default one.
* Useful for tweaking the behaviour at the connection level, such as when doing tunneling.
*/
agent?: http.Agent | boolean;
/**
* Forwards request through HTTP(s) proxy.
* Eg. proxy: 'http://user:pass@proxy.server.com:3128'.
* For more advanced proxying/tunneling use a custom agent.
*/
proxy?: string;
/**
* Object containing custom HTTP headers for request.
*/
headers?: {};
/**
* Determines what to do with provided username/password.
* Options are auto, digest or basic (default).
* auto will detect the type of authentication depending on the response headers.
*/
auth?: "auto" | "digest" | "basic";
/**
* When true, sets content type to application/json and sends request body as JSON string,
* instead of a query string.
*/
json?: boolean;
/**
* When sending streams, this lets manually set the Content-Length header
* --if the stream's bytecount is known beforehand--,
* preventing ECONNRESET (socket hang up) errors on some servers that misbehave
* when receiving payloads of unknown size.
* Set it to 0 and Needle will get and set the stream's length,
* or leave unset for the default behavior,
* which is no Content-Length header for stream payloads.
*/
stream_length?: number;
// These properties are overwritten by those in the 'headers' field
/**
* Builds and sets a Cookie header from a { key: 'value' } object.
*/
cookies?: Cookies;
/**
* If true, sets 'Accept-Encoding' header to 'gzip,deflate',
* and inflates content if zipped.
* Defaults to false.
*/
compressed?: boolean;
// Overwritten if present in the URI
/**
* For HTTP basic auth.
*/
username?: string;
/**
* For HTTP basic auth. Requires username to be passed, but is optional.
*/
password?: string;
/**
* Sets 'Accept' HTTP header. Defaults to */*.
*/
accept?: string;
/**
* Sets 'Connection' HTTP header.
* Not set by default, unless running Node < 0.11.4
* in which case it defaults to close.
*/
connection?: string;
/**
* Sets the 'User-Agent' HTTP header.
* Defaults to Needle/{version} (Node.js {node_version}).
*/
user_agent?: string;
/**
* Sets the 'Content-Type' header.
* Unset by default, unless you're sending data
* in which case it's set accordingly to whatever is being sent
* (application/x-www-form-urlencoded, application/json or multipart/form-data).
* That is, of course, unless the option is passed,
* either here or through options.headers.
*/
content_type?: string;
}
interface ResponseOptions {
/**
* Whether to decode the text responses to UTF-8,
* if Content-Type header shows a different charset. Defaults to true.
*/
decode_response?: boolean;
/**
* Alias for decode_response
*/
decode?: ResponseOptions['decode_response'];
/**
* Whether to parse XML or JSON response bodies automagically.
* Defaults to true.
* You can also set this to 'xml' or 'json' in which case Needle
* will only parse the response if the content type matches.
*/
parse_response?: boolean | 'json' | 'xml';
/**
* Alias for parse_response
*/
parse?: ResponseOptions['parse_response'];
/**
* Whether to parse response’s Set-Cookie header.
* Defaults to true.
* If parsed, response cookies will be available at resp.cookies.
*/
parse_cookies?: boolean;
/**
* Dump response output to file.
* This occurs after parsing and charset decoding is done.
*/
output?: string;
}
interface RedirectOptions {
/**
* Sends the cookies received in the set-cookie header
* as part of the following request.
* false by default.
*/
follow_set_cookie?: boolean;
/**
* Sets the 'Referer' header to the requested URI
* when following a redirect.
* false by default.
*/
follow_set_referer?: boolean;
/**
* If enabled, resends the request using the original verb
* instead of being rewritten to get with no data.
* false by default.
*/
follow_keep_method?: boolean;
/**
* When true, Needle will only follow redirects that point to the same host
* as the original request.
* false by default.
*/
follow_if_same_host?: boolean;
/**
* When true, Needle will only follow redirects that point to the same protocol
* as the original request.
* false by default.
*/
follow_if_same_protocol?: boolean;
}
interface KeyValue {
[key: string]: any;
}
type BodyData = Buffer | KeyValue | NodeJS.ReadableStream | string | null;
}
/**
* Calling needle() directly returns a Promise.
*
* Since needle 2.0
* @param method Designates an HTTP verb for the request.
*/
declare function needle(method: core.NeedleReadonlyHttpVerbs, url: string, options?: core.NeedleOptions): Promise<core.NeedleResponse>;
/**
* Calling needle() directly returns a Promise.
*
* Since needle 2.0
* @param method Designates an HTTP verb for the request.
* @param data May be null when issuing an HTTP DELETE request, but you need to explicity pass it.
*/
declare function needle(method: core.NeedleHttpVerbs, url: string, data: core.BodyData, options?: core.NeedleOptions): Promise<core.NeedleResponse>;
declare namespace needle {
export type BodyData = core.BodyData;
export type NeedleCallback = core.NeedleCallback;
export type NeedleHttpVerbs = core.NeedleHttpVerbs;
export type NeedleOptions = core.NeedleOptions;
export type NeedleResponse = core.NeedleResponse;
export type ReadableStream = core.ReadableStream;
/**
* Lets override the defaults for all future requests.
*/
export function defaults(options: NeedleOptions): NeedleOptions;
/**
* Issues an HTTP HEAD request.
*/
export function head(url: string, callback?: NeedleCallback): ReadableStream;
/**
* Issues an HTTP HEAD request.
*/
export function head(url: string, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream;
/**
* Issues an HTTP GET request.
*/
export function get(url: string, callback?: NeedleCallback): ReadableStream;
/**
* Issues an HTTP GET request.
*/
export function get(url: string, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream;
/**
* Issues an HTTP POST request.
*/
export function post(url: string, data: BodyData, callback?: NeedleCallback): ReadableStream;
/**
* Issues an HTTP POST request.
*/
export function post(url: string, data: BodyData, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream;
/**
* Issues an HTTP PUT request.
*/
export function put(url: string, data: BodyData, callback?: NeedleCallback): ReadableStream;
/**
* Issues an HTTP PUT request.
*/
export function put(url: string, data: BodyData, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream;
/**
* Same behaviour as PUT.
*/
export function patch(url: string, data: BodyData, callback?: NeedleCallback): ReadableStream;
/**
* Same behaviour as PUT.
*/
export function patch(url: string, data: BodyData, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream;
/**
* Issues an HTTP DELETE request.
*/
function deleteFunc(url: string, data: BodyData, callback?: NeedleCallback): ReadableStream;
/**
* Issues an HTTP DELETE request.
*/
function deleteFunc(url: string, data: BodyData, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream;
// See https://github.com/Microsoft/TypeScript/issues/1784#issuecomment-258720219
export { deleteFunc as delete };
/**
* Generic request.
* This not only allows for flexibility, but also lets you perform a GET request with data,
* in which case will be appended to the request as a query string,
* unless you pass a json: true option.
* @param method Designates an HTTP verb for the request.
*/
export function request(method: NeedleHttpVerbs, url: string, data: BodyData, callback?: NeedleCallback): ReadableStream;
/**
* Generic request.
* This not only allows for flexibility, but also lets you perform a GET request with data,
* in which case will be appended to the request as a query string,
* unless you pass a json: true option.
* @param method Designates an HTTP verb for the request.
*/
export function request(method: NeedleHttpVerbs, url: string, data: BodyData, options?: NeedleOptions, callback?: NeedleCallback): ReadableStream;
}
export = needle; | the_stack |
import {
createElement,
forwardRef,
memo, useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import {
ChildNodesType,
DropTargetType,
getComponentConfig, getDragSort,
getDropTarget,
PageConfigType,
ROOT,
STATE_PROPS,
} from '@brickd/core';
import { useCommon } from '@brickd/hooks';
import { getChildrenFields, VirtualDOMType } from '@brickd/utils';
import { isEqual, get, each, keys, isEmpty } from 'lodash';
import { defaultPropName } from 'common/constants';
import {
generateRequiredProps,
getComponent,
getIframe,
getSelectedNode,
cloneChildNodes,
dragSort,
getPropParentNodes,
getDragKey,
getIsModalChild,
PropParentNodes,
isVertical,
getDragSourceVDom,
isAllowAdd, isNeedJudgeFather, isAllowDrop,
} from '../utils';
import {
CommonPropsType,
handleModalTypeContainer,
propAreEqual,
handleChildNodes,
handlePropsClassName,
} from '../common/handleFuns';
import { useSelect } from '../hooks/useSelect';
import { useChildNodes } from '../hooks/useChildNodes';
import { useSelector } from '../hooks/useSelector';
import { useOperate } from '../hooks/useOperate';
import { useEvents } from '../hooks/useEvents';
import { useDropAble } from '../hooks/useDropAble';
/**
* 所有的容器组件名称
*/
export type ContainerState = {
pageConfig: PageConfigType;
dropTarget: DropTargetType;
};
function Container(allProps: CommonPropsType, ref: any) {
const {
specialProps,
specialProps: { key, domTreeKeys },
...rest
} = allProps;
const controlUpdate=useCallback((prevState: ContainerState, nextState: ContainerState)=> {
const {
pageConfig: prevPageConfig,
dropTarget: prevDropTarget,
} = prevState;
const { pageConfig, dropTarget } = nextState;
return (
prevPageConfig[key] !== pageConfig[key] ||
(get(prevDropTarget, 'selectedKey') === key &&
get(dropTarget, 'selectedKey') !== key) ||
(get(prevDropTarget, 'selectedKey') !== key &&
get(dropTarget, 'selectedKey') === key)
);
},[]);
const { pageConfig: PageDom, dropTarget } = useSelector<
ContainerState,
STATE_PROPS
>(['dropTarget', 'pageConfig'], controlUpdate);
const { selectedKey } = dropTarget || {};
const pageConfig = PageDom[ROOT] ? PageDom : getDragSourceVDom();
const vNode = get(pageConfig, key, {}) as VirtualDOMType;
const { childNodes, componentName } = vNode;
const { props, hidden, pageState } = useCommon(vNode, rest,getChildrenFields(pageConfig,childNodes));
const { index = 0, item, funParams } = pageState;
const uniqueKey=`${key}-${index}`;
useChildNodes({ childNodes, componentName, specialProps });
const [children, setChildren] = useState<ChildNodesType | undefined>(
childNodes,
);
useDropAble(componentName);
const { mirrorModalField, nodePropsConfig,childNodesRule } = useMemo(
() => getComponentConfig(componentName),
[],
);
const nodePropNames = keys(nodePropsConfig);
const prevPropName = useRef(
nodePropNames.includes(defaultPropName)
? defaultPropName
: nodePropNames[0],
);
const propParentNodes = useRef<PropParentNodes>({});
const parentRootNode = useRef<HTMLElement>();
const isModal = useMemo(() => getIsModalChild(pageConfig, domTreeKeys), [
pageConfig,
domTreeKeys,
]);
const { setOperateState, getOperateState } = useOperate(isModal);
const { selectedDomKeys, isSelected, propName } = useSelect(
specialProps,
!!mirrorModalField,
);
let selectedPropName = prevPropName.current;
if (propName && isSelected) {
prevPropName.current = propName;
selectedPropName = propName;
}
const {
setSelectedNode,
...events
} = useEvents(
parentRootNode,
specialProps,
isSelected,
props,
selectedPropName,
index,
);
const dragKey = getDragKey();
const dragOver=useCallback((event:DragEvent,propName:string)=>{
event.preventDefault();
const dragKey=getDragKey();
const {isLock}=getOperateState();
if(selectedKey!==key||domTreeKeys.includes(dragKey)||!isLock) return ;
setTimeout(()=>{
const childNodeKeys=get(children,propName,[]);
const isV=isVertical(propParentNodes.current[propName]);
if(!childNodeKeys.length){
getDragSort([dragKey]);
if (isEmpty(children)) {
setChildren({ [propName]: [dragKey] });
} else {
const newChildren = cloneChildNodes(childNodes);
newChildren[propName]=[dragKey];
setChildren(newChildren);
}
}else if(childNodeKeys.length===1&&childNodeKeys.includes(dragKey)){
return;
}else {
const newChildren=dragSort(childNodeKeys,propParentNodes.current[propName],event,isV);
const renderChildren=cloneChildNodes(childNodes);
renderChildren[propName]=newChildren;
if(!isEqual(renderChildren,children)){
getDragSort(newChildren);
setChildren(renderChildren);
}
}},200);
},[setChildren,children,selectedKey]);
useEffect(() => {
if (
!nodePropsConfig ||
isEmpty(propParentNodes.current)
)
return;
const propNameListeners = {};
each(propParentNodes.current, (parentNode, propName) => {
propNameListeners[propName] = {
dragOver:(event)=>dragOver(event,propName),
dragEnter: (event) => onDragEnter(event, propName),
};
parentNode.addEventListener('dragover',propNameListeners[propName].dragOver);
parentNode.addEventListener(
'dragenter',
get(propNameListeners, [propName, 'dragEnter']),
);
});
return () => {
each(propParentNodes.current, (parentNode, propName) => {
parentNode.removeEventListener('dragover',propNameListeners[propName].dragOver);
parentNode.removeEventListener(
'dragenter',
get(propNameListeners, [propName, 'dragEnter']),
);
});
};
},[propParentNodes.current]);
useEffect(() => {
if(dragKey&&domTreeKeys.includes(dragKey)) return;
const iframe = getIframe();
parentRootNode.current = getSelectedNode(uniqueKey, iframe);
const { index: selectedIndex } = getOperateState();
if (
isSelected &&
(isEmpty(funParams || item) ||
(isEmpty(funParams || item) && selectedIndex === index))
) {
setSelectedNode(parentRootNode.current);
}
if (childNodes) {
getPropParentNodes(childNodes, propParentNodes.current,index);
}
},[childNodes,dragKey]);
const parentDragOver =useCallback((event: DragEvent) => {
event.preventDefault();
const dragKey = getDragKey();
const {isLock}=getOperateState();
if(selectedKey!==key||domTreeKeys.includes(dragKey)||!isLock) return ;
const containerRootNode=propParentNodes.current[defaultPropName]||parentRootNode.current;
const isV = isVertical(containerRootNode);
if(isEmpty(children)){
if(nodePropsConfig){
setChildren({ [selectedPropName]: [dragKey] });
}else {
setChildren([dragKey]);
}
getDragSort([dragKey]);
}else if(Array.isArray(children)) {
if(children.length===1&&children.includes(dragKey)) return;
const newChildren = dragSort(
children,
containerRootNode,
event,
isV,
);
if (!isEqual(newChildren, children)) {
getDragSort(newChildren);
setChildren(newChildren);
}
}else {
const propChildren= get(children, selectedPropName, []);
if (!propChildren.includes(dragKey)) {
const newChildren = cloneChildNodes(children);
const childrenResult=[dragKey, ...propChildren];
getDragSort(childrenResult);
newChildren[selectedPropName] = childrenResult;
setChildren(newChildren);
}
}
},[children,setChildren,selectedKey]) ;
const onParentDragEnter = useCallback((e: DragEvent) => {
e.stopPropagation();
const dragKey = getDragKey();
/**
* 如果dragKey包含在组件所属的domTreeKeys中说明当前组件为拖拽组件的祖先节点之一
*/
if (domTreeKeys.includes(dragKey)) return;
let isDropAble;
if(nodePropsConfig){
const {childNodesRule}=nodePropsConfig[selectedPropName];
isDropAble=isAllowDrop(childNodesRule)&&(!isNeedJudgeFather()||isAllowAdd(`${componentName}.${selectedPropName}`));
}else {
isDropAble=isAllowDrop(childNodesRule)&&(!isNeedJudgeFather()||isAllowAdd(componentName));
}
setOperateState({
dropNode: parentRootNode.current,
isDropAble,
index,
isLock:true
});
if(!isDropAble) return;
getDropTarget({
propName: selectedPropName,
selectedKey: key,
domTreeKeys,
childNodeKeys:Array.isArray(childNodes)?childNodes:get(childNodes,selectedPropName,[])
});
},[childNodes,selectedPropName]);
useEffect(() => {
const containerRootNode=propParentNodes.current[defaultPropName]||parentRootNode.current;
if (isEmpty(containerRootNode)) return;
containerRootNode.addEventListener(
'dragover',
parentDragOver,
);
containerRootNode.addEventListener('dragenter',onParentDragEnter);
return () => {
containerRootNode.removeEventListener('dragover', parentDragOver);
containerRootNode.removeEventListener('dragenter',onParentDragEnter);
};
},[parentDragOver,onParentDragEnter]);
const { index: selectedIndex } = getOperateState();
if ((selectedKey !== key||selectedKey===key&&selectedIndex!==index) && !isEqual(childNodes, children)) {
setChildren(childNodes);
}
const onDragEnter = useCallback((e: DragEvent, propName?: string) => {
e.stopPropagation();
const dragKey = getDragKey();
if (domTreeKeys.includes(dragKey)) return;
const {childNodesRule}=nodePropsConfig[propName];
const isDropAble=isAllowDrop(childNodesRule)&&(!isNeedJudgeFather()||isAllowAdd(componentName));
setOperateState({
dropNode: propParentNodes.current[propName],
isDropAble,
index,
isLock:true
});
if(!isDropAble) return;
getDropTarget({
propName,
selectedKey: key,
domTreeKeys,
childNodeKeys:get(childNodes,propName,[])
});
},[propParentNodes.current,childNodes]);
if (!isSelected && (!componentName || hidden)) return null;
let modalProps: any = {};
if (mirrorModalField) {
const { displayPropName, mountedProps } = handleModalTypeContainer(
mirrorModalField,
);
if(displayPropName){
const isVisible =
isSelected || (selectedDomKeys && selectedDomKeys.includes(key));
modalProps = isVisible
? { [displayPropName]: isVisible, ...mountedProps }
: mountedProps;
}else {
modalProps=mountedProps;
}
}
const { className, animateClass, ...restProps } = props || {};
return createElement(getComponent(componentName), {
...restProps,
className: handlePropsClassName(
uniqueKey,
domTreeKeys.includes(dragKey),
className,
animateClass,
!!dragKey&&isAllowAdd(componentName)
),
onDragEnter:onParentDragEnter,
...events,
...generateRequiredProps(componentName),
...handleChildNodes(
specialProps,
pageConfig,
{ ...pageState, ...pageState.getPageState() },
children,
),
draggable: true,
/**
* 设置组件id方便抓取图片
*/
ref,
...modalProps,
});
}
export default memo<CommonPropsType>(forwardRef(Container), propAreEqual); | the_stack |
export function drawElements(canvas, drawingBufferWidth?, drawingBufferHeight?, nativeCanvas?) {
function main() {
var gl = canvas.getContext ? canvas.getContext("webgl") : canvas;
if (!gl) {
return;
}
drawingBufferWidth = drawingBufferWidth || gl.drawingBufferWidth;
drawingBufferHeight = drawingBufferHeight || gl.drawingBufferHeight;
console.log(drawingBufferWidth, drawingBufferHeight)
var vertexShaderSrc = `
attribute vec2 a_position;
uniform vec2 u_resolution;
void main() {
vec2 zeroToOne = a_position / u_resolution;
vec2 zeroToTwo = zeroToOne * 2.0;
vec2 clipSpace = zeroToTwo - 1.0;
gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);
}
`;
var fragmentShaderSrc = `
precision mediump float;
uniform vec4 u_color;
void main() {
gl_FragColor = u_color;
}
`;
// setup GLSL program
var vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vertexShaderSrc);
gl.compileShader(vertexShader);
let compiled = gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS);
if (!compiled) {
// Something went wrong during compilation; get the error
const lastError = gl.getShaderInfoLog(vertexShader);
console.log(
"*** Error compiling vertexShader '" + vertexShader + "':" + lastError
);
gl.deleteShader(vertexShader);
return null;
}
var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fragmentShaderSrc);
gl.compileShader(fragmentShader);
compiled = gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS);
if (!compiled) {
// Something went wrong during compilation; get the error
const lastError = gl.getShaderInfoLog(fragmentShader);
console.log(
"*** Error compiling fragmentShader '" +
fragmentShader +
"':" +
lastError
);
gl.deleteShader(fragmentShader);
return null;
}
var program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
// Check the link status
const linked = gl.getProgramParameter(program, gl.LINK_STATUS);
if (!linked) {
// something went wrong with the link
const lastError = gl.getProgramInfoLog(program);
console.log("Error in program linking:" + lastError);
gl.deleteProgram(program);
return null;
}
// look up where the vertex data needs to go.
var positionAttributeLocation = gl.getAttribLocation(program, "a_position");
// look up uniform locations
var resolutionUniformLocation = gl.getUniformLocation(
program,
"u_resolution"
);
var colorUniformLocation = gl.getUniformLocation(program, "u_color");
// Create a buffer to put three 2d clip space points in
var positionBuffer = gl.createBuffer();
// Bind it to ARRAY_BUFFER (think of it as ARRAY_BUFFER = positionBuffer)
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
// Tell WebGL how to convert from clip space to pixels
gl.viewport(0, 0, drawingBufferWidth, drawingBufferHeight);
// Clear the canvas
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT);
// Tell it to use our program (pair of shaders)
gl.useProgram(program);
// Bind the position buffer.
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
// create the buffer
const indexBuffer = gl.createBuffer();
// make this buffer the current 'ELEMENT_ARRAY_BUFFER'
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
// Fill the current element array buffer with data
const indices = [
0,
1,
2, // first triangle
2,
1,
3, // second triangle
];
gl.bufferData(
gl.ELEMENT_ARRAY_BUFFER,
new Uint16Array(indices),
gl.STATIC_DRAW
);
// code above this line is initialization code
// --------------------------------
// code below this line is rendering code
// Turn on the attribute
gl.enableVertexAttribArray(positionAttributeLocation);
// Tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
var size = 2; // 2 components per iteration
var type = gl.FLOAT; // the data is 32bit floats
var normalize = false; // don't normalize the data
var stride = 0; // 0 = move forward size * sizeof(type) each iteration to get the next position
var offset = 0; // start at the beginning of the buffer
gl.vertexAttribPointer(
positionAttributeLocation,
size,
type,
normalize,
stride,
offset
);
// bind the buffer containing the indices
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
// set the resolution
gl.uniform2f(
resolutionUniformLocation,
drawingBufferWidth,
drawingBufferHeight
);
// draw 50 random rectangles in random colors
for (var ii = 0; ii < 50; ++ii) {
// Setup a random rectangle
// This will write to positionBuffer because
// its the last thing we bound on the ARRAY_BUFFER
// bind point
setRectangle(
gl,
randomInt(300),
randomInt(300),
randomInt(300),
randomInt(300)
);
// Set a random color.
gl.uniform4f(
colorUniformLocation,
Math.random(),
Math.random(),
Math.random(),
1
);
// Draw the rectangle.
var primitiveType = gl.TRIANGLES;
var offset = 0;
var count = 6;
var indexType = gl.UNSIGNED_SHORT;
gl.drawElements(primitiveType, count, indexType, offset);
}
}
// Returns a random integer from 0 to range - 1.
function randomInt(range) {
return Math.floor(Math.random() * range);
}
// Fill the buffer with the values that define a rectangle.
function setRectangle(gl, x, y, width, height) {
var x1 = x;
var x2 = x + width;
var y1 = y;
var y2 = y + height;
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array([x1, y1, x2, y1, x1, y2, x2, y2]),
gl.STATIC_DRAW
);
}
main();
}
export function drawElementsBasic(canvas) {
var gl = canvas.getContext("webgl");
if (!gl) {
return;
}
var vertices = [
-0.5,
-0.5,
0.0,
-0.25,
0.5,
0.0,
0.0,
-0.5,
0.0,
0.25,
0.5,
0.0,
0.5,
-0.5,
0.0,
];
var indices = [0, 1, 2, 2, 3, 4];
gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0);
}
export function scaleTriangle(canvas) {
/*=================Creating a canvas=========================*/
var gl = canvas.getContext("experimental-webgl");
/*===========Defining and storing the geometry==============*/
var vertices = [-0.5, 0.5, 0.0, -0.5, -0.5, 0.0, 0.5, -0.5, 0.0];
//Create an empty buffer object and store vertex data
var vertex_buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, null);
/*========================Shaders============================*/
//Vertex shader source code
var vertCode =
"attribute vec4 coordinates;" +
"uniform mat4 u_xformMatrix;" +
"void main() {" +
" gl_Position = u_xformMatrix * coordinates;" +
"}";
//Create a vertex shader program object and compile it
var vertShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertShader, vertCode);
gl.compileShader(vertShader);
let compiled = gl.getShaderParameter(vertShader, gl.COMPILE_STATUS);
if (!compiled) {
// Something went wrong during compilation; get the error
const lastError = gl.getShaderInfoLog(vertShader);
console.log(
"*** Error compiling vertexShader '" + vertShader + "':" + lastError
);
gl.deleteShader(vertShader);
return null;
}
//fragment shader source code
var fragCode =
"void main() {" + " gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);" + "}";
//Create a fragment shader program object and compile it
var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragShader, fragCode);
gl.compileShader(fragShader);
compiled = gl.getShaderParameter(fragShader, gl.COMPILE_STATUS);
if (!compiled) {
// Something went wrong during compilation; get the error
const lastError = gl.getShaderInfoLog(fragShader);
console.log(
"*** Error compiling vertexShader '" + fragShader + "':" + lastError
);
gl.deleteShader(fragShader);
return null;
}
//Create and use combiened shader program
var shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertShader);
gl.attachShader(shaderProgram, fragShader);
gl.linkProgram(shaderProgram);
gl.useProgram(shaderProgram);
const linked = gl.getProgramParameter(shaderProgram, gl.LINK_STATUS);
if (!linked) {
// Something went wrong during compilation; get the error
const lastError = gl.getProgramInfoLog(shaderProgram);
console.log(
"*** Error linking shaderProgram '" + shaderProgram + "':" + lastError
);
return null;
}
/*===================scaling==========================*/
var Sx = 1.0,
Sy = 1.5,
Sz = 1.0;
var xformMatrix = new Float32Array([
Sx,
0.0,
0.0,
0.0,
0.0,
Sy,
0.0,
0.0,
0.0,
0.0,
Sz,
0.0,
0.0,
0.0,
0.0,
1.0,
]);
var u_xformMatrix = gl.getUniformLocation(shaderProgram, "u_xformMatrix");
gl.uniformMatrix4fv(u_xformMatrix, false, xformMatrix);
/* ===========Associating shaders to buffer objects============*/
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
var coordinatesVar = gl.getAttribLocation(shaderProgram, "coordinates");
gl.vertexAttribPointer(coordinatesVar, 3, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(coordinatesVar);
/*=================Drawing the Quad========================*/
gl.clearColor(0.5, 0.5, 0.5, 0.2);
//gl.enable(gl.DEPTH_TEST);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
gl.drawArrays(gl.TRIANGLES, 0, 3);
}
export function triangle(canvas) {
/*============== Creating a canvas ====================*/
var gl = canvas.getContext("experimental-webgl");
/*======== Defining and storing the geometry ===========*/
var vertices = [-0.5, 0.5, 0.0, -0.5, -0.5, 0.0, 0.5, -0.5, 0.0];
var indices = [0, 1, 2];
// Create an empty buffer object to store vertex buffer
var vertex_buffer = gl.createBuffer();
// Bind appropriate array buffer to it
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
// Pass the vertex data to the buffer
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
// Unbind the buffer
gl.bindBuffer(gl.ARRAY_BUFFER, null);
// Create an empty buffer object to store Index buffer
var Index_Buffer = gl.createBuffer();
// Bind appropriate array buffer to it
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Index_Buffer);
// Pass the vertex data to the buffer
gl.bufferData(
gl.ELEMENT_ARRAY_BUFFER,
new Uint16Array(indices),
gl.STATIC_DRAW
);
// Unbind the buffer
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
/*================ Shaders ====================*/
// Vertex shader source code
var vertCode =
"attribute vec3 coordinates;" +
"void main(void) {" +
" gl_Position = vec4(coordinates, 1.0);" +
"}";
// Create a vertex shader object
var vertShader = gl.createShader(gl.VERTEX_SHADER);
// Attach vertex shader source code
gl.shaderSource(vertShader, vertCode);
// Compile the vertex shader
gl.compileShader(vertShader);
//fragment shader source code
var fragCode =
"void main(void) {" + " gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);" + "}";
// Create fragment shader object
var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
// Attach fragment shader source code
gl.shaderSource(fragShader, fragCode);
// Compile the fragmentt shader
gl.compileShader(fragShader);
// Create a shader program object to store
// the combined shader program
var shaderProgram = gl.createProgram();
// Attach a vertex shader
gl.attachShader(shaderProgram, vertShader);
// Attach a fragment shader
gl.attachShader(shaderProgram, fragShader);
// Link both the programs
gl.linkProgram(shaderProgram);
// Use the combined shader program object
gl.useProgram(shaderProgram);
/*======= Associating shaders to buffer objects =======*/
// Bind vertex buffer object
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
// Bind index buffer object
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Index_Buffer);
// Get the attribute location
var coord = gl.getAttribLocation(shaderProgram, "coordinates");
// Point an attribute to the currently bound VBO
gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, 0, 0);
// Enable the attribute
gl.enableVertexAttribArray(coord);
/*=========Drawing the triangle===========*/
// Clear the canvas
gl.clearColor(0.5, 0.5, 0.5, 0.9);
// Enable the depth test
//gl.enable(gl.DEPTH_TEST);
// Clear the color buffer bit
gl.clear(gl.COLOR_BUFFER_BIT);
// Set the view port
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
// Draw the triangle
gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0);
}
export function points(canvas) {
/*================Creating a canvas=================*/
var gl = canvas.getContext("experimental-webgl");
/*==========Defining and storing the geometry=======*/
var vertices = [-0.5, 0.5, 0.0, 0.0, 0.5, 0.0, -0.25, 0.25, 0.0];
// Create an empty buffer object to store the vertex buffer
var vertex_buffer = gl.createBuffer();
//Bind appropriate array buffer to it
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
// Pass the vertex data to the buffer
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
// Unbind the buffer
gl.bindBuffer(gl.ARRAY_BUFFER, null);
/*=========================Shaders========================*/
// vertex shader source code
var vertCode =
"attribute vec3 coordinates;" +
"void main(void) {" +
" gl_Position = vec4(coordinates, 1.0);" +
"gl_PointSize = 10.0;" +
"}";
// Create a vertex shader object
var vertShader = gl.createShader(gl.VERTEX_SHADER);
// Attach vertex shader source code
gl.shaderSource(vertShader, vertCode);
// Compile the vertex shader
gl.compileShader(vertShader);
// fragment shader source code
var fragCode =
"void main(void) {" + " gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);" + "}";
// Create fragment shader object
var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
// Attach fragment shader source code
gl.shaderSource(fragShader, fragCode);
// Compile the fragmentt shader
gl.compileShader(fragShader);
// Create a shader program object to store
// the combined shader program
var shaderProgram = gl.createProgram();
// Attach a vertex shader
gl.attachShader(shaderProgram, vertShader);
// Attach a fragment shader
gl.attachShader(shaderProgram, fragShader);
// Link both programs
gl.linkProgram(shaderProgram);
// Use the combined shader program object
gl.useProgram(shaderProgram);
/*======== Associating shaders to buffer objects ========*/
// Bind vertex buffer object
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
// Get the attribute location
var coord = gl.getAttribLocation(shaderProgram, "coordinates");
// Point an attribute to the currently bound VBO
gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, 0, 0);
// Enable the attribute
gl.enableVertexAttribArray(coord);
/*============= Drawing the primitive ===============*/
// Clear the canvas
gl.clearColor(0.5, 0.5, 0.5, 0.9);
// Enable the depth test
//gl.enable(gl.DEPTH_TEST);
// Clear the color buffer bit
gl.clear(gl.COLOR_BUFFER_BIT);
// Set the view port
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
// Draw the triangle
gl.drawArrays(gl.POINTS, 0, 3);
}
export function drawModes(canvas, mode: 'line' | 'points' | 'line_strip' | 'triangle_strip' | 'triangle_fan' | 'triangles' | 'line_loop' = "line") {
/*======= Creating a canvas =========*/
var gl = canvas.getContext("experimental-webgl");
/*======= Defining and storing the geometry ======*/
var vertices = [
-0.7,
-0.1,
0,
-0.3,
0.6,
0,
-0.3,
-0.3,
0,
0.2,
0.6,
0,
0.3,
-0.3,
0,
0.7,
0.6,
0,
];
// Create an empty buffer object
var vertex_buffer = gl.createBuffer();
// Bind appropriate array buffer to it
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
// Pass the vertex data to the buffer
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
// Unbind the buffer
gl.bindBuffer(gl.ARRAY_BUFFER, null);
/*=================== Shaders ====================*/
// Vertex shader source code
var vertCode =
"attribute vec3 coordinates;" +
"void main(void) {" +
" gl_Position = vec4(coordinates, 1.0);" +
"}";
// Create a vertex shader object
var vertShader = gl.createShader(gl.VERTEX_SHADER);
// Attach vertex shader source code
gl.shaderSource(vertShader, vertCode);
// Compile the vertex shader
gl.compileShader(vertShader);
// Fragment shader source code
var fragCode =
"void main(void) {" + "gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);" + "}";
// Create fragment shader object
var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
// Attach fragment shader source code
gl.shaderSource(fragShader, fragCode);
// Compile the fragmentt shader
gl.compileShader(fragShader);
// Create a shader program object to store
// the combined shader program
var shaderProgram = gl.createProgram();
// Attach a vertex shader
gl.attachShader(shaderProgram, vertShader);
// Attach a fragment shader
gl.attachShader(shaderProgram, fragShader);
// Link both the programs
gl.linkProgram(shaderProgram);
// Use the combined shader program object
gl.useProgram(shaderProgram);
/*======= Associating shaders to buffer objects ======*/
// Bind vertex buffer object
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
// Get the attribute location
var coord = gl.getAttribLocation(shaderProgram, "coordinates");
// Point an attribute to the currently bound VBO
gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, 0, 0);
// Enable the attribute
gl.enableVertexAttribArray(coord);
/*============ Drawing the triangle =============*/
// Clear the canvas
gl.clearColor(0.5, 0.5, 0.5, 0.9);
// Enable the depth test
gl.enable(gl.DEPTH_TEST);
// Clear the color and depth buffer
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// Set the view port
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
// Draw the triangle
var m = gl.LINES;
switch (mode) {
case "points":
m = gl.POINTS;
break;
case "line_strip":
m = gl.LINE_STRIP;
break;
case "line_loop":
m = gl.LINE_LOOP;
break;
case "triangle_strip":
m = gl.TRIANGLE_STRIP;
break;
case "triangle_fan":
m = gl.TRIANGLE_FAN;
break;
case "triangles":
m = gl.TRIANGLES;
break;
default:
m = gl.LINES;
break;
}
gl.drawArrays(m, 0, 6);
// POINTS, LINE_STRIP, LINE_LOOP, LINES,
// TRIANGLE_STRIP,TRIANGLE_FAN, TRIANGLES
} | the_stack |
import {
Box,
Input,
InputGroup,
InputLeftAddon,
Spinner,
useColorMode,
} from '@chakra-ui/core'
import {
AuthProvider,
GithubButton,
useAuthData,
} from 'firebase-react-components'
import 'firebase/auth'
import fetch from 'isomorphic-unfetch'
import { Button, PageContainer } from 'landing-blocks'
import { Stack, StackProps } from 'layout-kit-react'
import Router from 'next/router'
import debounce from 'p-debounce'
import React, { useState } from 'react'
import {
Field,
Form,
useField,
useFormState,
FormRenderProps,
} from 'react-final-form'
import { useStorageState } from 'react-storage-hooks'
import { NPM_SCOPE, SESSION_STORAGE_CONFIG_KEY } from '../constants'
import { FormApi } from 'final-form'
export type MainFormData = {
name: string
endpoint: string
}
async function validate(
data: Partial<MainFormData>,
): Promise<Partial<MainFormData>> {
const errors: Partial<MainFormData> = {}
if (!data.name) {
errors.name = 'name required'
return errors
}
if (!data.endpoint) {
errors.endpoint = 'url required'
return errors
}
if (
!data?.endpoint?.startsWith('http://') &&
!data?.endpoint?.startsWith('https://')
) {
errors.endpoint = 'graphql endpoint should be an url'
}
// const nameOk = await npmNameAvailable(data.name)
// if (!nameOk) {
// errors.name = 'npm name already taken'
// }
return errors
}
function useInitialValues(
defaultValue: MainFormData,
): [MainFormData, Function] {
const [initialValues, setInitialValues] = useStorageState(
typeof window === 'undefined' ? null : localStorage,
SESSION_STORAGE_CONFIG_KEY,
JSON.stringify(defaultValue),
)
let data: any
try {
data = JSON.parse(initialValues)
} catch {
data = defaultValue
}
return [data, (x) => setInitialValues(JSON.stringify(x))]
}
export const MainForm = ({ ...rest }: StackProps) => {
const [error, setError] = useState('')
const [shouldLogin, setShouldLogin] = useState(false)
const { user, loading } = useAuthData()
const [initialValues, setInitialValues] = useInitialValues({
endpoint: 'https://countries.trevorblades.com',
name: 'my-package-' + (Math.random() * 1000).toFixed(0),
})
async function onSubmit(values: MainFormData) {
console.log('onSubmit')
setInitialValues(values)
if (!user) {
console.log('shouldLogin')
setShouldLogin(true)
return
}
console.log('sending ' + JSON.stringify(values, null, 4))
const res = await fetch('/api/publish', {
body: JSON.stringify(values),
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
})
if (!res.ok) {
setError(res.statusText)
return
}
const json = await res.json()
if (!json.ok) {
setError(json.error)
return
}
console.log('received ' + JSON.stringify(json, null, 4))
await Router.push({ query: { name: json.name }, pathname: '/ok' })
}
return (
<Form
initialValues={initialValues}
validate={validate}
onSubmit={onSubmit}
render={(formProps) => {
return (
<PageContainer spacing='0px'>
<Stack
// justify='center'
// align='space-between'
// minW='100%'
p='60px'
borderRadius='10px'
shadow='xl'
bg='white'
minH='100px'
// minW='400px'
{...rest}
>
<Stack
onSubmit={formProps.handleSubmit}
align='center'
w='100%'
as='form'
>
<AuthProvider
onError={console.error}
onLogin={async (user) => {
setShouldLogin(false)
console.log(
'called on login, redirecting',
)
// const uid = await user.getIdToken()
// Cookies.set(
// FIREBASE_ID_TOKEN_COOKIE,
// uid,
// {
// path: '/',
// },
// )
await Router.push('/me')
}}
>
<MainFormContent
w='100%'
shouldLogin={shouldLogin}
error={error}
resetError={() => setError('')}
{...formProps}
/>
</AuthProvider>
</Stack>
</Stack>
</PageContainer>
)
}}
/>
)
}
const MainFormContent = ({
submitting,
shouldLogin,
resetError,
error,
handleSubmit,
...rest
}: FormRenderProps & { shouldLogin; resetError } & StackProps) => {
const { loading, user } = useAuthData()
const { valid } = useFormState()
if (submitting || loading) {
return (
<Stack
mx='20px'
// color='primary'
align='center'
justify='center'
fontWeight='medium'
fontSize='text'
spacing='40px'
opacity={0.6}
textAlign='center'
{...rest}
>
<Box>
{loading ? 'logging in' : 'Generating the sdk package'}
</Box>
<Spinner />
</Stack>
)
}
if (shouldLogin && !user) {
return (
<Stack
maxW='400px'
// color='primary'
align='center'
justify='center'
fontWeight='medium'
fontSize='text'
spacing='40px'
textAlign='center'
>
<Box>Login first to create the client</Box>
<GithubButton text='Login With Github' />
{/* <DisplayUser /> */}
</Stack>
)
}
if (error) {
return (
<Stack
// color='primary'
align='center'
justify='center'
fontWeight='medium'
fontSize='text'
spacing='40px'
opacity={0.6}
textAlign='center'
>
<Box>Got an error 😢</Box>
<Box color='red.500'>{error}</Box>
<Button
// color='black'
onClick={(e) => {
e.preventDefault()
resetError()
}}
>
Retry
</Button>
</Stack>
)
}
if (!submitting) {
return (
<Stack
// flexDir={['column', null, null, 'row']}
spacing={['50px', null, null, '30px']}
direction={['column', null, null, 'row']}
// shouldWrapChildren
justify={['space-between', null, null, 'center']}
align={['center', null, null, 'flex-end']}
>
<Stack flex='1' position='relative' spacing='10px'>
<Label>Npm package name</Label>
<Field
name='name'
render={({ input, meta }) => (
<InputGroup shadow='sm'>
<InputLeftAddon>
<Box opacity={0.6}>{NPM_SCOPE}/</Box>
</InputLeftAddon>
<Input
{...input}
minW='160px'
isInvalid={meta.touched && meta.invalid}
roundedLeft='0'
type='text'
placeholder='Package Name'
/>
</InputGroup>
)}
/>
<ValidationError name='name' />
</Stack>
<Stack
w={['100%', null, null, 'auto']}
position='relative'
spacing='10px'
>
<Label>
Your Graphql api endpoint
{/* <Box as='pre' fontSize='0.8em'>
https://countries.trevorblades.com
</Box> */}
</Label>
<Field
name='endpoint'
render={({ input, meta }) => (
<Input
{...input}
isInvalid={meta.touched && meta.invalid}
shadow='sm'
minW='300px'
type='url'
placeholder='https://your-graphql-api'
/>
)}
/>
<ValidationError name='endpoint' />
</Stack>
<Button
type='submit'
onClick={(e) => {
e.preventDefault()
handleSubmit()
}}
animate
w={['100%', null, null, 'auto']}
shadow='md'
>
Generate Sdk Package
</Button>
</Stack>
)
}
}
const Label = (props) => {
const { colorMode } = useColorMode()
return (
<Box
color={{ light: 'gray.500', dark: 'gray.200' }[colorMode]}
{...props}
/>
)
}
export const ValidationError = ({ name, ...rest }) => {
const {
meta: { error, touched },
} = useField(name, { subscription: { error: true, touched: true } })
if (touched && error) {
return (
<Box
bottom='-50px'
position='absolute'
minH='40px'
color='red.500'
{...rest}
>
{error}
</Box>
)
}
return null
}
export const npmNameAvailable = debounce(async (name) => {
if (typeof name !== 'string') {
return Promise.reject(new Error('Name must be a string'))
}
const url = `https://unpkg.com/${name.toLowerCase()}`
const res = await fetch(url).catch((e) => {
console.log('catched fetch err')
})
return res && res.status === 404
}, 400) | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
class PrincipalObjectAttributeAccessApi {
/**
* DynamicsCrm.DevKit PrincipalObjectAttributeAccessApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Unique identifier of the shared secured field */
AttributeId: DevKit.WebApi.GuidValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_account: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_accountleads: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_activityfileattachment: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_activitymonitor: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_adminsettingsentity: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_appelement: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_applicationuser: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_appmodulecomponentedge: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_appmodulecomponentnode: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_appnotification: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_appointment: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_appsetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_appusersetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_attributeimageconfig: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_bookableresource: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_bookableresourcebooking: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_bookableresourcebookingexchangesyncidmapping: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_bookableresourcebookingheader: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_bookableresourcecategory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_bookableresourcecategoryassn: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_bookableresourcecharacteristic: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_bookableresourcegroup: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_bookingstatus: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_bot: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_botcomponent: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_bulkoperation: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_bulkoperationlog: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_businessunit: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_campaign: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_campaignactivity: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_campaignactivityitem: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_campaignitem: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_campaignresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_canvasappextendedmetadata: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_cascadegrantrevokeaccessrecordstracker: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_cascadegrantrevokeaccessversiontracker: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_catalog: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_catalogassignment: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
channelaccessprofile_principalobjectattributeaccess: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_characteristic: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_childincidentcount: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_commitment: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_competitor: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_competitoraddress: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_competitorproduct: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_competitorsalesliterature: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_connection: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_connectionreference: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_connector: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_constraintbasedgroup: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_contact: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_contactinvoices: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_contactleads: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_contactorders: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_contactquotes: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_contract: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_contractdetail: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_contracttemplate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_conversationtranscript: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_customapi: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_customapirequestparameter: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_customapiresponseproperty: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_customeraddress: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_customeropportunityrole: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_datalakefolder: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_datalakefolderpermission: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_datalakeworkspace: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_datalakeworkspacepermission: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_discount: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_discounttype: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_dynamicproperty: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_dynamicpropertyassociation: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_dynamicpropertyinstance: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_dynamicpropertyoptionsetitem: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_entitlement: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_entitlementchannel: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_entitlementcontacts: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_entitlemententityallocationtypemapping: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_entitlementproducts: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_entitlementtemplate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_entitlementtemplatechannel: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_entitlementtemplateproducts: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_entityanalyticsconfig: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_entityimageconfig: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_environmentvariabledefinition: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_environmentvariablevalue: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_equipment: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_exportsolutionupload: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_fax: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_feedback: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_flowmachine: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_flowmachinegroup: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_flowsession: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_goal: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_holidaywrapper: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_incident: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_incidentknowledgebaserecord: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_incidentresolution: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_internalcatalogassignment: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_invoice: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_invoicedetail: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_kbarticle: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_keyvaultreference: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_knowledgearticle: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_knowledgearticleincident: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_knowledgearticleviews: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_knowledgebaserecord: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_lead: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_leadaddress: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_leadcompetitors: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_leadproduct: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_leadtoopportunitysalesprocess: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_letter: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_list: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_listmember: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_listoperation: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_mailmergetemplate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_managedidentity: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_marketingformdisplayattributes: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdynce_botcontent: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdynsm_marketingsitemap: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdynsm_salessitemap: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdynsm_servicessitemap: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdynsm_settingssitemap: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_3dmodel: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_accountpricelist: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_actioncardregarding: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_actioncardrolesetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_actual: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_adaptivecardconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_adminappstate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_agentstatushistory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_agreement: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_agreementbookingdate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_agreementbookingincident: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_agreementbookingproduct: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_agreementbookingservice: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_agreementbookingservicetask: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_agreementbookingsetup: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_agreementinvoicedate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_agreementinvoiceproduct: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_agreementinvoicesetup: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_agreementsubstatus: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aibdataset: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aibdatasetfile: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aibdatasetrecord: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aibdatasetscontainer: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aibfile: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aibfileattacheddata: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aiconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aifptrainingdocument: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aimodel: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aiodimage: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aiodlabel: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aiodtrainingboundingbox: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aiodtrainingimage: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aitemplate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_analysiscomponent: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_analysisjob: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_analysisresult: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_analysisresultdetail: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_analytics: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_analyticsadminsettings: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_analyticsforcs: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_appconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_applicationextension: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_applicationtabtemplate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_assetcategorytemplateassociation: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_assettemplateassociation: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_assignmentconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_assignmentconfigurationstep: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_authenticationsettings: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_autocapturerule: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_autocapturesettings: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_batchjob: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_bookableresourceassociation: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_bookableresourcebookingquicknote: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_bookableresourcecapacityprofile: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_bookingalert: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_bookingalertstatus: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_bookingchange: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_bookingjournal: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_bookingrule: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_bookingsetupmetadata: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_bookingtimestamp: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_bpf_2c5fe86acc8b414b8322ae571000c799: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_bpf_477c16f59170487b8b4dc895c5dcd09b: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_bpf_665e73aa18c247d886bfc50499c73b82: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_bpf_989e9b1857e24af18787d5143b67523b: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_bpf_baa0a411a239410cb8bded8b5fdd88e3: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_bpf_d3d97bac8c294105840e99e37a9d1c39: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_bpf_d8f9dc7f099f44db9d641dd81fbd470d: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_businessclosure: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_callablecontext: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_cannedmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_capacityprofile: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_caseenrichment: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_casesuggestionrequestpayload: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_casetopic: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_casetopicsetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_casetopicsummary: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_casetopic_incident: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_cdsentityengagementctx: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_channel: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_channelcapability: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_channelprovider: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_characteristicreqforteammember: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_chatansweroption: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_chatquestionnaireresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_chatquestionnaireresponseitem: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_chatwidgetlanguage: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ciprovider: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_clientextension: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_collabgraphresource: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_configuration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_consoleapplicationnotificationfield: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_consoleapplicationnotificationtemplate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_consoleapplicationsessiontemplate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_consoleapplicationtemplate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_consoleapplicationtemplateparameter: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_consoleapplicationtype: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_consoleappparameterdefinition: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_contactpricelist: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_contractlinedetailperformance: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_contractlineinvoiceschedule: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_contractlinescheduleofvalue: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_contractperformance: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_conversationaction: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_conversationactionlocale: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_conversationdata: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_conversationinsight: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_conversationsuggestionrequestpayload: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_conversationtopic: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_conversationtopicsetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_conversationtopicsummary: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_conversationtopic_conversation: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_customengagementctx: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_customerasset: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_customerassetattachment: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_customerassetcategory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_dataanalyticsreport: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_dataanalyticsreport_csrmanager: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_dataanalyticsreport_ksinsights: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_dataanalyticsreport_oc: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_dataanalyticsreport_ocvoice: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_databaseversion: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_dataexport: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_dataflow: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_datainsightsandanalyticsfeature: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_decisioncontract: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_decisionruleset: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_delegation: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_dimension: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_dimensionfieldname: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_entitlementapplication: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_entityconfig: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_entityconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_entityrankingrule: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_entityroutingconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_estimate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_estimateline: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_expense: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_expensecategory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_expensereceipt: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_facebookengagementctx: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_fact: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_federatedarticle: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_federatedarticleincident: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_fieldcomputation: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_fieldservicepricelistitem: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_fieldservicesetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_fieldserviceslaconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_fieldservicesystemjob: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_findworkevent: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_flowcardtype: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_forecastconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_forecastdefinition: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_forecastinstance: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_forecastrecurrence: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_functionallocation: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_gdprdata: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_geofence: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_geofenceevent: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_geofencingsettings: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_geolocationsettings: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_geolocationtracking: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_helppage: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_icebreakersconfig: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_incidenttype: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_incidenttypecharacteristic: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_incidenttypeproduct: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_incidenttyperecommendationresult: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_incidenttyperecommendationrunhistory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_incidenttyperesolution: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_incidenttypeservice: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_incidenttypeservicetask: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_incidenttypessetup: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_incidenttype_requirementgroup: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_inspection: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_inspectionattachment: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_inspectiondefinition: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_inspectioninstance: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_inspectionresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_integrationjob: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_integrationjobdetail: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_inventoryadjustment: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_inventoryadjustmentproduct: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_inventoryjournal: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_inventorytransfer: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_invoicefrequency: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_invoicefrequencydetail: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_invoicelinetransaction: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_iotalert: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_iotdevice: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_iotdevicecategory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_iotdevicecommand: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_iotdevicecommanddefinition: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_iotdevicedatahistory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_iotdeviceproperty: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_iotdeviceregistrationhistory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_iotdevicevisualizationconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_iotfieldmapping: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_iotpropertydefinition: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_iotprovider: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_iotproviderinstance: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_iotsettings: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_iottocaseprocess: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_journal: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_journalline: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_kalanguagesetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_kbenrichment: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_kmfederatedsearchconfig: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_kmpersonalizationsetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_knowledgearticleimage: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_knowledgearticletemplate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_knowledgeinteractioninsight: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_knowledgepersonalfilter: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_knowledgesearchfilter: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_knowledgesearchinsight: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_kpieventdata: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_kpieventdefinition: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_lineengagementctx: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_livechatconfig: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_livechatengagementctx: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_livechatwidgetlocation: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_liveconversation: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_liveworkitemevent: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_liveworkstream: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_liveworkstreamcapacityprofile: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_localizedsurveyquestion: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_macrosession: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_maskingrule: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_masterentityroutingconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_migrationtracker: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_mlresultcache: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_msteamssetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_msteamssettingsv2: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_notesanalysisconfig: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_notificationfield: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_notificationtemplate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocbotchannelregistration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_occhannelconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_occhannelstateconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_occommunicationprovidersetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_occommunicationprovidersettingentry: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_occustommessagingchannel: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocfbapplication: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocfbpage: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_oclanguage: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_oclinechannelconfig: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocliveworkitemcapacityprofile: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocliveworkitemcharacteristic: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocliveworkitemcontextitem: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocliveworkitemparticipant: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocliveworkitemsentiment: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocliveworkstreamcontextvariable: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_oclocalizationdata: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocoutboundconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocphonenumber: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocprovisioningstate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocrequest: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocruleitem: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocsentimentdailytopic: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocsentimentdailytopickeyword: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocsentimentdailytopictrending: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocsession: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocsessioncharacteristic: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocsessionsentiment: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocsimltraining: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocsitdimportconfig: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocsitdskill: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocsitrainingdata: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocskillidentmlmodel: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocsmschannelsetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocsystemmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_octag: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_octeamschannelconfig: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_octwitterapplication: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_octwitterhandle: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocwechatchannelconfig: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocwhatsappchannelaccount: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_ocwhatsappchannelnumber: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_oc_geolocationprovider: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_omnichannelconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_omnichannelpersonalization: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_omnichannelqueue: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_omnichannelsyncconfig: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_operatinghour: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_opportunitylineresourcecategory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_opportunitylinetransaction: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_opportunitylinetransactioncategory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_opportunitylinetransactionclassificatio: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_opportunitypricelist: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_orderinvoicingdate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_orderinvoicingproduct: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_orderinvoicingsetup: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_orderinvoicingsetupdate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_orderlineresourcecategory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_orderlinetransaction: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_orderlinetransactioncategory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_orderlinetransactionclassification: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_orderpricelist: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_organizationalunit: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_paneconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_panetabconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_panetoolconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_payment: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_paymentdetail: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_paymentmethod: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_paymentterm: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_personalmessage: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_personalsoundsetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_personasecurityrolemapping: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_playbookactivity: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_playbookactivityattribute: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_playbookcategory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_playbookinstance: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_playbooktemplate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_pminferredtask: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_pmrecording: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_postalbum: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_postalcode: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_postconfig: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_postruleconfig: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_presence: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_priority: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_problematicasset: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_problematicassetfeedback: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_processnotes: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_productinventory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_productivityactioninputparameter: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_productivityactionoutputparameter: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_productivityagentscript: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_productivityagentscriptstep: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_productivitymacroactiontemplate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_productivitymacroconnector: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_productivitymacrosolutionconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_productivityparameterdefinition: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_project: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_projectapproval: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_projectparameter: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_projectparameterpricelist: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_projectpricelist: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_projecttask: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_projecttaskdependency: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_projecttaskstatususer: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_projectteam: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_projectteammembersignup: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_projecttransactioncategory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_property: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_propertyassetassociation: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_propertylog: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_propertytemplateassociation: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_provider: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_purchaseorder: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_purchaseorderbill: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_purchaseorderproduct: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_purchaseorderreceipt: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_purchaseorderreceiptproduct: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_purchaseordersubstatus: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_questionsequence: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_quotebookingincident: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_quotebookingproduct: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_quotebookingservice: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_quotebookingservicetask: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_quotebookingsetup: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_quoteinvoicingproduct: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_quoteinvoicingsetup: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_quotelineanalyticsbreakdown: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_quotelineinvoiceschedule: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_quotelineresourcecategory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_quotelinescheduleofvalue: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_quotelinetransaction: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_quotelinetransactioncategory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_quotelinetransactionclassification: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_quotepricelist: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_relationshipinsightsunifiedconfig: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_requirementcharacteristic: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_requirementdependency: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_requirementgroup: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_requirementorganizationunit: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_requirementrelationship: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_requirementresourcecategory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_requirementresourcepreference: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_requirementstatus: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_resolution: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_resourceassignment: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_resourceassignmentdetail: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_resourcecategorymarkuppricelevel: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_resourcecategorypricelevel: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_resourcepaytype: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_resourcerequest: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_resourcerequirement: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_resourcerequirementdetail: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_resourceterritory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_richtextfile: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_rma: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_rmaproduct: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_rmareceipt: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_rmareceiptproduct: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_rmasubstatus: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_rolecompetencyrequirement: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_roleutilization: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_routingconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_routingconfigurationstep: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_routingrequest: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_routingrulesetsetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_rtv: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_rtvproduct: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_rtvsubstatus: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_rulesetdependencymapping: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_salesinsightssettings: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_scenario: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_scheduleboardsetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_schedulingfeatureflag: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_schedulingparameter: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_searchconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_sentimentanalysis: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_serviceconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_servicetasktype: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_sessiondata: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_sessionevent: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_sessionparticipant: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_sessionparticipantdata: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_sessiontemplate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_shipvia: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_siconfig: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_sikeyvalueconfig: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_skillattachmentruleitem: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_skillattachmenttarget: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_slakpi: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_smartassistconfig: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_smsengagementctx: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_smsnumber: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_solutionhealthrule: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_solutionhealthruleargument: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_solutionhealthruleset: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_soundfile: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_soundnotificationsetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_suggestioninteraction: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_suggestionrequestpayload: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_suggestionsmodelsummary: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_suggestionssetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_surveyquestion: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_systemuserschedulersetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_taxcode: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_taxcodedetail: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_teamscollaboration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_teamsdialeradminsettings: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_teamsengagementctx: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_templateforproperties: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_templateparameter: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_templatetags: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_timeentry: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_timeentrysetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_timegroup: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_timegroupdetail: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_timeoffcalendar: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_timeoffrequest: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_tour: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_transactioncategory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_transactioncategoryclassification: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_transactioncategoryhierarchyelement: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_transactioncategorypricelevel: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_transactionconnection: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_transactionorigin: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_transactiontype: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_transcript: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_twitterengagementctx: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_unifiedroutingdiagnostic: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_unifiedroutingrun: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_unifiedroutingsetuptracker: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_uniquenumber: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_untrackedappointment: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_upgraderun: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_upgradestep: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_upgradeversion: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_urnotificationtemplate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_urnotificationtemplatemapping: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_usersetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_userworkhistory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_visitorjourney: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_wallsavedquery: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_wallsavedqueryusersettings: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_warehouse: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_wechatengagementctx: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_whatsappengagementctx: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_workhourtemplate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_workorder: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_workordercharacteristic: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_workorderdetailsgenerationqueue: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_workorderincident: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_workorderproduct: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_workorderresolution: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_workorderresourcerestriction: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_workorderservice: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_workorderservicetask: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_workordersubstatus: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_workordertype: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyusd_actioncallworkflow: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyusd_agentscriptaction: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyusd_agentscripttaskcategory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyusd_answer: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyusd_auditanddiagnosticssetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyusd_configuration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyusd_customizationfiles: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyusd_entityassignment: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyusd_entitysearch: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyusd_form: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyusd_languagemodule: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyusd_scriptlet: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyusd_scripttasktrigger: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyusd_search: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyusd_sessioninformation: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyusd_sessiontransfer: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyusd_task: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyusd_toolbarbutton: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyusd_toolbarstrip: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyusd_tracesourcesetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyusd_ucisettings: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyusd_uiievent: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyusd_usersettings: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyusd_windowroute: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msfp_alert: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msfp_alertrule: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msfp_emailtemplate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msfp_fileresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msfp_localizedemailtemplate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msfp_project: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msfp_question: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msfp_questionresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msfp_satisfactionmetric: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msfp_survey: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msfp_surveyinvite: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msfp_surveyreminder: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msfp_unsubscribedrecipient: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_opportunity: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_opportunityclose: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_opportunitycompetitors: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_opportunityproduct: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_opportunitysalesprocess: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_orderclose: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_organizationdatasyncsubscription: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_organizationdatasyncsubscriptionentity: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_organizationsetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_package: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_pdfsetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_phonecall: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_phonetocaseprocess: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_position: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_pricelevel: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_processstageparameter: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_product: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_productassociation: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_productpricelevel: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_productsalesliterature: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_productsubstitute: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_provisionlanguageforuser: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_queue: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_queueitem: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_quote: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_quoteclose: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_quotedetail: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_ratingmodel: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_ratingvalue: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_recurringappointmentmaster: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_relationshipattribute: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_reportcategory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_resource: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_resourcegroup: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_resourcegroupexpansion: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_resourcespec: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_revokeinheritedaccessrecordstracker: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_salesliterature: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_salesliteratureitem: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_salesorder: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_salesorderdetail: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_salesprocessinstance: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_service: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_serviceappointment: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_servicecontractcontacts: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_serviceplan: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_settingdefinition: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_sharepointdocumentlocation: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_sharepointsite: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_site: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_socialactivity: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_socialprofile: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_solutioncomponentattributeconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_solutioncomponentconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_solutioncomponentrelationshipconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_stagesolutionupload: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_systemuser: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_systemuserauthorizationchangetracker: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_task: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_team: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_teammobileofflineprofilemembership: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_territory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_topic: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_topichistory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_topicmodel: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_topicmodelconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_topicmodelexecutionhistory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_uii_action: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_uii_audit: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_uii_context: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_uii_hostedapplication: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_uii_nonhostedapplication: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_uii_option: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_uii_savedsession: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_uii_sessiontransfer: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_uii_workflow: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_uii_workflowstep: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_uii_workflow_workflowstep_mapping: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_uom: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_uomschedule: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_usermobileofflineprofilemembership: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_virtualentitymetadata: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_workflowbinary: DevKit.WebApi.LookupValue;
/** Unique identifier of the associated organization. */
OrganizationId: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the principal to which secured field is shared */
principalid_systemuser: DevKit.WebApi.LookupValue;
/** Unique identifier of the principal to which secured field is shared */
principalid_team: DevKit.WebApi.LookupValue;
/** Unique identifier of the shared secured field instance */
PrincipalObjectAttributeAccessId: DevKit.WebApi.GuidValue;
/** Read permission for secured field instance */
ReadAccess: DevKit.WebApi.BooleanValue;
/** Update permission for secured field instance */
UpdateAccess: DevKit.WebApi.BooleanValue;
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace PrincipalObjectAttributeAccess {
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':[],'JsWebApi':true,'IsDebugForm':false,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import {
action,
computed,
flow,
makeObservable,
observable,
runInAction,
} from "mobx";
import { AppCurrency, Keplr, KeplrSignOptions } from "@keplr-wallet/types";
import { DeepReadonly } from "utility-types";
import { ChainGetter } from "../common";
import { QueriesSetBase, QueriesStore } from "../query";
import { DenomHelper, toGenerator } from "@keplr-wallet/common";
import {
BroadcastMode,
makeSignDoc,
makeStdTx,
Msg,
StdFee,
StdSignDoc,
} from "@cosmjs/launchpad";
import {
BaseAccount,
cosmos,
google,
TendermintTxTracer,
} from "@keplr-wallet/cosmos";
import Axios, { AxiosInstance } from "axios";
import { Buffer } from "buffer/";
import Long from "long";
import ICoin = cosmos.base.v1beta1.ICoin;
import SignMode = cosmos.tx.signing.v1beta1.SignMode;
export enum WalletStatus {
NotInit = "NotInit",
Loading = "Loading",
Loaded = "Loaded",
NotExist = "NotExist",
Rejected = "Rejected",
}
export interface MsgOpt {
readonly type: string;
readonly gas: number;
}
/*
If the chain has "no-legacy-stdTx" feature, we should send the tx based on protobuf.
Expectedly, the sign doc should be formed as animo-json regardless of the tx type (animo or proto).
*/
type AminoMsgsOrWithProtoMsgs =
| Msg[]
| {
aminoMsgs: Msg[];
protoMsgs?: google.protobuf.IAny[];
};
export interface AccountSetOpts<MsgOpts> {
readonly prefetching: boolean;
readonly suggestChain: boolean;
readonly suggestChainFn?: (
keplr: Keplr,
chainInfo: ReturnType<ChainGetter["getChain"]>
) => Promise<void>;
readonly autoInit: boolean;
readonly preTxEvents?: {
onBroadcastFailed?: (e?: Error) => void;
onBroadcasted?: (txHash: Uint8Array) => void;
onFulfill?: (tx: any) => void;
};
readonly getKeplr: () => Promise<Keplr | undefined>;
readonly msgOpts: MsgOpts;
readonly wsObject?: new (
url: string,
protocols?: string | string[]
) => WebSocket;
}
export class AccountSetBase<MsgOpts, Queries> {
@observable
protected _walletVersion: string | undefined = undefined;
@observable
protected _walletStatus: WalletStatus = WalletStatus.NotInit;
@observable
protected _name: string = "";
@observable
protected _bech32Address: string = "";
@observable
protected _isSendingMsg: string | boolean = false;
public broadcastMode: "sync" | "async" | "block" = "sync";
protected pubKey: Uint8Array;
protected hasInited = false;
protected sendTokenFns: ((
amount: string,
currency: AppCurrency,
recipient: string,
memo: string,
stdFee: Partial<StdFee>,
signOptions?: KeplrSignOptions,
onTxEvents?:
| ((tx: any) => void)
| {
onBroadcastFailed?: (e?: Error) => void;
onBroadcasted?: (txHash: Uint8Array) => void;
onFulfill?: (tx: any) => void;
}
) => Promise<boolean>)[] = [];
constructor(
protected readonly eventListener: {
addEventListener: (type: string, fn: () => unknown) => void;
removeEventListener: (type: string, fn: () => unknown) => void;
},
protected readonly chainGetter: ChainGetter,
protected readonly chainId: string,
protected readonly queriesStore: QueriesStore<QueriesSetBase & Queries>,
protected readonly opts: AccountSetOpts<MsgOpts>
) {
makeObservable(this);
this.pubKey = new Uint8Array();
if (opts.autoInit) {
this.init();
}
}
getKeplr(): Promise<Keplr | undefined> {
return this.opts.getKeplr();
}
get msgOpts(): MsgOpts {
return this.opts.msgOpts;
}
registerSendTokenFn(
fn: (
amount: string,
currency: AppCurrency,
recipient: string,
memo: string,
stdFee: Partial<StdFee>,
signOptions?: KeplrSignOptions,
onTxEvents?:
| ((tx: any) => void)
| {
onBroadcasted?: (txHash: Uint8Array) => void;
onFulfill?: (tx: any) => void;
}
) => Promise<boolean>
) {
this.sendTokenFns.push(fn);
}
protected async enable(keplr: Keplr, chainId: string): Promise<void> {
const chainInfo = this.chainGetter.getChain(chainId);
if (this.opts.suggestChain) {
if (this.opts.suggestChainFn) {
await this.opts.suggestChainFn(keplr, chainInfo);
} else {
await this.suggestChain(keplr, chainInfo);
}
}
await keplr.enable(chainId);
}
protected async suggestChain(
keplr: Keplr,
chainInfo: ReturnType<ChainGetter["getChain"]>
): Promise<void> {
await keplr.experimentalSuggestChain(chainInfo.raw);
}
private readonly handleInit = () => this.init();
@flow
public *init() {
// If wallet status is not exist, there is no need to try to init because it always fails.
if (this.walletStatus === WalletStatus.NotExist) {
return;
}
// If the store has never been initialized, add the event listener.
if (!this.hasInited) {
// If key store in the keplr extension is changed, this event will be dispatched.
this.eventListener.addEventListener(
"keplr_keystorechange",
this.handleInit
);
}
this.hasInited = true;
// Set wallet status as loading whenever try to init.
this._walletStatus = WalletStatus.Loading;
const keplr = yield* toGenerator(this.getKeplr());
if (!keplr) {
this._walletStatus = WalletStatus.NotExist;
return;
}
this._walletVersion = keplr.version;
try {
yield this.enable(keplr, this.chainId);
} catch {
this._walletStatus = WalletStatus.Rejected;
return;
}
const key = yield* toGenerator(keplr.getKey(this.chainId));
this._bech32Address = key.bech32Address;
this._name = key.name;
this.pubKey = key.pubKey;
// Set the wallet status as loaded after getting all necessary infos.
this._walletStatus = WalletStatus.Loaded;
}
@action
public disconnect(): void {
this._walletStatus = WalletStatus.NotInit;
this.hasInited = false;
this.eventListener.removeEventListener(
"keplr_keystorechange",
this.handleInit
);
this._bech32Address = "";
this._name = "";
this.pubKey = new Uint8Array(0);
}
get walletVersion(): string | undefined {
return this._walletVersion;
}
@computed
get isReadyToSendMsgs(): boolean {
return (
this.walletStatus === WalletStatus.Loaded && this.bech32Address !== ""
);
}
async sendMsgs(
type: string | "unknown",
msgs:
| AminoMsgsOrWithProtoMsgs
| (() => Promise<AminoMsgsOrWithProtoMsgs> | AminoMsgsOrWithProtoMsgs),
memo: string = "",
fee: StdFee,
signOptions?: KeplrSignOptions,
onTxEvents?:
| ((tx: any) => void)
| {
onBroadcastFailed?: (e?: Error) => void;
onBroadcasted?: (txHash: Uint8Array) => void;
onFulfill?: (tx: any) => void;
}
) {
runInAction(() => {
this._isSendingMsg = type;
});
let txHash: Uint8Array;
let signDoc: StdSignDoc;
try {
if (typeof msgs === "function") {
msgs = await msgs();
}
const result = await this.broadcastMsgs(
msgs,
fee,
memo,
signOptions,
this.broadcastMode
);
txHash = result.txHash;
signDoc = result.signDoc;
} catch (e) {
runInAction(() => {
this._isSendingMsg = false;
});
if (this.opts.preTxEvents?.onBroadcastFailed) {
this.opts.preTxEvents.onBroadcastFailed(e);
}
if (
onTxEvents &&
"onBroadcastFailed" in onTxEvents &&
onTxEvents.onBroadcastFailed
) {
onTxEvents.onBroadcastFailed(e);
}
throw e;
}
let onBroadcasted: ((txHash: Uint8Array) => void) | undefined;
let onFulfill: ((tx: any) => void) | undefined;
if (onTxEvents) {
if (typeof onTxEvents === "function") {
onFulfill = onTxEvents;
} else {
onBroadcasted = onTxEvents.onBroadcasted;
onFulfill = onTxEvents.onFulfill;
}
}
if (this.opts.preTxEvents?.onBroadcasted) {
this.opts.preTxEvents.onBroadcasted(txHash);
}
if (onBroadcasted) {
onBroadcasted(txHash);
}
const txTracer = new TendermintTxTracer(
this.chainGetter.getChain(this.chainId).rpc,
"/websocket",
{
wsObject: this.opts.wsObject,
}
);
txTracer.traceTx(txHash).then((tx) => {
txTracer.close();
runInAction(() => {
this._isSendingMsg = false;
});
// After sending tx, the balances is probably changed due to the fee.
for (const feeAmount of signDoc.fee.amount) {
const bal = this.queries.queryBalances
.getQueryBech32Address(this.bech32Address)
.balances.find(
(bal) => bal.currency.coinMinimalDenom === feeAmount.denom
);
if (bal) {
bal.fetch();
}
}
// Always add the tx hash data.
if (tx && !tx.hash) {
tx.hash = Buffer.from(txHash).toString("hex");
}
if (this.opts.preTxEvents?.onFulfill) {
this.opts.preTxEvents.onFulfill(tx);
}
if (onFulfill) {
onFulfill(tx);
}
});
}
async sendToken(
amount: string,
currency: AppCurrency,
recipient: string,
memo: string = "",
stdFee: Partial<StdFee> = {},
signOptions?: KeplrSignOptions,
onTxEvents?:
| ((tx: any) => void)
| {
onBroadcasted?: (txHash: Uint8Array) => void;
onFulfill?: (tx: any) => void;
}
) {
for (let i = 0; i < this.sendTokenFns.length; i++) {
const fn = this.sendTokenFns[i];
if (
await fn(
amount,
currency,
recipient,
memo,
stdFee,
signOptions,
onTxEvents
)
) {
return;
}
}
const denomHelper = new DenomHelper(currency.coinMinimalDenom);
throw new Error(`Unsupported type of currency (${denomHelper.type})`);
}
// Return the tx hash.
protected async broadcastMsgs(
msgs: AminoMsgsOrWithProtoMsgs,
fee: StdFee,
memo: string = "",
signOptions?: KeplrSignOptions,
mode: "block" | "async" | "sync" = "async"
): Promise<{
txHash: Uint8Array;
signDoc: StdSignDoc;
}> {
if (this.walletStatus !== WalletStatus.Loaded) {
throw new Error(`Wallet is not loaded: ${this.walletStatus}`);
}
let aminoMsgs: Msg[];
let protoMsgs: google.protobuf.IAny[] | undefined;
if ("aminoMsgs" in msgs) {
aminoMsgs = msgs.aminoMsgs;
protoMsgs = msgs.protoMsgs;
} else {
aminoMsgs = msgs;
}
if (aminoMsgs.length === 0) {
throw new Error("There is no msg to send");
}
if (
this.hasNoLegacyStdFeature() &&
(!protoMsgs || protoMsgs.length === 0)
) {
throw new Error(
"Chain can't send legecy stdTx. But, proto any type msgs are not provided"
);
}
const account = await BaseAccount.fetchFromRest(
this.instance,
this.bech32Address,
true
);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const keplr = (await this.getKeplr())!;
const signDoc = makeSignDoc(
aminoMsgs,
fee,
this.chainId,
memo,
account.getAccountNumber().toString(),
account.getSequence().toString()
);
const signResponse = await keplr.signAmino(
this.chainId,
this.bech32Address,
signDoc,
signOptions
);
const signedTx = this.hasNoLegacyStdFeature()
? cosmos.tx.v1beta1.TxRaw.encode({
bodyBytes: cosmos.tx.v1beta1.TxBody.encode({
messages: protoMsgs,
memo: signResponse.signed.memo,
}).finish(),
authInfoBytes: cosmos.tx.v1beta1.AuthInfo.encode({
signerInfos: [
{
publicKey: {
type_url: "/cosmos.crypto.secp256k1.PubKey",
value: cosmos.crypto.secp256k1.PubKey.encode({
key: Buffer.from(
signResponse.signature.pub_key.value,
"base64"
),
}).finish(),
},
modeInfo: {
single: {
mode: SignMode.SIGN_MODE_LEGACY_AMINO_JSON,
},
},
sequence: Long.fromString(signResponse.signed.sequence),
},
],
fee: {
amount: signResponse.signed.fee.amount as ICoin[],
gasLimit: Long.fromString(signResponse.signed.fee.gas),
},
}).finish(),
signatures: [Buffer.from(signResponse.signature.signature, "base64")],
}).finish()
: makeStdTx(signResponse.signed, signResponse.signature);
return {
txHash: await keplr.sendTx(this.chainId, signedTx, mode as BroadcastMode),
signDoc: signResponse.signed,
};
}
get instance(): AxiosInstance {
const chainInfo = this.chainGetter.getChain(this.chainId);
return Axios.create({
...{
baseURL: chainInfo.rest,
},
...chainInfo.restConfig,
});
}
get walletStatus(): WalletStatus {
return this._walletStatus;
}
get name(): string {
return this._name;
}
get bech32Address(): string {
return this._bech32Address;
}
get isSendingMsg(): string | boolean {
return this._isSendingMsg;
}
protected get queries(): DeepReadonly<QueriesSetBase & Queries> {
return this.queriesStore.get(this.chainId);
}
protected hasNoLegacyStdFeature(): boolean {
const chainInfo = this.chainGetter.getChain(this.chainId);
return (
chainInfo.features != null &&
chainInfo.features.includes("no-legacy-stdTx")
);
}
} | the_stack |
import WebpackConfigComposer from "../../src/index";
import { expect } from "chai";
import fooPartial from "../fixtures/partial/foo";
import barPartial from "../fixtures/partial/bar";
import loaderPartial from "../fixtures/partial/loader";
// eslint-disable-next-line @typescript-eslint/no-var-requires
const _ = require("lodash");
import { FooPlugin } from "../fixtures/plugins/foo-plugin";
import Partial from "../../src/partial";
import CONSTANT from "../../src/constants";
const { PARTIALS } = CONSTANT;
/* eslint-disable max-statements */
describe("composer", () => {
it("should accept partials and generate config", () => {
const composer = new WebpackConfigComposer({
partials: {
test: {
config: {
testFoo: "test",
},
},
},
profiles: {
b: {
partials: {
bar: {
order: 200,
},
test: {
order: 300,
},
},
},
a: {
partials: {
foo: {
order: "100",
},
},
},
},
});
composer.addPartials([fooPartial, barPartial]);
expect(composer.profiles).to.have.keys("a", "b");
/* eslint-disable no-unused-expressions */
expect(composer.getProfile("a")).to.exist;
expect(composer.getPartial("test")).to.exist;
/* eslint-enable no-unused-expressions */
const config = composer.compose({}, "a", "b");
expect(config.testFoo).to.equal("test");
});
it("should keep custom props", () => {
const composer = new WebpackConfigComposer({
partials: {
test: {
config: {
_test: "hello",
foo: "foo",
},
},
},
});
const config = composer.compose(
{ keepCustomProps: true },
{
partials: { test: {} },
},
{} // test empty profile
);
expect(config._test).to.equal("hello");
});
it("should use currentConfig provided", () => {
const composer = new WebpackConfigComposer({
partials: {
test: {
config: {
_test: "hello",
foo: "foo",
},
},
},
});
const config = composer.compose(
{ currentConfig: { hello: "world" } },
{
partials: { test: {} },
}
);
expect(config.hello).to.equal("world");
});
it("instance should have deleteCustomProps", () => {
const composer = new WebpackConfigComposer({});
expect(
composer.deleteCustomProps({
_name: "test",
hello: "world",
})
).to.deep.equal({ hello: "world" });
});
it("should skip adding __name to plugins", () => {
const composer = new WebpackConfigComposer({});
composer.addPartials({
foo: {
config: {
plugins: [new FooPlugin()],
},
},
});
const config = composer.compose(
{ skipNamePlugins: true },
{
partials: {
foo: {},
},
}
);
expect(config.plugins[0].__name).to.equal(undefined);
});
it("should call a partial config if it's a function", () => {
const composer = new WebpackConfigComposer({});
composer.addPartials([fooPartial, loaderPartial]);
const config = composer.compose({}, [
{
partials: {
foo: {
order: "100",
},
},
},
{
partials: {
loader: {},
badButDisabled: {
enable: false,
},
},
},
]);
expect(config.module.rules[0]).to.equal("loader-rule1");
});
it("should call return function twice to get final partial config", () => {
const composer = new WebpackConfigComposer({});
composer.addPartials([
fooPartial,
{
loader: {
// eslint-disable-next-line @typescript-eslint/no-var-requires
config: () => require("../fixtures/partial/loader").default.loader.config,
},
},
]);
const config = composer.compose({}, { partials: { loader: {} } });
expect(config.module.rules[0]).to.equal("loader-rule1");
});
it.skip("should throw if a partial config cannot be processed", () => {
const composer = new WebpackConfigComposer({});
composer.addPartials({
test: {
config: true,
},
});
expect(() => composer.compose({}, { partials: { test: {} } })).to.throw();
});
it("should allow a config function to apply the config by returning nothing", () => {
const composer = new WebpackConfigComposer({});
composer.addPartials([
fooPartial,
{
loader: {
config: (options) => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const config = require("../fixtures/partial/loader").default.loader.config(options);
_.merge(options.currentConfig, config);
},
},
},
]);
const config = composer.compose({}, { partials: { loader: {} } });
expect(config.module.rules[0]).to.equal("loader-rule1");
});
it("compose should correct config module when meta is enabled", () => {
const composer = new WebpackConfigComposer({});
composer.addPartials([
fooPartial,
{
loader: {
config: (options) => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const config = require("../fixtures/partial/loader").default.loader.config(options);
_.merge(options.currentConfig, config);
},
},
},
]);
const config = composer.compose({ meta: true }, { partials: { loader: {} } });
expect(config.config).to.eql({
module: {
rules: ["loader-rule1"],
},
});
});
it("instance should created with null input", () => {
const composer = new WebpackConfigComposer(null);
// eslint-disable-next-line no-unused-expressions
expect(composer).to.exist;
});
describe("addProfiles", () => {
it("should accept multiple profiles", () => {
const composer = new WebpackConfigComposer({});
composer.addProfiles({ a: { partials: {} }, b: { partials: {} } });
expect(composer.profiles).to.have.keys("a", "b");
});
it("should accept profiles as an array", () => {
const composer = new WebpackConfigComposer({});
composer.addProfiles([{ a: { partials: {} }, b: { partials: {} } }]);
expect(composer.profiles).to.have.keys("a", "b");
});
});
describe("addProfile", () => {
it("should take list of partial names for new profile", () => {
const composer = new WebpackConfigComposer({});
composer.addProfile("test", "a");
const prof = composer.getProfile("test");
expect(prof.partials).to.deep.equal({
a: {},
});
});
it("should add profile with an object of partials", () => {
const composer = new WebpackConfigComposer({});
composer.addProfile("test", {
a: {},
b: {},
c: {},
});
const prof = composer.getProfile("test");
expect(prof.partials).to.deep.equal({
a: {},
b: {},
c: {},
});
});
});
describe("addPartialToProfile", () => {
it("should create profile if it doesn't exist", () => {
const composer = new WebpackConfigComposer({});
composer.addPartialToProfile("user", "test", { plugins: [] }, {});
const user = composer.getPartial("user");
// eslint-disable-next-line no-unused-expressions
expect(user).to.exist;
expect(user.config).to.deep.equal({ plugins: [] });
expect(user.options).to.deep.equal({});
// eslint-disable-next-line no-unused-expressions
expect(composer.getProfile("test")).to.exist;
});
it("should add the partial", () => {
const composer = new WebpackConfigComposer({});
composer.addPartialToProfile("user", "test", { plugins: [] }, {});
const user = composer.getPartial("user");
// eslint-disable-next-line no-unused-expressions
expect(user).to.exist;
expect(user.config).to.deep.equal({ plugins: [] });
expect(user.options).to.deep.equal({});
});
it("should use existing profile", () => {
const composer = new WebpackConfigComposer({});
composer.addProfile("test", "foo");
composer.addPartialToProfile("user", "test", { plugins: [] }, {});
const prof = composer.getProfile("test");
// eslint-disable-next-line no-unused-expressions
expect(prof).to.exist;
expect(prof.getPartial("foo")).to.deep.equal({});
});
});
describe("addPartials", () => {
it("should add new partial as class intance", () => {
const composer = new WebpackConfigComposer({});
composer.addPartials(fooPartial);
const foo = composer.getPartial("foo");
expect(foo.config).to.deep.equal(fooPartial.foo.config);
// test class set/get methods
foo.config = {};
expect(foo.config).to.deep.equal({});
expect(foo.options).to.deep.equal({});
foo.options = { a: 1 };
expect(foo.options).to.deep.equal({ a: 1 });
});
it("should add new partials as an array", () => {
const composer = new WebpackConfigComposer({});
composer.addPartials([fooPartial, barPartial]);
expect(composer.getPartial("foo").config).to.deep.equal(fooPartial.foo.config);
expect(composer.getPartial("bar").config).to.deep.equal(barPartial.bar.config);
});
it("should merge into existing partial", () => {
const composer = new WebpackConfigComposer({
partials: [fooPartial, barPartial],
});
composer.addPartials({
foo: {
config: {
plugins: ["fooTest"],
},
addOptions: {
concatArray: "tail",
},
},
bar: {
config: {
plugins: ["barTest"],
},
addOptions: {
concatArray: "head",
},
},
});
expect(composer.partials.foo.config.plugins[1]).to.equal("fooTest");
expect(composer.partials.bar.config.plugins[0]).to.equal("barTest");
});
it("should repalce existing partial", () => {
const composer = new WebpackConfigComposer({
partials: [fooPartial, barPartial],
});
composer.addPartials({
foo: {
config: {
plugins: ["fooTest"],
},
addOptions: {
method: "replace",
concatArray: "no",
},
},
});
composer.addPartial(
"bar",
{
plugins: ["barTest"],
},
{
concatArray: "head",
}
);
expect(composer.partials.foo.config.plugins.length).to.equal(1);
expect(composer.partials.foo.config.plugins[0]).to.equal("fooTest");
expect(composer.partials.bar.config.plugins[0]).to.equal("barTest");
});
it("should addPartial when given name does not exist but options having replace method", () => {
const composer = new WebpackConfigComposer({});
composer.addPartial(
"bar",
{
plugins: ["barTest"],
},
{
method: "replace",
}
);
expect(composer[PARTIALS].bar).to.deep.equal(new Partial("bar", { plugins: ["barTest"] }));
});
it("should addPartial when given name does not exist but options having replace method", () => {
const composer = new WebpackConfigComposer({});
const testPartialInstance = new Partial("foo", {});
composer._addPartial("bar", testPartialInstance, {
method: "replace",
});
expect(composer[PARTIALS].bar).to.deep.equal(testPartialInstance);
});
});
describe("enablePartial", () => {
it("should find partial enabled", () => {
const testName = "test_9527";
const composer = new WebpackConfigComposer({});
expect(composer.getPartial(testName)).to.equal(undefined);
composer.addPartial(testName, { foor: "bar" }, null);
expect(composer.getPartial(testName).enable).to.equal(undefined);
composer.enablePartial(testName, true);
expect(composer.getPartial(testName).enable).to.equal(true);
});
it("should find partial not enabled", () => {
const testName = "test_9527";
const composer = new WebpackConfigComposer({});
composer.addPartial(testName, { foor: "bar" }, null);
expect(composer.getPartial(testName).enable).to.equal(undefined);
composer.enablePartial("abc", true);
expect(composer.getPartial(testName).enable).to.equal(undefined);
});
});
describe("replacePartial", () => {
it("should replacePartial", () => {
const testName = "test_9528";
const composer = new WebpackConfigComposer({});
expect(composer.getPartial(testName)).to.equal(undefined);
composer.addPartial(testName, { foo1: "bar1" }, null);
expect(composer.getPartial(testName)).to.deep.equal(
new Partial(testName, { config: { foo1: "bar1" } })
);
composer.replacePartial(testName, { foo2: "bar2" }, null);
expect(composer.getPartial(testName)).to.deep.equal(
new Partial(testName, { config: { foo2: "bar2" } })
);
});
});
});
/* eslint-enable max-statements */ | the_stack |
import { Constraint, Operator } from "./constraint";
import { Expression } from "./expression";
import { createMap, IMap } from "./maptype";
import { Strength } from "./strength";
import { Variable } from "./variable";
/**
* The constraint solver class.
*
* @class
*/
export
class Solver {
/**
* Construct a new Solver.
*/
constructor() { }
/**
* Creates and add a constraint to the solver.
*
* @param {Expression|Variable} lhs Left hand side of the expression
* @param {Operator} operator Operator
* @param {Expression|Variable|Number} rhs Right hand side of the expression
* @param {Number} [strength=Strength.required] Strength
*/
public createConstraint(
lhs: Expression|Variable,
operator: Operator,
rhs: Expression|Variable|number,
strength: number = Strength.required): Constraint {
let cn = new Constraint(lhs, operator, rhs, strength);
this.addConstraint(cn);
return cn;
}
/**
* Add a constraint to the solver.
*
* @param {Constraint} constraint Constraint to add to the solver
*/
public addConstraint(constraint: Constraint): void {
let cnPair = this._cnMap.find(constraint);
if (cnPair !== undefined) {
throw new Error("duplicate constraint");
}
// Creating a row causes symbols to be reserved for the variables
// in the constraint. If this method exits with an exception,
// then its possible those variables will linger in the var map.
// Since its likely that those variables will be used in other
// constraints and since exceptional conditions are uncommon,
// i'm not too worried about aggressive cleanup of the var map.
let data = this._createRow( constraint );
let row = data.row;
let tag = data.tag;
let subject = this._chooseSubject( row, tag );
// If chooseSubject couldnt find a valid entering symbol, one
// last option is available if the entire row is composed of
// dummy variables. If the constant of the row is zero, then
// this represents redundant constraints and the new dummy
// marker can enter the basis. If the constant is non-zero,
// then it represents an unsatisfiable constraint.
if ( subject.type() === SymbolType.Invalid && row.allDummies() ) {
if ( !nearZero( row.constant() ) ) {
throw new Error( "unsatisfiable constraint" );
} else {
subject = tag.marker;
}
}
// If an entering symbol still isn't found, then the row must
// be added using an artificial variable. If that fails, then
// the row represents an unsatisfiable constraint.
if ( subject.type() === SymbolType.Invalid ) {
if ( !this._addWithArtificialVariable( row ) ) {
throw new Error( "unsatisfiable constraint" );
}
} else {
row.solveFor( subject );
this._substitute( subject, row );
this._rowMap.insert( subject, row );
}
this._cnMap.insert( constraint, tag );
// Optimizing after each constraint is added performs less
// aggregate work due to a smaller average system size. It
// also ensures the solver remains in a consistent state.
this._optimize( this._objective );
}
/**
* Remove a constraint from the solver.
*
* @param {Constraint} constraint Constraint to remove from the solver
*/
public removeConstraint( constraint: Constraint ): void {
let cnPair = this._cnMap.erase( constraint );
if ( cnPair === undefined ) {
throw new Error( "unknown constraint" );
}
// Remove the error effects from the objective function
// *before* pivoting, or substitutions into the objective
// will lead to incorrect solver results.
this._removeConstraintEffects( constraint, cnPair.second );
// If the marker is basic, simply drop the row. Otherwise,
// pivot the marker into the basis and then drop the row.
let marker = cnPair.second.marker;
let rowPair = this._rowMap.erase( marker );
if ( rowPair === undefined ) {
let leaving = this._getMarkerLeavingSymbol( marker );
if ( leaving.type() === SymbolType.Invalid ) {
throw new Error( "failed to find leaving row" );
}
rowPair = this._rowMap.erase( leaving );
rowPair.second.solveForEx( leaving, marker );
this._substitute( marker, rowPair.second );
}
// Optimizing after each constraint is removed ensures that the
// solver remains consistent. It makes the solver api easier to
// use at a small tradeoff for speed.
this._optimize( this._objective );
}
/**
* Test whether the solver contains the constraint.
*
* @param {Constraint} constraint Constraint to test for
* @return {Bool} true or false
*/
public hasConstraint( constraint: Constraint ): boolean {
return this._cnMap.contains( constraint );
}
/**
* Add an edit variable to the solver.
*
* @param {Variable} variable Edit variable to add to the solver
* @param {Number} strength Strength, should be less than `Strength.required`
*/
public addEditVariable( variable: Variable, strength: number ): void {
let editPair = this._editMap.find( variable );
if ( editPair !== undefined ) {
throw new Error( "duplicate edit variable" );
}
strength = Strength.clip( strength );
if ( strength === Strength.required ) {
throw new Error( "bad required strength" );
}
let expr = new Expression( variable );
let cn = new Constraint( expr, Operator.Eq, undefined, strength );
this.addConstraint( cn );
let tag = this._cnMap.find( cn ).second;
let info = { tag, constraint: cn, constant: 0.0 };
this._editMap.insert( variable, info );
}
/**
* Remove an edit variable from the solver.
*
* @param {Variable} variable Edit variable to remove from the solver
*/
public removeEditVariable( variable: Variable ): void {
let editPair = this._editMap.erase( variable );
if ( editPair === undefined ) {
throw new Error( "unknown edit variable" );
}
this.removeConstraint( editPair.second.constraint );
}
/**
* Test whether the solver contains the edit variable.
*
* @param {Variable} variable Edit variable to test for
* @return {Bool} true or false
*/
public hasEditVariable( variable: Variable ): boolean {
return this._editMap.contains( variable );
}
/**
* Suggest the value of an edit variable.
*
* @param {Variable} variable Edit variable to suggest a value for
* @param {Number} value Suggested value
*/
public suggestValue( variable: Variable, value: number ): void {
let editPair = this._editMap.find( variable );
if ( editPair === undefined ) {
throw new Error( "unknown edit variable" );
}
let rows = this._rowMap;
let info = editPair.second;
let delta = value - info.constant;
info.constant = value;
// Check first if the positive error variable is basic.
let marker = info.tag.marker;
let rowPair = rows.find( marker );
if ( rowPair !== undefined ) {
if ( rowPair.second.add( -delta ) < 0.0 ) {
this._infeasibleRows.push( marker );
}
this._dualOptimize();
return;
}
// Check next if the negative error variable is basic.
let other = info.tag.other;
rowPair = rows.find( other );
if ( rowPair !== undefined ) {
if ( rowPair.second.add( delta ) < 0.0 ) {
this._infeasibleRows.push( other );
}
this._dualOptimize();
return;
}
// Otherwise update each row where the error variables exist.
for ( let i = 0, n = rows.size(); i < n; ++i ) {
let rowPair = rows.itemAt( i );
let row = rowPair.second;
let coeff = row.coefficientFor( marker );
if ( coeff !== 0.0 && row.add( delta * coeff ) < 0.0 &&
rowPair.first.type() !== SymbolType.External ) {
this._infeasibleRows.push( rowPair.first );
}
}
this._dualOptimize();
}
/**
* Update the values of the variables.
*/
public updateVariables(): void {
let vars = this._varMap;
let rows = this._rowMap;
for ( let i = 0, n = vars.size(); i < n; ++i ) {
let pair = vars.itemAt( i );
let rowPair = rows.find( pair.second );
if ( rowPair !== undefined ) {
pair.first.setValue( rowPair.second.constant() );
} else {
pair.first.setValue( 0.0 );
}
}
}
/**
* Get the symbol for the given variable.
*
* If a symbol does not exist for the variable, one will be created.
* @private
*/
private _getVarSymbol( variable: Variable ): Symbol {
let factory = () => this._makeSymbol( SymbolType.External );
return this._varMap.setDefault( variable, factory ).second;
}
/**
* Create a new Row object for the given constraint.
*
* The terms in the constraint will be converted to cells in the row.
* Any term in the constraint with a coefficient of zero is ignored.
* This method uses the `_getVarSymbol` method to get the symbol for
* the variables added to the row. If the symbol for a given cell
* variable is basic, the cell variable will be substituted with the
* basic row.
*
* The necessary slack and error variables will be added to the row.
* If the constant for the row is negative, the sign for the row
* will be inverted so the constant becomes positive.
*
* Returns the created Row and the tag for tracking the constraint.
* @private
*/
private _createRow( constraint: Constraint ): IRowCreation {
let expr = constraint.expression();
let row = new Row( expr.constant() );
// Substitute the current basic variables into the row.
let terms = expr.terms();
for ( let i = 0, n = terms.size(); i < n; ++i ) {
let termPair = terms.itemAt( i );
if ( !nearZero( termPair.second ) ) {
let symbol = this._getVarSymbol( termPair.first );
let basicPair = this._rowMap.find( symbol );
if ( basicPair !== undefined ) {
row.insertRow( basicPair.second, termPair.second );
} else {
row.insertSymbol( symbol, termPair.second );
}
}
}
// Add the necessary slack, error, and dummy variables.
let objective = this._objective;
let strength = constraint.strength();
let tag = { marker: INVALID_SYMBOL, other: INVALID_SYMBOL };
switch ( constraint.op() ) {
case Operator.Le:
case Operator.Ge:
{
let coeff = constraint.op() === Operator.Le ? 1.0 : -1.0;
let slack = this._makeSymbol( SymbolType.Slack );
tag.marker = slack;
row.insertSymbol( slack, coeff );
if ( strength < Strength.required ) {
let error = this._makeSymbol( SymbolType.Error );
tag.other = error;
row.insertSymbol( error, -coeff );
objective.insertSymbol( error, strength );
}
break;
}
case Operator.Eq:
{
if ( strength < Strength.required ) {
let errplus = this._makeSymbol( SymbolType.Error );
let errminus = this._makeSymbol( SymbolType.Error );
tag.marker = errplus;
tag.other = errminus;
row.insertSymbol( errplus, -1.0 ); // v = eplus - eminus
row.insertSymbol( errminus, 1.0 ); // v - eplus + eminus = 0
objective.insertSymbol( errplus, strength );
objective.insertSymbol( errminus, strength );
} else {
let dummy = this._makeSymbol( SymbolType.Dummy );
tag.marker = dummy;
row.insertSymbol( dummy );
}
break;
}
}
// Ensure the row has a positive constant.
if ( row.constant() < 0.0 ) {
row.reverseSign();
}
return { row, tag };
}
/**
* Choose the subject for solving for the row.
*
* This method will choose the best subject for using as the solve
* target for the row. An invalid symbol will be returned if there
* is no valid target.
*
* The symbols are chosen according to the following precedence:
*
* 1) The first symbol representing an external variable.
* 2) A negative slack or error tag variable.
*
* If a subject cannot be found, an invalid symbol will be returned.
*
* @private
*/
private _chooseSubject( row: Row, tag: ITag ): Symbol {
let cells = row.cells();
for ( let i = 0, n = cells.size(); i < n; ++i ) {
let pair = cells.itemAt( i );
if ( pair.first.type() === SymbolType.External ) {
return pair.first;
}
}
let type = tag.marker.type();
if ( type === SymbolType.Slack || type === SymbolType.Error ) {
if ( row.coefficientFor( tag.marker ) < 0.0 ) {
return tag.marker;
}
}
type = tag.other.type();
if ( type === SymbolType.Slack || type === SymbolType.Error ) {
if ( row.coefficientFor( tag.other ) < 0.0 ) {
return tag.other;
}
}
return INVALID_SYMBOL;
}
/**
* Add the row to the tableau using an artificial variable.
*
* This will return false if the constraint cannot be satisfied.
*
* @private
*/
private _addWithArtificialVariable( row: Row ): boolean {
// Create and add the artificial variable to the tableau.
let art = this._makeSymbol( SymbolType.Slack );
this._rowMap.insert( art, row.copy() );
this._artificial = row.copy();
// Optimize the artificial objective. This is successful
// only if the artificial objective is optimized to zero.
this._optimize( this._artificial );
let success = nearZero( this._artificial.constant() );
this._artificial = null;
// If the artificial variable is basic, pivot the row so that
// it becomes non-basic. If the row is constant, exit early.
let pair = this._rowMap.erase( art );
if ( pair !== undefined ) {
let basicRow = pair.second;
if ( basicRow.isConstant() ) {
return success;
}
let entering = this._anyPivotableSymbol( basicRow );
if ( entering.type() === SymbolType.Invalid ) {
return false; // unsatisfiable (will this ever happen?)
}
basicRow.solveForEx( art, entering );
this._substitute( entering, basicRow );
this._rowMap.insert( entering, basicRow );
}
// Remove the artificial variable from the tableau.
let rows = this._rowMap;
for ( let i = 0, n = rows.size(); i < n; ++i ) {
rows.itemAt( i ).second.removeSymbol( art );
}
this._objective.removeSymbol( art );
return success;
}
/**
* Substitute the parametric symbol with the given row.
*
* This method will substitute all instances of the parametric symbol
* in the tableau and the objective function with the given row.
*
* @private
*/
private _substitute( symbol: Symbol, row: Row ): void {
let rows = this._rowMap;
for ( let i = 0, n = rows.size(); i < n; ++i ) {
let pair = rows.itemAt( i );
pair.second.substitute( symbol, row );
if ( pair.second.constant() < 0.0 &&
pair.first.type() !== SymbolType.External ) {
this._infeasibleRows.push( pair.first );
}
}
this._objective.substitute( symbol, row );
if ( this._artificial ) {
this._artificial.substitute( symbol, row );
}
}
/**
* Optimize the system for the given objective function.
*
* This method performs iterations of Phase 2 of the simplex method
* until the objective function reaches a minimum.
*
* @private
*/
private _optimize( objective: Row ): void {
while ( true ) {
let entering = this._getEnteringSymbol( objective );
if ( entering.type() === SymbolType.Invalid ) {
return;
}
let leaving = this._getLeavingSymbol( entering );
if ( leaving.type() === SymbolType.Invalid ) {
throw new Error( "the objective is unbounded" );
}
// pivot the entering symbol into the basis
let row = this._rowMap.erase( leaving ).second;
row.solveForEx( leaving, entering );
this._substitute( entering, row );
this._rowMap.insert( entering, row );
}
}
/**
* Optimize the system using the dual of the simplex method.
*
* The current state of the system should be such that the objective
* function is optimal, but not feasible. This method will perform
* an iteration of the dual simplex method to make the solution both
* optimal and feasible.
*
* @private
*/
private _dualOptimize(): void {
let rows = this._rowMap;
let infeasible = this._infeasibleRows;
while ( infeasible.length !== 0 ) {
let leaving = infeasible.pop();
let pair = rows.find( leaving );
if ( pair !== undefined && pair.second.constant() < 0.0 ) {
let entering = this._getDualEnteringSymbol( pair.second );
if ( entering.type() === SymbolType.Invalid ) {
throw new Error( "dual optimize failed" );
}
// pivot the entering symbol into the basis
let row = pair.second;
rows.erase( leaving );
row.solveForEx( leaving, entering );
this._substitute( entering, row );
rows.insert( entering, row );
}
}
}
/**
* Compute the entering variable for a pivot operation.
*
* This method will return first symbol in the objective function which
* is non-dummy and has a coefficient less than zero. If no symbol meets
* the criteria, it means the objective function is at a minimum, and an
* invalid symbol is returned.
*
* @private
*/
private _getEnteringSymbol( objective: Row ): Symbol {
let cells = objective.cells();
for ( let i = 0, n = cells.size(); i < n; ++i ) {
let pair = cells.itemAt( i );
let symbol = pair.first;
if ( pair.second < 0.0 && symbol.type() !== SymbolType.Dummy ) {
return symbol;
}
}
return INVALID_SYMBOL;
}
/**
* Compute the entering symbol for the dual optimize operation.
*
* This method will return the symbol in the row which has a positive
* coefficient and yields the minimum ratio for its respective symbol
* in the objective function. The provided row *must* be infeasible.
* If no symbol is found which meats the criteria, an invalid symbol
* is returned.
*
* @private
*/
private _getDualEnteringSymbol( row: Row ): Symbol {
let ratio = Number.MAX_VALUE;
let entering = INVALID_SYMBOL;
let cells = row.cells();
for ( let i = 0, n = cells.size(); i < n; ++i ) {
let pair = cells.itemAt( i );
let symbol = pair.first;
let c = pair.second;
if ( c > 0.0 && symbol.type() !== SymbolType.Dummy ) {
let coeff = this._objective.coefficientFor( symbol );
let r = coeff / c;
if ( r < ratio ) {
ratio = r;
entering = symbol;
}
}
}
return entering;
}
/**
* Compute the symbol for pivot exit row.
*
* This method will return the symbol for the exit row in the row
* map. If no appropriate exit symbol is found, an invalid symbol
* will be returned. This indicates that the objective function is
* unbounded.
*
* @private
*/
private _getLeavingSymbol( entering: Symbol ): Symbol {
let ratio = Number.MAX_VALUE;
let found = INVALID_SYMBOL;
let rows = this._rowMap;
for ( let i = 0, n = rows.size(); i < n; ++i ) {
let pair = rows.itemAt( i );
let symbol = pair.first;
if ( symbol.type() !== SymbolType.External ) {
let row = pair.second;
let temp = row.coefficientFor( entering );
if ( temp < 0.0 ) {
let temp_ratio = -row.constant() / temp;
if ( temp_ratio < ratio ) {
ratio = temp_ratio;
found = symbol;
}
}
}
}
return found;
}
/**
* Compute the leaving symbol for a marker variable.
*
* This method will return a symbol corresponding to a basic row
* which holds the given marker variable. The row will be chosen
* according to the following precedence:
*
* 1) The row with a restricted basic varible and a negative coefficient
* for the marker with the smallest ratio of -constant / coefficient.
*
* 2) The row with a restricted basic variable and the smallest ratio
* of constant / coefficient.
*
* 3) The last unrestricted row which contains the marker.
*
* If the marker does not exist in any row, an invalid symbol will be
* returned. This indicates an internal solver error since the marker
* *should* exist somewhere in the tableau.
*
* @private
*/
private _getMarkerLeavingSymbol( marker: Symbol ): Symbol {
let dmax = Number.MAX_VALUE;
let r1 = dmax;
let r2 = dmax;
let invalid = INVALID_SYMBOL;
let first = invalid;
let second = invalid;
let third = invalid;
let rows = this._rowMap;
for ( let i = 0, n = rows.size(); i < n; ++i ) {
let pair = rows.itemAt( i );
let row = pair.second;
let c = row.coefficientFor( marker );
if ( c === 0.0 ) {
continue;
}
let symbol = pair.first;
if ( symbol.type() === SymbolType.External ) {
third = symbol;
} else if ( c < 0.0 ) {
let r = -row.constant() / c;
if ( r < r1 ) {
r1 = r;
first = symbol;
}
} else {
let r = row.constant() / c;
if ( r < r2 ) {
r2 = r;
second = symbol;
}
}
}
if ( first !== invalid ) {
return first;
}
if ( second !== invalid ) {
return second;
}
return third;
}
/**
* Remove the effects of a constraint on the objective function.
*
* @private
*/
private _removeConstraintEffects( cn: Constraint, tag: ITag ): void {
if ( tag.marker.type() === SymbolType.Error ) {
this._removeMarkerEffects( tag.marker, cn.strength() );
}
if ( tag.other.type() === SymbolType.Error ) {
this._removeMarkerEffects( tag.other, cn.strength() );
}
}
/**
* Remove the effects of an error marker on the objective function.
*
* @private
*/
private _removeMarkerEffects( marker: Symbol, strength: number ): void {
let pair = this._rowMap.find( marker );
if ( pair !== undefined ) {
this._objective.insertRow( pair.second, -strength );
} else {
this._objective.insertSymbol( marker, -strength );
}
}
/**
* Get the first Slack or Error symbol in the row.
*
* If no such symbol is present, an invalid symbol will be returned.
*
* @private
*/
private _anyPivotableSymbol( row: Row ): Symbol {
let cells = row.cells();
for ( let i = 0, n = cells.size(); i < n; ++i ) {
let pair = cells.itemAt( i );
let type = pair.first.type();
if ( type === SymbolType.Slack || type === SymbolType.Error ) {
return pair.first;
}
}
return INVALID_SYMBOL;
}
/**
* Returns a new Symbol of the given type.
*
* @private
*/
private _makeSymbol( type: SymbolType ): Symbol {
return new Symbol( type, this._idTick++ );
}
private _cnMap = createCnMap();
private _rowMap = createRowMap();
private _varMap = createVarMap();
private _editMap = createEditMap();
private _infeasibleRows: Symbol[] = [];
private _objective: Row = new Row();
private _artificial: Row = null;
private _idTick: number = 0;
}
/**
* Test whether a value is approximately zero.
* @private
*/
function nearZero( value: number ): boolean {
let eps = 1.0e-8;
return value < 0.0 ? -value < eps : value < eps;
}
/**
* The internal interface of a tag value.
*/
interface ITag {
marker: Symbol;
other: Symbol;
}
/**
* The internal interface of an edit info object.
*/
interface IEditInfo {
tag: ITag;
constraint: Constraint;
constant: number;
}
/**
* The internal interface for returning created row data.
*/
interface IRowCreation {
row: Row;
tag: ITag;
}
/**
* An internal function for creating a constraint map.
* @private
*/
function createCnMap(): IMap<Constraint, ITag> {
return createMap<Constraint, ITag>();
}
/**
* An internal function for creating a row map.
* @private
*/
function createRowMap(): IMap<Symbol, Row> {
return createMap<Symbol, Row>();
}
/**
* An internal function for creating a variable map.
* @private
*/
function createVarMap(): IMap<Variable, Symbol> {
return createMap<Variable, Symbol>();
}
/**
* An internal function for creating an edit map.
* @private
*/
function createEditMap(): IMap<Variable, IEditInfo> {
return createMap<Variable, IEditInfo>();
}
/**
* An enum defining the available symbol types.
* @private
*/
enum SymbolType {
Invalid,
External,
Slack,
Error,
Dummy,
}
/**
* An internal class representing a symbol in the solver.
* @private
*/
class Symbol {
/**
* Construct a new Symbol
*
* @param [type] The type of the symbol.
* @param [id] The unique id number of the symbol.
*/
constructor( type: SymbolType, id: number ) {
this._id = id;
this._type = type;
}
/**
* Returns the unique id number of the symbol.
*/
public id(): number {
return this._id;
}
/**
* Returns the type of the symbol.
*/
public type(): SymbolType {
return this._type;
}
private _id: number;
private _type: SymbolType;
}
/**
* A static invalid symbol
* @private
*/
let INVALID_SYMBOL = new Symbol( SymbolType.Invalid, -1 );
/**
* An internal row class used by the solver.
* @private
*/
class Row {
/**
* Construct a new Row.
*/
constructor( constant: number = 0.0 ) {
this._constant = constant;
}
/**
* Returns the mapping of symbols to coefficients.
*/
public cells(): IMap<Symbol, number> {
return this._cellMap;
}
/**
* Returns the constant for the row.
*/
public constant(): number {
return this._constant;
}
/**
* Returns true if the row is a constant value.
*/
public isConstant(): boolean {
return this._cellMap.empty();
}
/**
* Returns true if the Row has all dummy symbols.
*/
public allDummies(): boolean {
let cells = this._cellMap;
for ( let i = 0, n = cells.size(); i < n; ++i ) {
let pair = cells.itemAt( i );
if ( pair.first.type() !== SymbolType.Dummy ) {
return false;
}
}
return true;
}
/**
* Create a copy of the row.
*/
public copy(): Row {
let theCopy = new Row( this._constant );
theCopy._cellMap = this._cellMap.copy();
return theCopy;
}
/**
* Add a constant value to the row constant.
*
* Returns the new value of the constant.
*/
public add( value: number ): number {
return this._constant += value;
}
/**
* Insert the symbol into the row with the given coefficient.
*
* If the symbol already exists in the row, the coefficient
* will be added to the existing coefficient. If the resulting
* coefficient is zero, the symbol will be removed from the row.
*/
public insertSymbol( symbol: Symbol, coefficient: number = 1.0 ): void {
let pair = this._cellMap.setDefault( symbol, () => 0.0 );
if ( nearZero( pair.second += coefficient ) ) {
this._cellMap.erase( symbol );
}
}
/**
* Insert a row into this row with a given coefficient.
*
* The constant and the cells of the other row will be
* multiplied by the coefficient and added to this row. Any
* cell with a resulting coefficient of zero will be removed
* from the row.
*/
public insertRow( other: Row, coefficient: number = 1.0 ): void {
this._constant += other._constant * coefficient;
let cells = other._cellMap;
for ( let i = 0, n = cells.size(); i < n; ++i ) {
let pair = cells.itemAt( i );
this.insertSymbol( pair.first, pair.second * coefficient );
}
}
/**
* Remove a symbol from the row.
*/
public removeSymbol( symbol: Symbol ): void {
this._cellMap.erase( symbol );
}
/**
* Reverse the sign of the constant and cells in the row.
*/
public reverseSign(): void {
this._constant = -this._constant;
let cells = this._cellMap;
for ( let i = 0, n = cells.size(); i < n; ++i ) {
let pair = cells.itemAt( i );
pair.second = -pair.second;
}
}
/**
* Solve the row for the given symbol.
*
* This method assumes the row is of the form
* a * x + b * y + c = 0 and (assuming solve for x) will modify
* the row to represent the right hand side of
* x = -b/a * y - c / a. The target symbol will be removed from
* the row, and the constant and other cells will be multiplied
* by the negative inverse of the target coefficient.
*
* The given symbol *must* exist in the row.
*/
public solveFor( symbol: Symbol ): void {
let cells = this._cellMap;
let pair = cells.erase( symbol );
let coeff = -1.0 / pair.second;
this._constant *= coeff;
for ( let i = 0, n = cells.size(); i < n; ++i ) {
cells.itemAt( i ).second *= coeff;
}
}
/**
* Solve the row for the given symbols.
*
* This method assumes the row is of the form
* x = b * y + c and will solve the row such that
* y = x / b - c / b. The rhs symbol will be removed from the
* row, the lhs added, and the result divided by the negative
* inverse of the rhs coefficient.
*
* The lhs symbol *must not* exist in the row, and the rhs
* symbol must* exist in the row.
*/
public solveForEx( lhs: Symbol, rhs: Symbol ): void {
this.insertSymbol( lhs, -1.0 );
this.solveFor( rhs );
}
/**
* Returns the coefficient for the given symbol.
*/
public coefficientFor( symbol: Symbol ): number {
let pair = this._cellMap.find( symbol );
return pair !== undefined ? pair.second : 0.0;
}
/**
* Substitute a symbol with the data from another row.
*
* Given a row of the form a * x + b and a substitution of the
* form x = 3 * y + c the row will be updated to reflect the
* expression 3 * a * y + a * c + b.
*
* If the symbol does not exist in the row, this is a no-op.
*/
public substitute( symbol: Symbol, row: Row ): void {
let pair = this._cellMap.erase( symbol );
if ( pair !== undefined ) {
this.insertRow( row, pair.second );
}
}
private _cellMap = createMap<Symbol, number>();
private _constant: number;
} | the_stack |
import Rectangle from '../Rectangle';
import {
getBoundingBox,
getDirectedBounds,
isNotNullish,
mod,
} from '../../../util/Utils';
import {
DIRECTION_EAST,
DIRECTION_NORTH,
DIRECTION_SOUTH,
DIRECTION_WEST,
LINE_ARCSIZE,
NONE,
RECTANGLE_ROUNDING_FACTOR,
SHADOW_OFFSET_X,
SHADOW_OFFSET_Y,
} from '../../../util/Constants';
import Point from '../Point';
import AbstractCanvas2D from '../../../util/canvas/AbstractCanvas2D';
import SvgCanvas2D from '../../../util/canvas/SvgCanvas2D';
import InternalEvent from '../../event/InternalEvent';
import mxClient from '../../../mxClient';
import CellState from '../../cell/datatypes/CellState';
import StencilShape from './node/StencilShape';
import CellOverlay from '../../cell/CellOverlay';
import ImageBox from '../../image/ImageBox';
import type {
ArrowType,
CellStateStyles,
ColorValue,
DirectionValue,
GradientMap,
} from '../../../types';
/**
* Base class for all shapes.
* A shape in mxGraph is a separate implementation for SVG, VML and HTML.
* Which implementation to use is controlled by the dialect property which
* is assigned from within the mxCellRenderer when the shape is created.
* The dialect must be assigned for a shape, and it does normally depend on
* the browser and the configuration of the graph (see mxGraph rendering hint).
*
* For each supported shape in SVG and VML, a corresponding shape exists in
* mxGraph, namely for text, image, rectangle, rhombus, ellipse and polyline.
* The other shapes are a combination of these shapes (eg. label and swimlane)
* or they consist of one or more (filled) path objects (eg. actor and cylinder).
* The HTML implementation is optional but may be required for a HTML-only view
* of the graph.
*
* ### Custom Shapes
* To extend from this class, the basic code looks as follows.
* In the special case where the custom shape consists only of one filled region
* or one filled region and an additional stroke the mxActor and mxCylinder
* should be subclassed, respectively.
* @example
* ```javascript
* function CustomShape() { }
*
* CustomShape.prototype = new mxShape();
* CustomShape.prototype.constructor = CustomShape;
* ```
* To register a custom shape in an existing graph instance, one must register the
* shape under a new name in the graph’s cell renderer as follows:
* @example
* ```javascript
* mxCellRenderer.registerShape('customShape', CustomShape);
* ```
* The second argument is the name of the constructor.
* In order to use the shape you can refer to the given name above in a stylesheet.
* For example, to change the shape for the default vertex style, the following code
* is used:
* @example
* ```javascript
* var style = graph.getStylesheet().getDefaultVertexStyle();
* style.shape = 'customShape';
* ```
*/
class Shape {
// Assigned in mxCellRenderer
preserveImageAspect = false;
overlay: CellOverlay | null = null;
indicator: Shape | null = null;
indicatorShape: typeof Shape | null = null;
// Assigned in mxCellHighlight
opacity = 100;
isDashed = false;
fill: ColorValue = NONE;
gradient: ColorValue = NONE;
gradientDirection: DirectionValue = DIRECTION_EAST;
fillOpacity = 100;
strokeOpacity = 100;
stroke: ColorValue = NONE;
strokeWidth = 1;
spacing = 0;
startSize = 1;
endSize = 1;
startArrow: ArrowType = NONE;
endArrow: ArrowType = NONE;
direction: DirectionValue = DIRECTION_EAST;
flipH = false;
flipV = false;
isShadow = false;
isRounded = false;
rotation = 0;
cursor = '';
verticalTextRotation = 0;
oldGradients: GradientMap = {};
glass = false;
/**
* Variable: dialect
*
* Holds the dialect in which the shape is to be painted.
* This can be one of the DIALECT constants in <mxConstants>.
*/
dialect: string | null = null;
/**
* Variable: scale
*
* Holds the scale in which the shape is being painted.
*/
scale = 1;
/**
* Variable: antiAlias
*
* Rendering hint for configuring the canvas.
*/
antiAlias = true;
/**
* Variable: minSvgStrokeWidth
*
* Minimum stroke width for SVG output.
*/
minSvgStrokeWidth = 1;
/**
* Variable: bounds
*
* Holds the <mxRectangle> that specifies the bounds of this shape.
*/
bounds: Rectangle | null = null;
/**
* Variable: points
*
* Holds the array of <mxPoints> that specify the points of this shape.
*/
points: (Point | null)[] = [];
/**
* Variable: node
*
* Holds the outermost DOM node that represents this shape.
*/
node: SVGGElement;
/**
* Variable: state
*
* Optional reference to the corresponding <mxCellState>.
*/
state: CellState | null = null;
/**
* Variable: style
*
* Optional reference to the style of the corresponding <mxCellState>.
*/
style: CellStateStyles | null = null;
/**
* Variable: boundingBox
*
* Contains the bounding box of the shape, that is, the smallest rectangle
* that includes all pixels of the shape.
*/
boundingBox: Rectangle | null = null;
/**
* Variable: stencil
*
* Holds the <mxStencil> that defines the shape.
*/
stencil: StencilShape | null = null;
/**
* Variable: svgStrokeTolerance
*
* Event-tolerance for SVG strokes (in px). Default is 8. This is only passed
* to the canvas in <createSvgCanvas> if <pointerEvents> is true.
*/
svgStrokeTolerance = 8;
/**
* Variable: pointerEvents
*
* Specifies if pointer events should be handled. Default is true.
*/
pointerEvents = true;
originalPointerEvents: boolean | null = null;
/**
* Variable: svgPointerEvents
*
* Specifies if pointer events should be handled. Default is true.
*/
svgPointerEvents = 'all';
/**
* Variable: shapePointerEvents
*
* Specifies if pointer events outside of shape should be handled. Default
* is false.
*/
shapePointerEvents = false;
/**
* Variable: stencilPointerEvents
*
* Specifies if pointer events outside of stencils should be handled. Default
* is false. Set this to true for backwards compatibility with the 1.x branch.
*/
stencilPointerEvents = false;
/**
* Variable: outline
*
* Specifies if the shape should be drawn as an outline. This disables all
* fill colors and can be used to disable other drawing states that should
* not be painted for outlines. Default is false. This should be set before
* calling <apply>.
*/
outline = false;
/**
* Variable: visible
*
* Specifies if the shape is visible. Default is true.
*/
visible = true;
/**
* Variable: useSvgBoundingBox
*
* Allows to use the SVG bounding box in SVG. Default is false for performance
* reasons.
*/
useSvgBoundingBox = true;
image: ImageBox | null = null;
imageSrc: string | null = null;
indicatorColor: ColorValue = NONE;
indicatorStrokeColor: ColorValue = NONE;
indicatorGradientColor: ColorValue = NONE;
indicatorDirection: DirectionValue = DIRECTION_EAST;
indicatorImageSrc: string | null = null;
constructor(stencil: StencilShape | null = null) {
// `stencil` is not null when instantiated directly,
// but can be null when instantiated through a child class.
if (stencil) {
this.stencil = stencil;
}
// moved from init()
this.node = this.create();
}
/**
* Function: init
*
* Initializes the shape by creaing the DOM node using <create>
* and adding it into the given container.
*
* Parameters:
*
* container - DOM node that will contain the shape.
*/
init(container: HTMLElement | SVGElement) {
if (!this.node.parentNode) {
container.appendChild(this.node);
}
}
/**
* Function: initStyles
*
* Sets the styles to their default values.
*/
initStyles() {
this.strokeWidth = 1;
this.rotation = 0;
this.opacity = 100;
this.fillOpacity = 100;
this.strokeOpacity = 100;
this.flipH = false;
this.flipV = false;
}
/**
* Function: isHtmlAllowed
*
* Returns true if HTML is allowed for this shape. This implementation always
* returns false.
*/
isHtmlAllowed() {
return false;
}
/**
* Function: getSvgScreenOffset
*
* Returns 0, or 0.5 if <strokewidth> % 2 == 1.
*/
getSvgScreenOffset(): number {
const sw =
this.stencil && this.stencil.strokeWidthValue !== 'inherit'
? Number(this.stencil.strokeWidthValue)
: this.strokeWidth ?? 0;
return mod(Math.max(1, Math.round(sw * this.scale)), 2) === 1 ? 0.5 : 0;
}
/**
* Function: create
*
* Creates and returns the DOM node(s) for the shape in
* the given container. This implementation invokes
* <createSvg>, <createHtml> or <createVml> depending
* on the <dialect> and style settings.
*
* Parameters:
*
* container - DOM node that will contain the shape.
*/
create() {
return document.createElementNS('http://www.w3.org/2000/svg', 'g');
}
/**
* Function: reconfigure
*
* Reconfigures this shape. This will update the colors etc in
* addition to the bounds or points.
*/
reconfigure() {
this.redraw();
}
/**
* Function: redraw
*
* Creates and returns the SVG node(s) to represent this shape.
*/
redraw() {
this.updateBoundsFromPoints();
if (this.visible && this.checkBounds()) {
this.node.style.visibility = 'visible';
this.clear();
this.redrawShape();
this.updateBoundingBox();
} else {
this.node.style.visibility = 'hidden';
this.boundingBox = null;
}
}
/**
* Function: clear
*
* Removes all child nodes and resets all CSS.
*/
clear() {
while (this.node.lastChild) {
this.node.removeChild(this.node.lastChild);
}
}
/**
* Function: updateBoundsFromPoints
*
* Updates the bounds based on the points.
*/
updateBoundsFromPoints() {
const pts = this.points;
if (pts.length > 0 && pts[0]) {
this.bounds = new Rectangle(Math.round(pts[0].x), Math.round(pts[0].y), 1, 1);
for (const pt of pts) {
if (pt) {
this.bounds.add(new Rectangle(Math.round(pt.x), Math.round(pt.y), 1, 1));
}
}
}
}
/**
* Function: getLabelBounds
*
* Returns the <mxRectangle> for the label bounds of this shape, based on the
* given scaled and translated bounds of the shape. This method should not
* change the rectangle in-place. This implementation returns the given rect.
*/
getLabelBounds(rect: Rectangle) {
const d = this.style?.direction ?? DIRECTION_EAST;
let bounds = rect.clone();
// Normalizes argument for getLabelMargins hook
if (
d !== DIRECTION_SOUTH &&
d !== DIRECTION_NORTH &&
this.state &&
this.state.text &&
this.state.text.isPaintBoundsInverted()
) {
bounds = bounds.clone();
[bounds.width, bounds.height] = [bounds.height, bounds.width];
}
let labelMargins = this.getLabelMargins(bounds);
if (labelMargins) {
labelMargins = labelMargins.clone();
let flipH = this.style?.flipH ?? false;
let flipV = this.style?.flipV ?? false;
// Handles special case for vertical labels
if (this.state && this.state.text && this.state.text.isPaintBoundsInverted()) {
const tmp = labelMargins.x;
labelMargins.x = labelMargins.height;
labelMargins.height = labelMargins.width;
labelMargins.width = labelMargins.y;
labelMargins.y = tmp;
[flipH, flipV] = [flipV, flipH];
}
return getDirectedBounds(rect, labelMargins, this.style, flipH, flipV);
}
return rect;
}
/**
* Function: getLabelMargins
*
* Returns the scaled top, left, bottom and right margin to be used for
* computing the label bounds as an <mxRectangle>, where the bottom and right
* margin are defined in the width and height of the rectangle, respectively.
*/
getLabelMargins(rect: Rectangle | null): Rectangle | null {
return null;
}
/**
* Function: checkBounds
*
* Returns true if the bounds are not null and all of its variables are numeric.
*/
checkBounds() {
return (
!Number.isNaN(this.scale) &&
Number.isFinite(this.scale) &&
this.scale > 0 &&
this.bounds &&
!Number.isNaN(this.bounds.x) &&
!Number.isNaN(this.bounds.y) &&
!Number.isNaN(this.bounds.width) &&
!Number.isNaN(this.bounds.height) &&
this.bounds.width > 0 &&
this.bounds.height > 0
);
}
/**
* Function: redrawShape
*
* Updates the SVG or VML shape.
*/
redrawShape() {
const canvas = this.createCanvas();
if (canvas) {
// Specifies if events should be handled
canvas.pointerEvents = this.pointerEvents;
this.beforePaint(canvas);
this.paint(canvas);
this.afterPaint(canvas);
if (this.node !== canvas.root && canvas.root) {
// Forces parsing in IE8 standards mode - slow! avoid
this.node.insertAdjacentHTML('beforeend', canvas.root.outerHTML);
}
this.destroyCanvas(canvas);
}
}
/**
* Function: createCanvas
*
* Creates a new canvas for drawing this shape. May return null.
*/
createCanvas() {
const canvas = this.createSvgCanvas();
if (canvas && this.outline) {
canvas.setStrokeWidth(this.strokeWidth);
canvas.setStrokeColor(this.stroke);
if (this.isDashed) {
canvas.setDashed(this.isDashed);
}
canvas.setStrokeWidth = () => {};
canvas.setStrokeColor = () => {};
canvas.setFillColor = () => {};
canvas.setGradient = () => {};
canvas.setDashed = () => {};
canvas.text = () => {};
}
return canvas;
}
/**
* Function: createSvgCanvas
*
* Creates and returns an <mxSvgCanvas2D> for rendering this shape.
*/
createSvgCanvas() {
if (!this.node) return null;
const canvas = new SvgCanvas2D(this.node, false);
canvas.strokeTolerance = this.pointerEvents ? this.svgStrokeTolerance : 0;
canvas.pointerEventsValue = this.svgPointerEvents;
const off = this.getSvgScreenOffset();
if (off !== 0) {
this.node.setAttribute('transform', `translate(${off},${off})`);
} else {
this.node.removeAttribute('transform');
}
canvas.minStrokeWidth = this.minSvgStrokeWidth;
if (!this.antiAlias) {
// Rounds all numbers in the SVG output to integers
canvas.format = (value) => {
return Math.round(value);
};
}
return canvas;
}
/**
* Function: destroyCanvas
*
* Destroys the given canvas which was used for drawing. This implementation
* increments the reference counts on all shared gradients used in the canvas.
*/
destroyCanvas(canvas: AbstractCanvas2D) {
// Manages reference counts
if (canvas instanceof SvgCanvas2D) {
// Increments ref counts
for (const key in canvas.gradients) {
const gradient = canvas.gradients[key];
if (gradient) {
gradient.mxRefCount = (gradient.mxRefCount || 0) + 1;
}
}
this.releaseSvgGradients(this.oldGradients);
this.oldGradients = canvas.gradients;
}
}
/**
* Function: beforePaint
*
* Invoked before paint is called.
*/
beforePaint(c: AbstractCanvas2D) {}
/**
* Function: afterPaint
*
* Invokes after paint was called.
*/
afterPaint(c: AbstractCanvas2D) {}
/**
* Generic rendering code.
*/
paint(c: AbstractCanvas2D) {
let strokeDrawn = false;
if (c && this.outline) {
const { stroke } = c;
c.stroke = (...args) => {
strokeDrawn = true;
stroke.apply(c, args);
};
const { fillAndStroke } = c;
c.fillAndStroke = (...args) => {
strokeDrawn = true;
fillAndStroke.apply(c, args);
};
}
// Scale is passed-through to canvas
const s = this.scale;
const bounds = this.bounds;
if (bounds) {
let x = bounds.x / s;
let y = bounds.y / s;
let w = bounds.width / s;
let h = bounds.height / s;
if (this.isPaintBoundsInverted()) {
const t = (w - h) / 2;
x += t;
y -= t;
const tmp = w;
w = h;
h = tmp;
}
this.updateTransform(c, x, y, w, h);
this.configureCanvas(c, x, y, w, h);
// Adds background rectangle to capture events
let bg = null;
if (
(!this.stencil && this.points.length === 0 && this.shapePointerEvents) ||
(this.stencil && this.stencilPointerEvents)
) {
const bb = this.createBoundingBox();
if (bb && this.node) {
bg = this.createTransparentSvgRectangle(bb.x, bb.y, bb.width, bb.height);
this.node.appendChild(bg);
}
}
if (this.stencil) {
this.stencil.drawShape(c, this, x, y, w, h);
} else {
// Stencils have separate strokewidth
c.setStrokeWidth(this.strokeWidth);
if (this.points.length > 0) {
// Paints edge shape
const pts = [];
for (let i = 0; i < this.points.length; i += 1) {
const p = this.points[i];
if (p) {
pts.push(new Point(p.x / s, p.y / s));
}
}
this.paintEdgeShape(c, pts);
} else {
// Paints vertex shape
this.paintVertexShape(c, x, y, w, h);
}
}
if (bg && c.state && isNotNullish(c.state.transform)) {
bg.setAttribute('transform', <string>c.state.transform);
}
// Draws highlight rectangle if no stroke was used
if (c && this.outline && !strokeDrawn) {
c.rect(x, y, w, h);
c.stroke();
}
}
}
/**
* Sets the state of the canvas for drawing the shape.
*/
configureCanvas(c: AbstractCanvas2D, x: number, y: number, w: number, h: number) {
let dash: string | null = null;
if (this.style) {
dash = this.style.dashPattern;
}
c.setAlpha(this.opacity / 100);
c.setFillAlpha(this.fillOpacity / 100);
c.setStrokeAlpha(this.strokeOpacity / 100);
// Sets alpha, colors and gradients
if (this.isShadow) {
c.setShadow(this.isShadow);
}
// Dash pattern
if (this.isDashed) {
c.setDashed(this.isDashed, this.style?.fixDash ?? false);
}
if (dash) {
c.setDashPattern(dash);
}
if (this.fill !== NONE && this.gradient !== NONE) {
const b = this.getGradientBounds(c, x, y, w, h);
c.setGradient(
this.fill,
this.gradient,
b.x,
b.y,
b.width,
b.height,
this.gradientDirection
);
} else {
c.setFillColor(this.fill);
}
c.setStrokeColor(this.stroke);
}
/**
* Function: getGradientBounds
*
* Returns the bounding box for the gradient box for this shape.
*/
getGradientBounds(c: AbstractCanvas2D, x: number, y: number, w: number, h: number) {
return new Rectangle(x, y, w, h);
}
/**
* Function: updateTransform
*
* Sets the scale and rotation on the given canvas.
*/
updateTransform(c: AbstractCanvas2D, x: number, y: number, w: number, h: number) {
// NOTE: Currently, scale is implemented in state and canvas. This will
// move to canvas in a later version, so that the states are unscaled
// and untranslated and do not need an update after zooming or panning.
c.scale(this.scale);
c.rotate(this.getShapeRotation(), this.flipH, this.flipV, x + w / 2, y + h / 2);
}
/**
* Function: paintVertexShape
*
* Paints the vertex shape.
*/
paintVertexShape(c: AbstractCanvas2D, x: number, y: number, w: number, h: number) {
this.paintBackground(c, x, y, w, h);
if (!this.outline || !this.style || (this.style.backgroundOutline ?? 0) === 0) {
c.setShadow(false);
this.paintForeground(c, x, y, w, h);
}
}
/**
* Function: paintBackground
*
* Hook for subclassers. This implementation is empty.
*/
paintBackground(c: AbstractCanvas2D, x: number, y: number, w: number, h: number) {}
/**
* Hook for subclassers. This implementation is empty.
*/
paintForeground(c: AbstractCanvas2D, x: number, y: number, w: number, h: number) {}
/**
* Function: paintEdgeShape
*
* Hook for subclassers. This implementation is empty.
*/
paintEdgeShape(c: AbstractCanvas2D, pts: Point[]) {}
/**
* Function: getArcSize
*
* Returns the arc size for the given dimension.
*/
getArcSize(w: number, h: number) {
let r = 0;
if (this.style?.absoluteArcSize === 0) {
r = Math.min(w / 2, Math.min(h / 2, (this.style?.arcSize ?? LINE_ARCSIZE) / 2));
} else {
const f = (this.style?.arcSize ?? RECTANGLE_ROUNDING_FACTOR * 100) / 100;
r = Math.min(w * f, h * f);
}
return r;
}
/**
* Function: paintGlassEffect
*
* Paints the glass gradient effect.
*/
paintGlassEffect(
c: AbstractCanvas2D,
x: number,
y: number,
w: number,
h: number,
arc: number
) {
const sw = Math.ceil((this.strokeWidth ?? 0) / 2);
const size = 0.4;
c.setGradient('#ffffff', '#ffffff', x, y, w, h * 0.6, 'south', 0.9, 0.1);
c.begin();
arc += 2 * sw;
if (this.isRounded) {
c.moveTo(x - sw + arc, y - sw);
c.quadTo(x - sw, y - sw, x - sw, y - sw + arc);
c.lineTo(x - sw, y + h * size);
c.quadTo(x + w * 0.5, y + h * 0.7, x + w + sw, y + h * size);
c.lineTo(x + w + sw, y - sw + arc);
c.quadTo(x + w + sw, y - sw, x + w + sw - arc, y - sw);
} else {
c.moveTo(x - sw, y - sw);
c.lineTo(x - sw, y + h * size);
c.quadTo(x + w * 0.5, y + h * 0.7, x + w + sw, y + h * size);
c.lineTo(x + w + sw, y - sw);
}
c.close();
c.fill();
}
/**
* Function: addPoints
*
* Paints the given points with rounded corners.
*/
addPoints(
c: AbstractCanvas2D,
pts: Point[],
rounded: boolean = false,
arcSize: number,
close: boolean = false,
exclude: number[] = [],
initialMove: boolean = true
) {
if (pts.length > 0) {
const pe = pts[pts.length - 1];
// Adds virtual waypoint in the center between start and end point
if (close && rounded) {
pts = pts.slice();
const p0 = pts[0];
const wp = new Point(pe.x + (p0.x - pe.x) / 2, pe.y + (p0.y - pe.y) / 2);
pts.splice(0, 0, wp);
}
let pt = pts[0];
let i = 1;
// Draws the line segments
if (initialMove) {
c.moveTo(pt.x, pt.y);
} else {
c.lineTo(pt.x, pt.y);
}
while (i < (close ? pts.length : pts.length - 1)) {
let tmp = pts[mod(i, pts.length)];
let dx = pt.x - tmp.x;
let dy = pt.y - tmp.y;
if (rounded && (dx !== 0 || dy !== 0) && exclude.indexOf(i - 1) < 0) {
// Draws a line from the last point to the current
// point with a spacing of size off the current point
// into direction of the last point
let dist = Math.sqrt(dx * dx + dy * dy);
const nx1 = (dx * Math.min(arcSize, dist / 2)) / dist;
const ny1 = (dy * Math.min(arcSize, dist / 2)) / dist;
const x1 = tmp.x + nx1;
const y1 = tmp.y + ny1;
c.lineTo(x1, y1);
// Draws a curve from the last point to the current
// point with a spacing of size off the current point
// into direction of the next point
let next = pts[mod(i + 1, pts.length)];
// Uses next non-overlapping point
while (
i < pts.length - 2 &&
Math.round(next.x - tmp.x) === 0 &&
Math.round(next.y - tmp.y) === 0
) {
next = pts[mod(i + 2, pts.length)];
i++;
}
dx = next.x - tmp.x;
dy = next.y - tmp.y;
dist = Math.max(1, Math.sqrt(dx * dx + dy * dy));
const nx2 = (dx * Math.min(arcSize, dist / 2)) / dist;
const ny2 = (dy * Math.min(arcSize, dist / 2)) / dist;
const x2 = tmp.x + nx2;
const y2 = tmp.y + ny2;
c.quadTo(tmp.x, tmp.y, x2, y2);
tmp = new Point(x2, y2);
} else {
c.lineTo(tmp.x, tmp.y);
}
pt = tmp;
i += 1;
}
if (close) {
c.close();
} else {
c.lineTo(pe.x, pe.y);
}
}
}
/**
* Function: resetStyles
*
* Resets all styles.
*/
resetStyles() {
this.initStyles();
this.spacing = 0;
this.fill = NONE;
this.gradient = NONE;
this.gradientDirection = DIRECTION_EAST;
this.stroke = NONE;
this.startSize = 1;
this.endSize = 1;
this.startArrow = NONE;
this.endArrow = NONE;
this.direction = DIRECTION_EAST;
this.isShadow = false;
this.isDashed = false;
this.isRounded = false;
this.glass = false;
}
/**
* Function: apply
*
* Applies the style of the given <mxCellState> to the shape. This
* implementation assigns the following styles to local fields:
*
* - <'fillColor'> => fill
* - <'gradientColor'> => gradient
* - <'gradientDirection'> => gradientDirection
* - <'opacity'> => opacity
* - <mxConstants.STYLE_FILL_OPACITY> => fillOpacity
* - <mxConstants.STYLE_STROKE_OPACITY> => strokeOpacity
* - <'strokeColor'> => stroke
* - <'strokeWidth'> => strokewidth
* - <'shadow'> => isShadow
* - <'dashed'> => isDashed
* - <'spacing'> => spacing
* - <'startSize'> => startSize
* - <'endSize'> => endSize
* - <'rounded'> => isRounded
* - <'startArrow'> => startArrow
* - <'endArrow'> => endArrow
* - <'rotation'> => rotation
* - <'direction'> => direction
* - <'glass'> => glass
*
* This keeps a reference to the <style>. If you need to keep a reference to
* the cell, you can override this method and store a local reference to
* state.cell or the <mxCellState> itself. If <outline> should be true, make
* sure to set it before calling this method.
*
* Parameters:
*
* state - <mxCellState> of the corresponding cell.
*/
apply(state: CellState) {
this.state = state;
this.style = state.style;
if (this.style) {
this.fill = this.style.fillColor ?? this.fill;
this.gradient = this.style.gradientColor ?? this.gradient;
this.gradientDirection = this.style.gradientDirection ?? this.gradientDirection;
this.opacity = this.style.opacity ?? this.opacity;
this.fillOpacity = this.style.fillOpacity ?? this.fillOpacity;
this.strokeOpacity = this.style.strokeOpacity ?? this.strokeOpacity;
this.stroke = this.style.strokeColor ?? this.stroke;
this.strokeWidth = this.style.strokeWidth ?? this.strokeWidth;
this.spacing = this.style.spacing ?? this.spacing;
this.startSize = this.style.startSize ?? this.startSize;
this.endSize = this.style.endSize ?? this.endSize;
this.startArrow = this.style.startArrow ?? this.startArrow;
this.endArrow = this.style.endArrow ?? this.endArrow;
this.rotation = this.style.rotation ?? this.rotation;
this.direction = this.style.direction ?? this.direction;
this.flipH = !!this.style.flipH;
this.flipV = !!this.style.flipV;
if (this.direction === DIRECTION_NORTH || this.direction === DIRECTION_SOUTH) {
const tmp = this.flipH;
this.flipH = this.flipV;
this.flipV = tmp;
}
this.isShadow = this.style.shadow ?? this.isShadow;
this.isDashed = this.style.dashed ?? this.isDashed;
this.isRounded = this.style.rounded ?? this.isRounded;
this.glass = this.style.glass ?? this.glass;
}
}
/**
* Function: setCursor
*
* Sets the cursor on the given shape.
*
* Parameters:
*
* cursor - The cursor to be used.
*/
setCursor(cursor: string) {
this.cursor = cursor;
this.node.style.cursor = cursor;
}
/**
* Function: getCursor
*
* Returns the current cursor.
*/
getCursor() {
return this.cursor;
}
/**
* Hook for subclassers.
*/
isRoundable(c: AbstractCanvas2D, x: number, y: number, w: number, h: number) {
return false;
}
/**
* Function: updateBoundingBox
*
* Updates the <boundingBox> for this shape using <createBoundingBox> and
* <augmentBoundingBox> and stores the result in <boundingBox>.
*/
updateBoundingBox() {
// Tries to get bounding box from SVG subsystem
// LATER: Use getBoundingClientRect for fallback in VML
if (this.useSvgBoundingBox && this.node.ownerSVGElement) {
try {
const b = this.node.getBBox();
if (b.width > 0 && b.height > 0) {
this.boundingBox = new Rectangle(b.x, b.y, b.width, b.height);
// Adds strokeWidth
this.boundingBox.grow(((this.strokeWidth ?? 0) * this.scale) / 2);
return;
}
} catch (e) {
// fallback to code below
}
}
if (this.bounds) {
let bbox = this.createBoundingBox();
if (bbox) {
this.augmentBoundingBox(bbox);
const rot = this.getShapeRotation();
if (rot !== 0) {
bbox = getBoundingBox(bbox, rot);
}
}
this.boundingBox = bbox;
}
}
/**
* Function: createBoundingBox
*
* Returns a new rectangle that represents the bounding box of the bare shape
* with no shadows or strokewidths.
*/
createBoundingBox() {
if (!this.bounds) return null;
const bb = this.bounds.clone();
if (
(this.stencil &&
(this.direction === DIRECTION_NORTH || this.direction === DIRECTION_SOUTH)) ||
this.isPaintBoundsInverted()
) {
bb.rotate90();
}
return bb;
}
/**
* Augments the bounding box with the strokewidth and shadow offsets.
*/
augmentBoundingBox(bbox: Rectangle) {
if (this.isShadow) {
bbox.width += Math.ceil(SHADOW_OFFSET_X * this.scale);
bbox.height += Math.ceil(SHADOW_OFFSET_Y * this.scale);
}
// Adds strokeWidth
bbox.grow(((this.strokeWidth ?? 0) * this.scale) / 2);
}
/**
* Function: isPaintBoundsInverted
*
* Returns true if the bounds should be inverted.
*/
isPaintBoundsInverted() {
// Stencil implements inversion via aspect
return (
!this.stencil &&
(this.direction === DIRECTION_NORTH || this.direction === DIRECTION_SOUTH)
);
}
/**
* Function: getRotation
*
* Returns the rotation from the style.
*/
getRotation() {
return this.rotation ?? 0;
}
/**
* Function: getTextRotation
*
* Returns the rotation for the text label.
*/
getTextRotation() {
let rot = this.getRotation();
if (!(this.style?.horizontal ?? true)) {
rot += this.verticalTextRotation || -90; // WARNING WARNING!!!! ===============================================================================================
}
return rot;
}
/**
* Function: getShapeRotation
*
* Returns the actual rotation of the shape.
*/
getShapeRotation() {
let rot = this.getRotation();
if (this.direction === DIRECTION_NORTH) {
rot += 270;
} else if (this.direction === DIRECTION_WEST) {
rot += 180;
} else if (this.direction === DIRECTION_SOUTH) {
rot += 90;
}
return rot;
}
/**
* Function: createTransparentSvgRectangle
*
* Adds a transparent rectangle that catches all events.
*/
createTransparentSvgRectangle(x: number, y: number, w: number, h: number) {
const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
rect.setAttribute('x', String(x));
rect.setAttribute('y', String(y));
rect.setAttribute('width', String(w));
rect.setAttribute('height', String(h));
rect.setAttribute('fill', NONE);
rect.setAttribute('stroke', NONE);
rect.setAttribute('pointer-events', 'all');
return rect;
}
redrawHtmlShape() {}
/**
* Function: setTransparentBackgroundImage
*
* Sets a transparent background CSS style to catch all events.
*
* Paints the line shape.
*/
setTransparentBackgroundImage(node: SVGElement) {
node.style.backgroundImage = `url('${mxClient.imageBasePath}/transparent.gif')`;
}
/**
* Function: releaseSvgGradients
*
* Paints the line shape.
*/
releaseSvgGradients(grads: GradientMap) {
for (const key in grads) {
const gradient = grads[key];
if (gradient) {
gradient.mxRefCount = (gradient.mxRefCount || 0) - 1;
if (gradient.mxRefCount === 0 && gradient.parentNode) {
gradient.parentNode.removeChild(gradient);
}
}
}
}
/**
* Function: destroy
*
* Destroys the shape by removing it from the DOM and releasing the DOM
* node associated with the shape using <mxEvent.release>.
*/
destroy() {
InternalEvent.release(this.node);
if (this.node.parentNode) {
this.node.parentNode.removeChild(this.node);
}
this.node.innerHTML = '';
// Decrements refCount and removes unused
this.releaseSvgGradients(this.oldGradients);
this.oldGradients = {};
}
}
export default Shape; | the_stack |
/// <reference path="../../../dist/automapper-classes.d.ts" />
/// <reference path="../../../dist/automapper-interfaces.d.ts" />
/// <reference path="../../../dist/automapper-declaration.d.ts" />
var globalScope = this;
module AutoMapperJs {
class PascalCaseToCamelCaseMappingProfile extends Profile {
public sourceMemberNamingConvention: INamingConvention;
public destinationMemberNamingConvention: INamingConvention;
public profileName = 'PascalCaseToCamelCase';
public configure() {
this.sourceMemberNamingConvention = new PascalCaseNamingConvention();
this.destinationMemberNamingConvention = new CamelCaseNamingConvention();
super.createMap('a', 'b');
}
}
class ForAllMembersMappingProfile extends Profile {
public sourceMemberNamingConvention: INamingConvention;
public destinationMemberNamingConvention: INamingConvention;
public profileName = 'ForAllMembers';
private _fromKey: string;
private _toKey: string;
private _forAllMembersMappingSuffix: string;
constructor(fromKey: string, toKey: string, forAllMembersMappingSuffix: string) {
super();
this._fromKey = fromKey;
this._toKey = toKey;
this._forAllMembersMappingSuffix = forAllMembersMappingSuffix;
}
public configure() {
super.createMap(this._fromKey, this._toKey)
.forMember('prop1', (opts: IMemberConfigurationOptions): any => opts.intermediatePropertyValue)
.forMember('prop2', (opts: IMemberConfigurationOptions): any => opts.intermediatePropertyValue)
.forAllMembers((destinationObject: any,
destinationPropertyName: string,
value: any): void => {
destinationObject[destinationPropertyName] = value + this._forAllMembersMappingSuffix;
});
}
}
class ConvertUsingMappingProfile extends Profile {
public sourceMemberNamingConvention: INamingConvention;
public destinationMemberNamingConvention: INamingConvention;
public profileName = 'ConvertUsing';
private _fromKey: string;
private _toKey: string;
private _convertUsingSuffix: string;
constructor(fromKey: string, toKey: string, convertUsingSuffix: string) {
super();
this._fromKey = fromKey;
this._toKey = toKey;
this._convertUsingSuffix = convertUsingSuffix;
}
public configure() {
super.createMap(this._fromKey, this._toKey)
.convertUsing((resolutionContext: IResolutionContext): any => {
return {
prop1: resolutionContext.sourceValue.prop1 + this._convertUsingSuffix,
prop2: resolutionContext.sourceValue.prop2 + this._convertUsingSuffix
};
});
}
}
class CamelCaseToPascalCaseMappingProfile extends Profile {
public sourceMemberNamingConvention: INamingConvention;
public destinationMemberNamingConvention: INamingConvention;
public profileName = 'CamelCaseToPascalCase';
public configure() {
this.sourceMemberNamingConvention = new CamelCaseNamingConvention();
this.destinationMemberNamingConvention = new PascalCaseNamingConvention();
}
}
class ValidatedAgeMappingProfile extends Profile {
public profileName = 'ValidatedAgeMappingProfile';
public configure() {
const sourceKey = '{808D9D7F-AA89-4D07-917E-A528F078E642}';
const destinationKey = '{808D9D6F-BA89-4D17-915E-A528E178EE64}';
this.createMap(sourceKey, destinationKey)
.forMember('proclaimedAge', (opts: IMemberConfigurationOptions) => opts.ignore())
.forMember('age', (opts: IMemberConfigurationOptions) => opts.mapFrom('ageOnId'))
.convertToType(Person);
}
}
class ValidatedAgeMappingProfile2 extends Profile {
public profileName = 'ValidatedAgeMappingProfile2';
public configure() {
const sourceKey = '{918D9D7F-AA89-4D07-917E-A528F07EEF42}';
const destinationKey = '{908D9D6F-BA89-4D17-915E-A528E988EE64}';
this.createMap(sourceKey, destinationKey)
.forMember('proclaimedAge', (opts: IMemberConfigurationOptions) => opts.ignore())
.forMember('age', (opts: IMemberConfigurationOptions) => opts.mapFrom('ageOnId'))
.convertToType(Person);
}
}
class Person {
fullName: string = null;
age: number = null;
}
class BeerBuyingYoungster extends Person {
}
describe('AutoMapper.initialize', () => {
let postfix = ' [f0e5ef4a-ebe1-32c4-a3ed-48f8b5a5fac7]';
beforeEach(() => {
utils.registerTools(globalScope);
utils.registerCustomMatchers(globalScope);
});
it('should use created mapping profile', () => {
// arrange
var fromKey = '{5700E351-8D88-A327-A216-3CC94A308EDE}';
var toKey = '{BB33A261-3CA9-A8FC-85E6-2C269F73728C}';
automapper.initialize((config: IConfiguration) => {
config.createMap(fromKey, toKey);
});
// act
automapper.map(fromKey, toKey, {});
// assert
});
it('should be able to use a naming convention to convert Pascal case to camel case', () => {
automapper.initialize((config: IConfiguration) => {
config.addProfile(new PascalCaseToCamelCaseMappingProfile());
});
const sourceKey = 'PascalCase';
const destinationKey = 'CamelCase';
const sourceObject = { FullName: 'John Doe' };
automapper
.createMap(sourceKey, destinationKey)
.withProfile('PascalCaseToCamelCase');
var result = automapper.map(sourceKey, destinationKey, sourceObject);
expect(result).toEqualData({ fullName: 'John Doe' });
});
it('should be able to use a naming convention to convert camelCase to PascalCase', () => {
automapper.initialize((config: IConfiguration) => {
config.addProfile(new CamelCaseToPascalCaseMappingProfile());
});
const sourceKey = 'CamelCase2';
const destinationKey = 'PascalCase2';
const sourceObject = { fullName: 'John Doe' };
automapper
.createMap(sourceKey, destinationKey)
.withProfile('CamelCaseToPascalCase');
var result = automapper.map(sourceKey, destinationKey, sourceObject);
expect(result).toEqualData({ FullName: 'John Doe' });
});
it('should be able to use forMember besides using a profile', () => {
automapper.initialize((config: IConfiguration) => {
config.addProfile(new CamelCaseToPascalCaseMappingProfile());
});
const sourceKey = 'CamelCase';
const destinationKey = 'PascalCase';
const sourceObject = { fullName: 'John Doe', age: 20 };
automapper
.createMap(sourceKey, destinationKey)
.forMember('theAge', (opts: IMemberConfigurationOptions) => opts.mapFrom('age'))
.withProfile('CamelCaseToPascalCase');
var result = automapper.map(sourceKey, destinationKey, sourceObject);
expect(result).toEqualData({ FullName: 'John Doe', theAge: sourceObject.age });
});
it('should use profile when only profile properties are specified', () => {
automapper.initialize((config: IConfiguration) => {
config.addProfile(new ValidatedAgeMappingProfile2());
});
const sourceKey = '{918D9D7F-AA89-4D07-917E-A528F07EEF42}';
const destinationKey = '{908D9D6F-BA89-4D17-915E-A528E988EE64}';
const sourceObject = { fullName: 'John Doe', proclaimedAge: 21, ageOnId: 15 };
automapper
.createMap(sourceKey, destinationKey)
.withProfile('ValidatedAgeMappingProfile2');
var result = automapper.map(sourceKey, destinationKey, sourceObject);
expect(result).toEqualData({ fullName: 'John Doe', age: sourceObject.ageOnId });
expect(result instanceof Person).toBeTruthy();
expect(result instanceof BeerBuyingYoungster).not.toBeTruthy();
});
it('should fail when using a non-existing profile', () => {
// arrange
var caught = false;
var profileName = 'Non-existing profile';
const sourceKey = 'should fail when using ';
const destinationKey = 'a non-existing profile';
const sourceObject = {};
// act
try {
automapper
.createMap(sourceKey, destinationKey)
.withProfile(profileName);
var result = automapper.map(sourceKey, destinationKey, sourceObject);
} catch (e) {
caught = true;
// assert
expect(e.message).toEqual('Could not find profile with profile name \'' + profileName + '\'.');
}
if (!caught) {
// assert
expect().fail('Using a non-existing mapping profile should result in an error.');
}
});
it('should merge forMember calls when specifying the same destination property normally and using profile', () => {
automapper.initialize((config: IConfiguration) => {
config.addProfile(new ValidatedAgeMappingProfile());
});
const sourceKey = '{808D9D7F-AA89-4D07-917E-A528F078E642}';
const destinationKey = '{808D9D6F-BA89-4D17-915E-A528E178EE64}';
const sourceObject = { fullName: 'John Doe', proclaimedAge: 21, ageOnId: 15 };
automapper
.createMap(sourceKey, destinationKey)
.forMember('ageOnId', (opts: IMemberConfigurationOptions) => opts.ignore())
.forMember('age', (opts: IMemberConfigurationOptions) => opts.mapFrom('proclaimedAge'))
.convertToType(BeerBuyingYoungster)
.withProfile('ValidatedAgeMappingProfile');
var result = automapper.map(sourceKey, destinationKey, sourceObject);
expect(result).toEqualData({ fullName: 'John Doe', age: sourceObject.ageOnId });
expect(result instanceof Person).toBeTruthy();
expect(result instanceof BeerBuyingYoungster).not.toBeTruthy();
});
it('should be able to use currying when calling initialize(cfg => cfg.createMap)', () => {
// arrange
var fromKey = '{808D9D7F-AA89-4D07-917E-A528F078EE64}';
var toKey1 = '{B364C0A0-9E24-4424-A569-A4C14102147C}';
var toKey2 = '{1055CA5A-4FC4-44CA-B4D8-B004F43D4440}';
var source = { prop: 'Value' };
// act
var mapFromKeyCurry: (destinationKey: string) => ICreateMapFluentFunctions;
automapper.initialize((config: IConfiguration) => {
mapFromKeyCurry = config.createMap(fromKey);
mapFromKeyCurry(toKey1)
.forSourceMember('prop', (opts: ISourceMemberConfigurationOptions) => {
opts.ignore();
});
mapFromKeyCurry(toKey2);
});
var result1 = automapper.map(fromKey, toKey1, source);
var result2 = automapper.map(fromKey, toKey2, source);
// assert
expect(typeof mapFromKeyCurry === 'function').toBeTruthy();
expect(result1.prop).toBeUndefined();
expect(result2.prop).toEqual(source.prop);
});
it('should be able to use a mapping profile with forAllMemberMappings', () => {
// arrange
var fromKey = 'should be able to use a mapping profile ';
var toKey = 'with forAllMemberMappings' + postfix;
var source = { prop1: 'prop1', prop2: 'prop2' };
var forAllMembersMappingSuffix = ' [forAllMembers]';
automapper.initialize((config: IConfiguration) => {
config.addProfile(new ForAllMembersMappingProfile(fromKey, toKey, forAllMembersMappingSuffix));
});
automapper
.createMap(fromKey, toKey)
.withProfile('ForAllMembers');
// act
var destination = automapper.map(fromKey, toKey, source);
// assert
expect(destination.prop1).toEqual(source.prop1 + forAllMembersMappingSuffix);
expect(destination.prop2).toEqual(source.prop2 + forAllMembersMappingSuffix);
});
it('should be able to use a mapping profile with convertUsing', () => {
// arrange
var fromKey = 'should be able to use a mapping profile ';
var toKey = 'with convertUsing' + postfix;
var source = { prop1: 'prop1', prop2: 'prop2' };
var convertUsingSuffix = ' [convertUsing]';
automapper.initialize((config: IConfiguration) => {
config.addProfile(new ConvertUsingMappingProfile(fromKey, toKey, convertUsingSuffix));
});
automapper
.createMap(fromKey, toKey)
.withProfile('ConvertUsing');
// act
var destination = automapper.map(fromKey, toKey, source);
// assert
expect(destination.prop1).toEqual(source.prop1 + convertUsingSuffix);
expect(destination.prop2).toEqual(source.prop2 + convertUsingSuffix);
});
});
} | the_stack |
import { BoundingBox, Paragraph, Word, Line } from './../../types/DocumentRepresentation';
const ARABIC_REGEXP = /[0-9]+(\.[0-9]+)?( |$)/g;
const ROMAN_REGEXP = /(?=[MDCLXVI])M*(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})( |$)/gi;
export const THRESHOLD = 0.4;
export function TOCDetected(allParagraphs: Paragraph[], pageKeywords: string[]): Paragraph[] {
let tocCandidates: Paragraph[] = [];
let tocParagraphs: Paragraph[] = [];
let tocIntegerRight: Word[] = [];
let tocRomanNumberRight: Word[] = [];
let tocIntegerLeft: Word[] = [];
if (allParagraphs.length === 0) {
return [];
}
const { right, left, roman, candidates } = storeNumAndRomanNum(allParagraphs, pageKeywords);
tocIntegerRight = findTocNumber(right);
tocRomanNumberRight = findTocRomanNumber(roman);
tocIntegerLeft = findTocNumber(left);
tocCandidates = candidates;
findTocPara(tocCandidates, tocIntegerRight, tocParagraphs);
findTocPara(tocCandidates, tocRomanNumberRight, tocParagraphs);
findTocPara(tocCandidates, tocIntegerLeft, tocParagraphs);
tocParagraphs.forEach(paragraph => {
paragraph.content.forEach(line => {
if (line.content.length === 1) {
completeTocLine(tocParagraphs, allParagraphs, line);
}
});
});
tocCandidates.forEach(candidate => {
if (
hasPageNKeyword(candidate, pageKeywords) &&
tocParagraphs.indexOf(candidate) === -1
) {
tocParagraphs.push(candidate);
}
});
return tocParagraphs;
}
/*
- Searches for text starting or finishing in numbers in the Left or right 10% width area of the BBox,
then store them by alignment.
- Searches for text containing pagekeywords following by a digit.
*/
function storeNumAndRomanNum(
allParagraphs: Paragraph[],
pageKeywords: string[],
): { right: Word[][]; left: Word[][]; roman: Word[][]; candidates: Paragraph[] } {
let numberRight: Word[][] = [];
let numberLeft: Word[][] = [];
let romanNumberRight: Word[][] = [];
let paragraphsCandidates: Paragraph[] = [];
for (const paragraph of allParagraphs) {
const w = paragraph.width * 0.1;
const intersectionBoxRight = new BoundingBox(
paragraph.right - w,
paragraph.top,
w,
paragraph.height,
);
const intersectionBoxLeft = new BoundingBox(paragraph.left, paragraph.top, w, paragraph.height);
const numbersInsideIntersectionRight = paragraph
.getWords()
.filter(wordOverlaps(intersectionBoxRight))
.filter(word => !isSeparator(word));
const numbersInsideIntersectionLeft = paragraph
.getWords()
.filter(wordOverlaps(intersectionBoxLeft))
.filter(word => !isSeparator(word));
if (
numbersInsideIntersectionRight.filter(isNumberRight).length >
Math.floor(numbersInsideIntersectionRight.length * 0.5) ||
numbersInsideIntersectionLeft.filter(isNumberLeft).length >
Math.floor(numbersInsideIntersectionLeft.length * 0.5) ||
hasPageNKeyword(paragraph, pageKeywords)
) {
paragraphsCandidates.push(paragraph);
numbersInsideIntersectionRight.forEach(word => {
if (word.toString().match(ARABIC_REGEXP)) {
addAlignedNumberRight(numberRight, word);
} else if (word.toString().match(ROMAN_REGEXP)) {
addAlignedNumberRight(romanNumberRight, word);
}
});
numbersInsideIntersectionLeft.forEach(word => {
if (word.toString().match(ARABIC_REGEXP)) {
addAlignedNumberLeft(numberLeft, word);
} else if (word.toString().match(ROMAN_REGEXP)) {
addAlignedNumberRight(romanNumberRight, word);
}
});
}
}
return {
right: sortBoxNumber(numberRight),
left: sortBoxNumber(numberLeft),
roman: sortBoxNumber(romanNumberRight),
candidates: paragraphsCandidates,
};
}
function wordOverlaps(box: BoundingBox): (word: Word) => boolean {
return word => BoundingBox.getOverlap(word.box, box).box1OverlapProportion > 0;
}
function isNumberRight(word: Word): boolean {
const decimalNumbers = new RegExp(ARABIC_REGEXP);
const romanNumbers = new RegExp(ROMAN_REGEXP);
const w = word.toString();
return decimalNumbers.test(w) || romanNumbers.test(w);
}
function isNumberLeft(word: Word): boolean {
const decimalNumbers = new RegExp(ARABIC_REGEXP);
const w = word.toString();
return decimalNumbers.test(w);
}
function isSeparator(word: Word): boolean {
const separators = new RegExp(/^[-. ]+$/);
return separators.test(word.toString().trim());
}
function hasPageNKeyword(p: Paragraph, pageKeywords: string[]): boolean {
const regexp = `^(${pageKeywords.join('|')}).* (\\d+) (.+)`;
return new RegExp(regexp, 'gi').test(p.toString());
}
function addAlignedNumberRight(storeBoxNumber: Word[][], number: Word) {
const indexValue = storeBoxNumber.findIndex(
aNum =>
(aNum[0].box.left + aNum[0].box.width - 5 <= number.box.left + number.box.width &&
aNum[0].box.left + aNum[0].box.width + 10 >= number.box.left + number.box.width) ||
(aNum[0].box.left + aNum[0].box.width - 20 <= number.box.left &&
aNum[0].box.left + aNum[0].box.width - 5 >= number.box.left),
);
if (indexValue !== -1 && storeBoxNumber[indexValue].indexOf(number) === -1) {
storeBoxNumber[indexValue].push(number);
} else if (indexValue === -1) {
storeBoxNumber.push([number]);
}
}
function addAlignedNumberLeft(storeBoxNumberLeft: Word[][], number: Word) {
const indexValueExist = storeBoxNumberLeft.findIndex(
aNum =>
aNum[0].box.left - 15 <= number.box.left &&
aNum[0].box.left + 15 >= number.box.left + number.box.width,
);
if (indexValueExist !== -1) {
storeBoxNumberLeft[indexValueExist].push(number);
} else {
storeBoxNumberLeft.push([number]);
}
}
function sortBoxNumber(storeBoxNumber: Word[][]): Word[][] {
storeBoxNumber.sort((a, b) => b.length - a.length);
for (let boxes of storeBoxNumber) {
boxes.sort((a, b) => a.box.top - b.box.top);
}
return storeBoxNumber;
}
/*
Searches for a good rate of integer number,
then searches for a good rate of integer in ascending order
*/
function findTocNumber(storeBoxNumber: Word[][]): Word[] {
let nbOfNumber: number;
let storedInteger: number[] = [];
let nbOfIntegerInOrder = 0;
for (let box of storeBoxNumber) {
nbOfNumber = box.length;
for (const word of box) {
let num = Number(word.toString().match(ARABIC_REGEXP));
if (Number.isInteger(num)) {
storedInteger.push(num);
}
}
if (storedInteger.length / nbOfNumber > 0.75) {
nbOfIntegerInOrder = findIntegerAscendingOrder(storedInteger);
if (nbOfIntegerInOrder / storedInteger.length > 0.75) {
return box;
}
}
}
return null;
}
/*
Searches for a good rate of roman number in ascending order.
*/
function findTocRomanNumber(storeBoxNumber: Word[][]): Word[] {
let storedRomanNbInteger: number[] = [];
let nbOfRomanNbIntegerInOrder = 0;
for (let box of storeBoxNumber) {
for (const word of box) {
storedRomanNbInteger.push(romanToArabic(word.toString().match(ROMAN_REGEXP)));
}
nbOfRomanNbIntegerInOrder = findIntegerAscendingOrder(storedRomanNbInteger);
if (nbOfRomanNbIntegerInOrder / storedRomanNbInteger.length > 0.75) {
return box;
}
}
return null;
}
function romanToArabic(romanNumber): number {
romanNumber = romanNumber[0].toUpperCase();
const romanNumList = ['CM', 'M', 'CD', 'D', 'XC', 'C', 'XL', 'L', 'IX', 'X', 'IV', 'V', 'I'];
const corresp = [900, 1000, 400, 500, 90, 100, 40, 50, 9, 10, 4, 5, 1];
let index = 0;
let num = 0;
for (let rn in romanNumList) {
index = romanNumber.indexOf(romanNumList[rn]);
while (index != -1) {
num += corresp[rn];
romanNumber = romanNumber.replace(romanNumList[rn], '-');
index = romanNumber.indexOf(romanNumList[rn]);
}
}
return num;
}
function findIntegerAscendingOrder(storedInteger: number[]): number {
let maxIntegerInOrder = 0;
let iStart = 0;
let nbIntegerInOrder = 1;
while (iStart < storedInteger.length / 3 && maxIntegerInOrder < storedInteger.length * 0.7) {
let step = 1;
let iLastInOrder = iStart;
let iCompare = iLastInOrder + step;
while (iCompare < storedInteger.length) {
if (storedInteger[iCompare] >= storedInteger[iLastInOrder]) {
nbIntegerInOrder++;
iLastInOrder = iCompare;
step = 0;
}
step++;
iCompare = iLastInOrder + step;
}
if (nbIntegerInOrder > maxIntegerInOrder) {
maxIntegerInOrder = nbIntegerInOrder;
}
iStart++;
nbIntegerInOrder = 1;
}
return maxIntegerInOrder;
}
/*
Searches for the parents paragraphs containing TOC numbers.
*/
function findTocPara(tocCandidatesParagraphs: Paragraph[], tocInteger: Word[], tocParagraphs: Paragraph[]) {
if (!tocInteger || tocInteger.length < 2) {
return;
}
for (let i = 0; i < tocCandidatesParagraphs.length; i++) {
for (let j = 0; j < tocCandidatesParagraphs[i].content.length; j++) {
for (let integer of tocInteger) {
if (
tocCandidatesParagraphs[i].content[j].content.find(word => word.id === integer.id) &&
!containsObject(tocCandidatesParagraphs[i], tocParagraphs)
) {
tocParagraphs.push(tocCandidatesParagraphs[i]);
break;
}
}
}
}
}
function containsObject(obj: Paragraph, list: Paragraph[]): boolean {
return list.some(e => e.id === obj.id);
}
/*
Searches for paragraphs aligned with alone TOC number (cases with no leaders).
*/
function completeTocLine(tocParagraphs: Paragraph[], allParagraphs: Paragraph[], line: Line) {
for (let i = 0; i < allParagraphs.length; i++) {
if (
allParagraphs[i].content.find(
oneLine =>
oneLine.box.top >= line.box.top - 1 &&
oneLine.box.top <= line.box.top + 1 &&
!tocParagraphs.includes(allParagraphs[i]),
)
) {
if (allParagraphs[i].left < line.box.left) {
tocParagraphs.unshift(allParagraphs[i]);
} else {
tocParagraphs.push(allParagraphs[i]);
}
}
}
} | the_stack |
/**
* This file contains a sample demonstrating TPM related parts of the device side of the protocol used by the Azure IoT DRS
*/
// When using tss.js package replace "../lib/index.js" with "tss.js"
import * as tss from "../lib/index.js";
import { TPM_HANDLE, TPM_ALG_ID, TPM_RC, TPM_HT, TPM_PT, TPMA_OBJECT, TPMT_PUBLIC, TPM2B_PRIVATE, Owner, Endorsement, Session, NullPwSession, NullSymDef, Tpm, TpmBuffer, TpmError, Crypto, TPMT_SENSITIVE } from "../lib/index.js";
/*
import * as tss from "../lib/TpmTypes.js";
import {TPM_HANDLE, TPM_ALG_ID, TPM_RC, TPM_HT, TPM_PT, TPMA_OBJECT, TPMT_PUBLIC, TPM2B_PRIVATE} from "../lib/TpmTypes.js";
import {Owner, Endorsement, Session, NullPwSession, NullSymDef} from "../lib/Tss.js";
import {Tpm} from "../lib/Tpm.js";
import {TpmBuffer} from "../lib/TpmMarshaller.js";
import {TpmError} from "../lib/TpmBase.js";
import {Crypto} from "../lib/Crypt.js";
*/
import * as crypto from 'crypto';
const TEST_MODE: boolean = true;
const Aes128SymDef = new tss.TPMT_SYM_DEF_OBJECT(TPM_ALG_ID.AES, 128, TPM_ALG_ID.CFB);
const Aes256SymDef = new tss.TPMT_SYM_DEF_OBJECT(TPM_ALG_ID.AES, 256, TPM_ALG_ID.CFB);
const EK_PersHandle: TPM_HANDLE = new TPM_HANDLE(0x81010001);
const SRK_PersHandle: TPM_HANDLE = new TPM_HANDLE(0x81000001);
const ID_KEY_PersHandle: TPM_HANDLE = new TPM_HANDLE(0x81000100);
// Template of the Endorsement Key (EK)
const EkTemplate = new TPMT_PUBLIC(TPM_ALG_ID.SHA256,
TPMA_OBJECT.restricted | TPMA_OBJECT.decrypt | TPMA_OBJECT.fixedTPM | TPMA_OBJECT.fixedParent
| TPMA_OBJECT.adminWithPolicy | TPMA_OBJECT.sensitiveDataOrigin,
new Buffer('837197674484b3f81a90cc8d46a5d724fd52d76e06520b64f2a1da1b331469aa', 'hex'),
new tss.TPMS_RSA_PARMS(Aes128SymDef, new tss.TPMS_NULL_ASYM_SCHEME(), 2048, 0),
new tss.TPM2B_PUBLIC_KEY_RSA());
// Template of the Storage Root Key (SRK)
const SrkTemplate = new TPMT_PUBLIC(TPM_ALG_ID.SHA256,
TPMA_OBJECT.restricted | TPMA_OBJECT.decrypt | TPMA_OBJECT.fixedTPM | TPMA_OBJECT.fixedParent
| TPMA_OBJECT.noDA | TPMA_OBJECT.userWithAuth | TPMA_OBJECT.sensitiveDataOrigin,
null,
new tss.TPMS_RSA_PARMS(Aes128SymDef, new tss.TPMS_NULL_ASYM_SCHEME(), 2048, 0),
new tss.TPM2B_PUBLIC_KEY_RSA());
// Template of a signing RSA key
const SigKeyTemplate = new TPMT_PUBLIC(TPM_ALG_ID.SHA1,
TPMA_OBJECT.sign | TPMA_OBJECT.fixedTPM | TPMA_OBJECT.fixedParent
| TPMA_OBJECT.userWithAuth | TPMA_OBJECT.sensitiveDataOrigin,
null,
new tss.TPMS_RSA_PARMS(Aes256SymDef, new tss.TPMS_SIG_SCHEME_RSASSA(TPM_ALG_ID.SHA1), 1024, 0),
new tss.TPM2B_PUBLIC_KEY_RSA());
/**
* Data structure with the information about persistent keys used in the protocol (EK and SRK).
*/
class PersKeyInfo {
public constructor(
/**
* Human readable name for debugging/logging purposes only
*/
public name: string,
/**
* The TPM hierarachy, to which the key belongs
* @note All the keys are persisted in the owner hierarchy disregarding their mother one
*/
public hierarchy: TPM_HANDLE,
/**
* Handle value where the persistent key is expected to be found
*/
public handle: TPM_HANDLE,
/**
* Template to be used for key cretaion if the persistent key with the given handle does not exist
*/
public template: TPMT_PUBLIC,
/**
* Public part of the persistent key. Identical to its template in all regards, save that it
* additionally has its 'unique' field (i.e. actual public key bits) initialized.
*/
public pub: TPMT_PUBLIC = null
) {}
};
const PersKeys: PersKeyInfo[] = [new PersKeyInfo('EK', Endorsement, EK_PersHandle, EkTemplate),
new PersKeyInfo('SRK', Owner, SRK_PersHandle, SrkTemplate)];
const EK: number = 0;
const SRK: number = 1;
let useTpmSim: boolean = false;
let cleanOnly: boolean = false;
console.log('DrsClientNode started on ' + (process.platform == 'win32' ? 'Windows' : process.platform) + '!!');
processCmdLine();
let tpm = new Tpm(useTpmSim);
tpm.connect(drsClientSampleMain);
function processCmdLine()
{
for (let i = 2; i < process.argv.length; ++i)
{
let opt: string = process.argv[i];
if (opt[0] == '-' || opt[0] == '/')
opt = opt.substr(opt.length > 1 && opt[1] == '-' ? 2 : 1);
if (opt == 'sim' || opt == 's')
useTpmSim = true;
else if (opt == 'clear' || opt == 'c')
cleanOnly = true;
}
}
function drsClientSampleMain(): void
{
if (cleanOnly)
{
console.log('Removing EK & SRK');
clearPersistentPrimary(PersKeys);
}
else if (TEST_MODE) {
// Issue a simple bi-directional command to make sure that TPM communication channel is functional
tpm.GetRandom(0x20, (err: TpmError, response: Buffer) => {
console.log('GetRandom() returned ' + response.length + ' bytes: ' + new Uint8Array(response));
// Clean debris possibly left from the previous run (one entity of each kind)
let numDandlingHandles: number = 0;
tpm.FlushContext(new TPM_HANDLE(TPM_HT.HMAC_SESSION << 24), (err: TpmError) => {
numDandlingHandles += err ? 0 : 1;
tpm.FlushContext(new TPM_HANDLE(TPM_HT.POLICY_SESSION << 24), (err: TpmError) => {
numDandlingHandles += err ? 0 : 1;
tpm.FlushContext(new TPM_HANDLE(TPM_HT.TRANSIENT << 24), (err: TpmError) => {
numDandlingHandles += err ? 0 : 1;
console.log('Cleanup pahse: ' + numDandlingHandles + ' dandling handles discovered');
// Kick off sample's main logic
createPersistentPrimary(PersKeys); }) }) }) });
}
else {
// Kick off sample's main logic
createPersistentPrimary(PersKeys);
}
}
function clearPersistentPrimary(persKeys: PersKeyInfo[]): void
{
let pki = persKeys[0];
tpm.ReadPublic(pki.handle, (err: TpmError, resp?: tss.ReadPublicResponse) => {
console.log('ReadPublic(' + pki.name + ') returned ' + TPM_RC[tpm.lastResponseCode]);
if (!err) {
// Delete the existing persistent key
tpm.EvictControl(Owner, pki.handle, pki.handle, () => {
console.log('EvictControl(' + pki.name + ') returned ' + TPM_RC[tpm.lastResponseCode]);
// Recurse to delete the next key in the list
if (persKeys.length > 1)
clearPersistentPrimary(persKeys.slice(1, persKeys.length));
});
}
else
{
// Recurse to delete the next key in the list
if (persKeys.length > 1)
clearPersistentPrimary(persKeys.slice(1, persKeys.length));
else
console.log('All persistent keys cleared');
} });
} // clearPersistentPrimary()
/**
* Makes sure that the device persistent TPM keys the protocol relies on (EK and SRK) are in place.
*
* @note On a real device EK should be pre-installed, and its public part made available to the
* DRS service before the device gets to the end user.
*/
function createPersistentPrimary(persKeys: PersKeyInfo[]): void
{
let pki = persKeys[0];
tpm.ReadPublic(pki.handle, (err: TpmError, resp?: tss.ReadPublicResponse) => {
console.log('ReadPublic(' + pki.name + ') returned ' + TPM_RC[tpm.lastResponseCode]);
if (err) {
tpm.CreatePrimary(pki.hierarchy, new tss.TPMS_SENSITIVE_CREATE(), pki.template, null, null,
(err: TpmError, resp: tss.CreatePrimaryResponse) => {
if (failed(err))
return;
pki.pub = resp.outPublic;
tpm.EvictControl(Owner, resp.handle, pki.handle, (err) => {
if (failed(err))
return;
console.log('EvictControl() for ' + pki.name + ' succeeded');
if(!TEST_MODE && TEST_MODE && pki.hierarchy == Owner)
{
// TODO: Fix this test branch (then remove '!TEST_MODE' from the 'if' above)
tpm.withSessions(NullPwSession)
.Create(resp.handle, new tss.TPMS_SENSITIVE_CREATE(), SigKeyTemplate, null, [new tss.TPMS_PCR_SELECTION(TPM_ALG_ID.SHA1, new Buffer([5, 0, 0]))],
(err: TpmError, sigKey: tss.CreateResponse) => {
if (failed(err))
return;
console.log('Signing key was successfully created');
tpm.withSessions(NullPwSession)
.Load(resp.handle, sigKey.outPrivate, sigKey.outPublic,
(err: TpmError, hSigKey: TPM_HANDLE) => {
tpm.withSessions(NullPwSession)
.CertifyCreation(hSigKey, resp.handle, null, resp.creationHash, new tss.TPMS_NULL_SIG_SCHEME(), resp.creationTicket,
(err: TpmError, certResp: tss.CertifyCreationResponse) => {
if (failed(err))
return;
console.log('Primary key certification succeeded');
tpm.FlushContext(hSigKey, () => {
if (failed(err))
return;
console.log('Successfully deleted the signing key');
tpm.FlushContext(resp.handle, () => {
console.log('FlushContext(0x' + resp.handle.handle.toString(16) + ') returned ' + TPM_RC[tpm.lastResponseCode]);
createPersistentPrimary_Cont(persKeys);
}) }) }) }) })
}
else {
tpm.FlushContext(resp.handle, () => {
console.log('FlushContext(0x' + resp.handle.handle.toString(16) + ') returned ' + TPM_RC[tpm.lastResponseCode]);
createPersistentPrimary_Cont(persKeys);
})
}
}) });
}
else if (TEST_MODE) {
// Delete the existing persistent key in order to test key creation commands
tpm.EvictControl(Owner, pki.handle, pki.handle, () => {
console.log('EvictControl() for' + pki.name + ' returned ' + TPM_RC[tpm.lastResponseCode]);
// Recurse to create the key anew
createPersistentPrimary(persKeys); });
}
else
{
pki.pub = resp.outPublic;
createPersistentPrimary_Cont(persKeys);
} });
} // createPersistentPrimary()
function createPersistentPrimary_Cont(persKeys: PersKeyInfo[]): void
{
if (persKeys.length > 1)
{
// Create the next persistent key
createPersistentPrimary(persKeys.slice(1, persKeys.length));
return;
}
// Proceed to the new ID Key activation logic
//if (process.platform == 'win32')
beginActivation();
}
/**
* Represents the structure of the activation blob generated by the DRS service in response to device provisioning request:
* Note that 'credBlob' and 'idKeyPub' members are marshaled by the DRS sized data structures, i.e. prepended with a 2-byte
* size field (see the 'fromTpm()' method).
*/
class DrsActivationBlob
{
public credBlob: tss.TPMS_ID_OBJECT;
public encSecret: tss.TPM2B_ENCRYPTED_SECRET;
public idKeyDupBlob: tss.TPM2B_PRIVATE;
public encWrapKey: tss.TPM2B_ENCRYPTED_SECRET;
public idKeyPub: TPMT_PUBLIC;
public encUriData: tss.TPM2B_DATA;
constructor (actBlob: TpmBuffer | Buffer = null)
{
if (actBlob != null)
this.fromTpm(actBlob);
}
fromTpm (actBlob: TpmBuffer | Buffer)
{
let buf: TpmBuffer = actBlob instanceof Buffer ? new TpmBuffer(actBlob) : actBlob;
this.credBlob = buf.createSizedObj(tss.TPMS_ID_OBJECT);
//console.log("credBlob end: " + actBlob.getCurPos());
this.encSecret = buf.createObj(tss.TPM2B_ENCRYPTED_SECRET);
//console.log("encSecret end: " + actBlob.getCurPos() + "; size = " + this.encSecret.secret.length);
this.idKeyDupBlob = buf.createObj(tss.TPM2B_PRIVATE);
//console.log("idKeyDupBlob end: " + actBlob.getCurPos() + "; size = " + this.idKeyDupBlob.buffer.length);
this.encWrapKey = buf.createObj(tss.TPM2B_ENCRYPTED_SECRET);
//console.log("encWrapKey end: " + actBlob.getCurPos() + "; size = " + this.encWrapKey.secret.length);
this.idKeyPub = buf.createSizedObj(TPMT_PUBLIC);
//console.log("idKeyPub end: " + actBlob.getCurPos());
this.encUriData = buf.createObj(tss.TPM2B_DATA);
//console.log("encUriData end: " + actBlob.getCurPos());
if (!buf.isOk())
throw new Error("Failed to unmarshal Activation Blob");
if (buf.curPos != buf.size)
console.log("WARNING: Activation Blob sent by DRS has contains extra unidentified data");
}
} // class DrsActivationBlob
//let policySess: Session = null;
/**
* Performs the main phase of the device registration protocol:
* - sends EK and SRK data to the DRS;
* - parses returned activation data;
* - imports and persists Device ID Key generated by the DRS.
*
* Also demonstrates how to decrypt secret URI data sent by the DRS.
*/
//import * as drs from "./DrsServerEmulator.js";
let drs = null;
function beginActivation(): void
{
// Note that here we need complete public parts containg the actual public key bits, not just the corresponding templates.
// Complete public parts are returned by ReadPublic() or CretePrimary() commands in the above code.
let ekPub: Buffer = PersKeys[EK].pub.asTpm2B();
let srkPub: Buffer = PersKeys[SRK].pub.asTpm2B();
// Perform the DRS request.
// Note that this code uses a call out to an emulator. The actual SDK code will have to use
// one of the web protocols supported by the DRS to exchange these data.
let rawActBlob = drsGetActivationBlob(tpm, ekPub, srkPub, doActivation);
}
function doActivation(rawActBlob: Buffer): void
{
console.log("Raw Activation Blob size: " + rawActBlob.length);
// Unmarshal components of the activation blob received from the DRS
let actBlob = new DrsActivationBlob(rawActBlob);
// Start a policy session to be used with ActivateCredential()
let nonceCaller = crypto.randomBytes(20);
tpm.StartAuthSession(null, null, nonceCaller, null, tss.TPM_SE.POLICY, NullSymDef, TPM_ALG_ID.SHA256,
(err: TpmError, resp: tss.StartAuthSessionResponse) => {
console.log('StartAuthSession(POLICY_SESS) returned ' + TPM_RC[tpm.lastResponseCode] + '; sess handle: ' + resp.handle.handle.toString(16));
let policySess = new Session(resp.handle, resp.nonceTPM);
// Apply the policy necessary to authorize an EK on Windows
tpm.PolicySecret(Endorsement, policySess.SessIn.sessionHandle, null, null, null, 0,
(err: TpmError, resp: tss.PolicySecretResponse) => {
console.log('PolicySecret() returned ' + TPM_RC[tpm.lastResponseCode]);
// Use ActivateCredential() to decrypt symmetric key that is used as an inner protector
// of the duplication blob of the new Device ID key generated by DRS.
tpm.withSessions(null, policySess)
.ActivateCredential(SRK_PersHandle, EK_PersHandle, actBlob.credBlob, actBlob.encSecret.secret,
(err: TpmError, innerWrapKey: Buffer) => {
console.log('ActivateCredential() returned ' + TPM_RC[tpm.lastResponseCode] + '; innerWrapKey size ' + innerWrapKey.length);
// Initialize parameters of the symmetric key used by DRS
// Note that the client uses the key size chosen by DRS, but other parameters are fixes (an AES key in CFB mode).
let symDef = new tss.TPMT_SYM_DEF_OBJECT(TPM_ALG_ID.AES, innerWrapKey.length * 8, TPM_ALG_ID.CFB);
// Import the new Device ID key issued by DRS to the device's TPM
tpm.Import(SRK_PersHandle, innerWrapKey, actBlob.idKeyPub, actBlob.idKeyDupBlob, actBlob.encWrapKey.secret, symDef,
(err: TpmError, idKeyPriv: TPM2B_PRIVATE) => {
console.log('Import() returned ' + TPM_RC[tpm.lastResponseCode] + '; idKeyPriv size ' + idKeyPriv.buffer.length);
// Load the imported key into the TPM
tpm.Load(SRK_PersHandle, idKeyPriv, actBlob.idKeyPub,
(err: TpmError, hIdKey: TPM_HANDLE) => {
console.log('Load() returned ' + TPM_RC[tpm.lastResponseCode] + '; ID key handle: 0x' + hIdKey.handle.toString(16));
// Remove possibly existing persistent instance of the previous Device ID key
tpm.EvictControl(Owner, ID_KEY_PersHandle, ID_KEY_PersHandle, () => {
// Persist the new Device ID key
tpm.EvictControl(Owner, hIdKey, ID_KEY_PersHandle,
() => {
console.log('EvictControl(0x' + hIdKey.handle.toString(16) + ', 0x' + ID_KEY_PersHandle.handle.toString(16) +
') returned ' + TPM_RC[tpm.lastResponseCode]);
// Free the ID Key transient handle
tpm.FlushContext(hIdKey, () => {
console.log('FlushContext(TRANS_ID_KEY) returned ' + TPM_RC[tpm.lastResponseCode]);
// Free the session object
tpm.FlushContext(policySess.SessIn.sessionHandle,
() => {
console.log('FlushContext(POLICY_SESS) returned ' + TPM_RC[tpm.lastResponseCode]);
//
// Decrypt the secret URI data sent by the DRS
//
let symAlg = 'AES-' + (innerWrapKey.length * 8).toString(10) + '-CFB';
let iv = new Buffer(16);
iv.fill(0);
let dec: crypto.Decipher = crypto.createDecipheriv(symAlg, innerWrapKey, iv);
let decUriData: Buffer = dec.update(actBlob.encUriData.buffer);
console.log('Decipher.update returned ' + decUriData.length + ' bytes: ' + decUriData);
let decFinal: Buffer = dec.final();
console.log('Decipher.final returned ' + decFinal.length + ' bytes: ' + decFinal);
//
// Example of signing a device token using the new Device ID key
//
let idKeyHashAlg: TPM_ALG_ID = (<tss.TPMS_SCHEME_HMAC>(<tss.TPMS_KEYEDHASH_PARMS>actBlob.idKeyPub.parameters).scheme).hashAlg;
SignDeviceToken(idKeyHashAlg);
}) }) }) }) }) }) }) }) });
} // doActivation()
/**
* Example of signing a device token using the new persistent Device ID key
*/
function SignDeviceToken(idKeyHashAlg: TPM_ALG_ID): void
{
//TpmHelpers.getTpmProperty(tpm, TPM_PT.INPUT_BUFFER);
//let MaxInputBuffer: number = 1024;
tpm.GetCapability(tss.TPM_CAP.TPM_PROPERTIES, TPM_PT.INPUT_BUFFER, 1,
(err: TpmError, caps: tss.GetCapabilityResponse) => {
let props = <tss.TPML_TAGGED_TPM_PROPERTY>caps.capabilityData;
if (props.tpmProperty.length != 1 || props.tpmProperty[0].property != TPM_PT.INPUT_BUFFER)
throw new Error("Unexpected result of TPM2_GetCapability(TPM_PT.INPUT_BUFFER)");
let MaxInputBuffer: number = props.tpmProperty[0].value;
// First, the code for a short token (<= MaxInputBuffer) signing
let deviceIdToken: Buffer = crypto.randomBytes(800);
if (deviceIdToken.length > MaxInputBuffer)
throw new Error('Too long token to HMAC');
tpm.HMAC(ID_KEY_PersHandle, deviceIdToken, idKeyHashAlg,
(err: TpmError, signature: Buffer) => {
console.log('HMAC() returned ' + TPM_RC[tpm.lastResponseCode] + '; signature size ' + signature.length);
if (TEST_MODE)
{
// Verify the signature correctness
let sigOK: boolean = drsVerifyIdSignature(tpm, deviceIdToken, signature);
console.log('Signature over short token: ' + (sigOK ? 'OK' : 'FAILED'));
signature[16] ^= 0xCC;
sigOK = drsVerifyIdSignature(tpm, deviceIdToken, signature);
console.log('Bad signature over short token: ' + (sigOK ? 'OK' : 'FAILED'));
}
// Now the code for long token (> MaxInputBuffer) signing
deviceIdToken = crypto.randomBytes(5500);
let curPos: number = 0;
let bytesLeft: number = deviceIdToken.length;
let hSequence: TPM_HANDLE = null;
let loopFn = () => {
if (bytesLeft > MaxInputBuffer) {
tpm.SequenceUpdate(hSequence, deviceIdToken.slice(curPos, curPos + MaxInputBuffer), loopFn);
console.log('SequenceUpdate() returned ' + TPM_RC[tpm.lastResponseCode] +
' for slice [' + curPos + ', ' + (curPos + MaxInputBuffer) + ']');
bytesLeft -= MaxInputBuffer;
curPos += MaxInputBuffer;
}
else {
tpm.SequenceComplete(hSequence, deviceIdToken.slice(curPos, curPos + bytesLeft), new TPM_HANDLE(tss.TPM_RH.NULL),
(err: TpmError, resp: tss.SequenceCompleteResponse) => {
console.log('SequenceComplete() returned ' + TPM_RC[tpm.lastResponseCode]);
console.log('signature size ' + signature.length);
if (TEST_MODE)
{
let sigOK: boolean = drsVerifyIdSignature(tpm, deviceIdToken, resp.result);
console.log('Signature over long token: ' + (sigOK ? 'OK' : 'FAILED'));
}
// END OF SAMPLE
finish(true, 'Sample completed successfully!');
});
}
};
tpm.HMAC_Start(ID_KEY_PersHandle, new Buffer(0), idKeyHashAlg,
(err: TpmError, hSeq: TPM_HANDLE) => {
console.log('HMAC_Start() returned ' + TPM_RC[tpm.lastResponseCode]);
hSequence = hSeq;
loopFn();
}) }) });
} // SignDeviceToken()
//
// DRS logic emulation
//
let keyBytes = crypto.randomBytes(32);
let idKeySens = new tss.TPMS_SENSITIVE_CREATE(null, keyBytes);
let idKeyTemplate = new TPMT_PUBLIC(TPM_ALG_ID.SHA256,
tss.TPMA_OBJECT.sign | tss.TPMA_OBJECT.userWithAuth | tss.TPMA_OBJECT.noDA,
null, // Will be filled by getActivationBlob
new tss.TPMS_KEYEDHASH_PARMS(new tss.TPMS_SCHEME_HMAC(TPM_ALG_ID.SHA256)),
new tss.TPM2B_DIGEST_KEYEDHASH());
export function drsVerifyIdSignature(tpm: Tpm, data: Buffer, sig: Buffer): boolean
{
let hmacOverData = Crypto.hmac(TPM_ALG_ID.SHA256, idKeySens.data, data);
return Buffer.compare(sig, hmacOverData) == 0;
/*
tpm.withSession(NullPwSession)
.CreatePrimary(owner, idKeySens, idKeyTemplate, null, [],
(keyCreationErr: TpmError, idKey: tss.CreatePrimaryResponse) => {
if (keyCreationErr)
return setImmediate(continuation, keyCreationErr);
tpm.allowErrors()
.VerifySignature(idKey.handle, data, sig,
(verificationErr: TpmError, verified: tss.TPMT_TK_VERIFIED) => {
tpm.FlushContext(idKey.handle, (err: TpmError) => {
setImmediate(continuation, verificationErr);
}); }); });
*/
}
export function drsGetActivationBlob(tpm: Tpm, ekPubBlob: Buffer, srkPubBlob: Buffer, continuation: (actBlob: Buffer) => void): void
{
let ekPub: TPMT_PUBLIC = new TpmBuffer(ekPubBlob).createObj(tss.TPM2B_PUBLIC).publicArea;
let srkPub: TPMT_PUBLIC = new TpmBuffer(srkPubBlob).createObj(tss.TPM2B_PUBLIC).publicArea;
// Start a policy session to be used with ActivateCredential()
let nonceCaller = crypto.randomBytes(20);
tpm.StartAuthSession(null, null, nonceCaller, null, tss.TPM_SE.POLICY, NullSymDef, TPM_ALG_ID.SHA256,
(err: TpmError, respSas: tss.StartAuthSessionResponse) => {
let hSess = respSas.handle;
console.log('DRS >> StartAuthSession(POLICY_SESS) returned ' + TPM_RC[tpm.lastResponseCode] + '; sess handle: ' + hSess.handle.toString(16));
let sess = new Session(hSess, respSas.nonceTPM);
// Run the policy command necessary for key duplication
tpm.PolicyCommandCode(hSess, tss.TPM_CC.Duplicate,
(err: TpmError) => {
console.log('DRS >> PolicyCommandCode() returned ' + TPM_RC[tpm.lastResponseCode]);
// Retrieve the policy digest computed by the TPM
tpm.PolicyGetDigest(hSess, (err: TpmError, dupPolicyDigest: Buffer) => {
console.log('DRS >> PolicyGetDigest() returned ' + TPM_RC[tpm.lastResponseCode]);
idKeyTemplate.authPolicy = dupPolicyDigest;
tpm.withSession(NullPwSession)
.CreatePrimary(Owner, idKeySens, idKeyTemplate, null, [],
(err: TpmError, idKey: tss.CreatePrimaryResponse) => {
console.log('DRS >> CreatePrimary(idKey) returned ' + TPM_RC[tpm.lastResponseCode]);
tpm.LoadExternal(null, srkPub, Owner,
(err: TpmError, hSrkPub: tss.TPM_HANDLE) => {
console.log('DRS >> LoadExternal(SRKpub) returned ' + TPM_RC[tpm.lastResponseCode]);
let symWrapperDef = new tss.TPMT_SYM_DEF_OBJECT(TPM_ALG_ID.AES, 128, TPM_ALG_ID.CFB);
tpm.withSession(sess)
.Duplicate(idKey.handle, hSrkPub, null, symWrapperDef,
(err: TpmError, respDup: tss.DuplicateResponse) => {
console.log('DRS >> Duplicate(...) returned ' + TPM_RC[tpm.lastResponseCode]);
tpm.FlushContext(hSrkPub, (err: TpmError) => {
tpm.LoadExternal(null, ekPub, Endorsement,
(err: TpmError, hEkPub: tss.TPM_HANDLE) => {
console.log('DRS >> LoadExternal(EKpub) returned ' + TPM_RC[tpm.lastResponseCode]);
tpm.MakeCredential(hEkPub, respDup.encryptionKeyOut, srkPub.getName(),
(err: TpmError, cred: tss.MakeCredentialResponse) => {
console.log('DRS >> MakeCredential(...) returned ' + TPM_RC[tpm.lastResponseCode]);
// Delete the key and session handles
tpm.FlushContext(hEkPub, (err: TpmError) => {
tpm.FlushContext(idKey.handle, (err: TpmError) => {
tpm.FlushContext(hSess, (err: TpmError) => {
console.log('DRS >> Cleanup done');
//
// Encrypt URI data to be passed to the client device
//
let symWrapperTemplate = new TPMT_PUBLIC(TPM_ALG_ID.SHA256,
tss.TPMA_OBJECT.decrypt | tss.TPMA_OBJECT.encrypt | tss.TPMA_OBJECT.userWithAuth,
null,
new tss.TPMS_SYMCIPHER_PARMS(symWrapperDef),
new tss.TPM2B_DIGEST());
let sens = new tss.TPMS_SENSITIVE_CREATE(null, respDup.encryptionKeyOut);
tpm.withSession(NullPwSession)
.CreatePrimary(Owner, sens, symWrapperTemplate, null, [],
(err: TpmError, symWrapperKey: tss.CreatePrimaryResponse) => {
console.log('DRS >> CreatePrimary(SymWrapperKey) returned ' + TPM_RC[tpm.lastResponseCode]);
let uriData = Buffer.from("http://my.test.url/TestDeviceID=F4ED90771DAA7C0B3230FF675DF8A61104AE7C8BB0093FD6A", 'utf8');
let iv = Buffer.alloc(respDup.encryptionKeyOut.length, 0);
tpm.withSession(NullPwSession)
.EncryptDecrypt(symWrapperKey.handle, 0, TPM_ALG_ID.CFB, iv, uriData,
(err: TpmError, respEnc: tss.EncryptDecryptResponse) => {
console.log('DRS >> EncryptDecrypt() returned ' + TPM_RC[tpm.lastResponseCode]);
let encryptedUri = respEnc.outData;
// Delete the key and session handles
tpm.FlushContext(symWrapperKey.handle, (err: TpmError) => {
console.log('DRS >> Final cleanup done');
//
// Prepare data to send back to the DRS client
//
let actBlob = new TpmBuffer();
actBlob.writeSizedObj(cred.credentialBlob);
actBlob.writeSizedByteBuf(cred.secret);
respDup.duplicate.toTpm(actBlob);
actBlob.writeSizedByteBuf(respDup.outSymSeed);
actBlob.writeSizedObj(idKey.outPublic);
actBlob.writeSizedByteBuf(encryptedUri);
console.log('DRS >> Activation blob of ' + actBlob.curPos + ' bytes generated');
setImmediate(continuation, actBlob.trim());
}); }); }); }); }); }); }); }); }); }); }); }); }); }); });
} // drsGetActivationBlob()
function failed(err: TpmError, msg: string = null): boolean {
if (err) {
finish(false, msg ? msg : err.tpmCommand + " FAILED with error " + TPM_RC[err.responseCode] + ": " + err.message);
return true;
}
return false;
}
function finish(ok: boolean, msg: string) {
console.log(msg);
console.log('Node.JS demo ' + (ok ? 'successfully finished!' : 'terminated because of a TPM error'));
tpm.close();
} | the_stack |
import {
MalVal,
createMalFunc,
isMalFunc,
MalFuncThis,
MalError,
symbolFor as S,
isSymbol,
M_ISMACRO,
M_EVAL,
isMap,
MalMap,
isList,
createList as L,
MalNode,
isNode,
MalSeq,
M_PARAMS,
MalBind,
isSeq,
isVector,
setExpandInfo,
ExpandType,
getType,
isSymbolFor,
M_AST,
M_ENV,
isFunc,
MalSymbol,
} from './types'
import Env from './env'
import {printExp} from '.'
import {capital} from 'case'
const S_DEF = S('def')
const S_DEFVAR = S('defvar')
const S_LET = S('let')
const S_BINDING = S('binding')
const S_IF = S('if')
const S_DO = S('do')
const S_FN = S('fn')
const S_GET_ALL_SYMBOLS = S('get-all-symbols')
const S_FN_PARAMS = S('fn-params')
const S_FN_SUGAR = S('fn-sugar')
const S_MACRO = S('macro')
const S_MACROEXPAND = S('macroexpand')
const S_QUOTE = S('quote')
const S_QUASIQUOTE = S('quasiquote')
const S_TRY = S('try')
const S_CATCH = S('catch')
const S_CONCAT = S('concat')
const S_EVAL_IN_ENV = S('eval*')
const S_LST = S('lst')
function quasiquote(exp: MalVal): MalVal {
if (isMap(exp)) {
const ret: {[k: string]: MalVal} = {}
for (const [k, v] of Object.entries(exp)) {
ret[k] = quasiquote(v)
}
return ret
}
if (!isPair(exp)) {
return L(S_QUOTE, exp)
}
if (isSymbolFor(exp[0], 'unquote')) {
return exp[1]
}
let ret = L(
S_CONCAT,
...exp.map(e => {
if (isPair(e) && isSymbolFor(e[0], 'splice-unquote')) {
return e[1]
} else {
return [quasiquote(e)]
}
})
)
ret = isList(exp) ? L(S_LST, ret) : ret
return ret
function isPair(x: MalVal): x is MalVal[] {
return isSeq(x) && x.length > 0
}
}
function macroexpand(_exp: MalVal, env: Env, cache: boolean) {
let exp = _exp
while (isList(exp) && isSymbol(exp[0]) && env.find(exp[0])) {
const fn = env.get(exp[0])
if (!isMalFunc(fn) || !fn[M_ISMACRO]) {
break
}
exp[0].evaluated = fn
exp = fn.apply({callerEnv: env}, exp.slice(1))
}
if (cache && exp !== _exp && isList(_exp)) {
setExpandInfo(_exp, {type: ExpandType.Constant, exp})
}
return exp
}
function evalAtom(
this: void | MalFuncThis,
exp: MalVal,
env: Env,
cache: boolean
) {
if (isSymbol(exp)) {
const ret = env.get(exp)
if (cache) {
const def = env.getDef(exp)
if (def) {
exp.def = def
}
exp.evaluated = ret
}
return ret
} else if (Array.isArray(exp)) {
const ret = exp.map(x => {
const ret = evalExp.call(this, x, env, cache)
if (cache && isNode(x)) {
x[M_EVAL] = ret
}
return ret
})
if (cache) {
;(exp as MalNode)[M_EVAL] = ret
}
return isList(exp) ? L(...ret) : ret
} else if (isMap(exp)) {
const hm: MalMap = {}
for (const k in exp) {
const ret = evalExp.call(this, exp[k], env, cache)
if (cache && isNode(exp[k])) {
;(exp[k] as MalNode)[M_EVAL] = ret
}
hm[k] = ret
}
if (cache) {
;(exp as MalNode)[M_EVAL] = hm
}
return hm
} else {
return exp
}
}
export default function evalExp(
this: void | MalFuncThis,
exp: MalVal,
env: Env,
cache = true
): MalVal {
const origExp: MalSeq = exp as MalSeq
let counter = 0
while (counter++ < 1e6) {
if (!isList(exp)) {
const ret = evalAtom.call(this, exp, env, cache)
if (cache && isNode(origExp)) {
origExp[M_EVAL] = ret
}
return ret
}
// Expand macro
exp = macroexpand(exp, env, cache)
if (!isList(exp)) {
const ret = evalAtom.call(this, exp, env, cache)
if (cache && isNode(origExp)) {
origExp[M_EVAL] = ret
}
return ret
}
if (exp.length === 0) {
if (cache && isNode(origExp)) {
origExp[M_EVAL] = null
}
return null
}
// Apply list
const [first] = exp
if (!isSymbol(first) && !isFunc(first)) {
throw new MalError(
`${capital(getType(first))} ${printExp(
first
)} is not a function. First element of list always should be a function.`
)
}
switch (isSymbol(first) ? first.value : first) {
case 'def': {
if (cache) {
;(first as MalSymbol).evaluated = env.get(S_DEF)
}
const [, sym, form] = exp
if (!isSymbol(sym) || form === undefined) {
throw new MalError('Invalid form of def')
}
const ret = env.set(sym, evalExp.call(this, form, env, cache))
if (cache) {
setExpandInfo(exp, {
type: ExpandType.Unchange,
})
origExp[M_EVAL] = ret
}
return ret
}
case 'defvar': {
if (cache) {
;(first as MalSymbol).evaluated = env.get(S_DEFVAR)
}
const [, sym, form] = exp
if (!isSymbol(sym) || form === undefined) {
throw new MalError('Invalid form of defvar')
}
const ret = evalExp.call(this, form, env, cache)
env.set(sym, ret, exp)
if (cache) {
origExp[M_EVAL] = ret
}
return ret
}
case 'let': {
if (cache) {
;(first as MalSymbol).evaluated = env.get(S_LET)
}
const letEnv = new Env(env)
const [, binds, ...body] = exp
if (!isVector(binds)) {
throw new MalError('Invalid bind-expr in let')
}
for (let i = 0; i < binds.length; i += 2) {
letEnv.bindAll(
binds[i] as any,
evalExp.call(this, binds[i + 1], letEnv, cache) as MalVal[]
)
}
env = letEnv
const ret = body.length === 1 ? body[0] : L(S_DO, ...body)
if (cache) {
setExpandInfo(exp, {
type: ExpandType.Env,
exp: ret,
env: letEnv,
})
}
exp = ret
break // continue TCO loop
}
case 'binding': {
if (cache) {
;(first as MalSymbol).evaluated = env.get(S_BINDING)
}
const bindingEnv = new Env(undefined, undefined, undefined, 'binding')
const [, binds, ..._body] = exp
if (!isSeq(binds)) {
throw new MalError('Invalid bind-expr in binding')
}
for (let i = 0; i < binds.length; i += 2) {
bindingEnv.bindAll(
binds[i] as any,
evalExp.call(this, binds[i + 1], env, cache) as MalVal[]
)
}
env.pushBinding(bindingEnv)
const body = _body.length === 1 ? _body[0] : L(S_DO, ..._body)
let ret
try {
ret = evalExp.call(this, body, env, cache)
} finally {
env.popBinding()
}
if (cache) {
origExp[M_EVAL] = ret
}
return ret
}
case 'get-all-symbols': {
const ret = env.getAllSymbols()
if (cache) {
;(first as MalSymbol).evaluated = env.get(S_GET_ALL_SYMBOLS)
origExp[M_EVAL] = ret
}
return ret
}
case 'fn-params': {
if (cache) {
;(first as MalSymbol).evaluated = env.get(S_FN_PARAMS)
}
const fn = evalExp.call(this, exp[1], env, cache)
const ret = isMalFunc(fn) ? [...fn[M_PARAMS]] : null
if (cache) {
origExp[M_EVAL] = ret
}
return ret
}
case 'eval*': {
if (cache) {
;(first as MalSymbol).evaluated = env.get(S_EVAL_IN_ENV)
}
// if (!this) {
// throw new MalError('Cannot find the caller env')
// }
const expanded = evalExp.call(this, exp[1], env, cache)
exp = evalExp.call(this, expanded, this ? this.callerEnv : env, cache)
break // continue TCO loop
}
case 'quote': {
const ret = exp[1]
if (cache) {
;(first as MalSymbol).evaluated = env.get(S_QUOTE)
origExp[M_EVAL] = ret
}
return ret
}
case 'quasiquote': {
if (cache) {
;(first as MalSymbol).evaluated = env.get(S_QUASIQUOTE)
}
const ret = quasiquote(exp[1])
exp = ret
break // continue TCO loop
}
case 'fn': {
const [, , body] = exp
let [, params] = exp
if (isMap(params)) {
params = [params]
}
if (!isVector(params)) {
throw new MalError('First argument of fn should be vector or map')
}
if (body === undefined) {
throw new MalError('Second argument of fn should be specified')
}
const ret = createMalFunc(
function (...args) {
return evalExp.call(
this,
body,
new Env(env, params as any[], args),
cache
)
},
body,
env,
params as MalBind
)
if (cache) {
;(first as MalSymbol).evaluated = env.get(S_FN)
origExp[M_EVAL] = ret
}
return ret
}
case 'fn-sugar': {
if (cache) {
;(first as MalSymbol).evaluated = env.get(S_FN_SUGAR)
}
const body = exp[1]
const ret = createMalFunc(
function (...args) {
return evalExp.call(this, body, new Env(env, [], args), cache)
},
body,
env,
[]
)
if (cache) {
origExp[M_EVAL] = ret
}
return ret
}
case 'macro': {
if (cache) {
;(first as MalSymbol).evaluated = env.get(S_MACRO)
}
const [, , body] = exp
let [, params] = exp
if (isMap(params)) {
params = [params]
}
if (!isVector(params)) {
throw new MalError('First argument of macro should be vector or map')
}
if (body === undefined) {
throw new MalError('Second argument of macro should be specified')
}
const ret = createMalFunc(
function (...args) {
return evalExp.call(
this,
body,
new Env(env, params as any[], args),
cache
)
},
body,
env,
params as MalBind
)
ret[M_ISMACRO] = true
if (cache) {
origExp[M_EVAL] = ret
}
return ret
}
case 'macroexpand': {
if (cache) {
;(first as MalSymbol).evaluated = env.get(S_MACROEXPAND)
}
const ret = macroexpand(exp[1], env, cache)
if (cache) {
origExp[M_EVAL] = ret
}
return ret
}
case 'try': {
if (cache) {
;(first as MalSymbol).evaluated = env.get(S_TRY)
}
const [, testExp, catchExp] = exp
try {
const ret = evalExp.call(this, testExp, env, cache)
if (cache) {
origExp[M_EVAL] = ret
}
return ret
} catch (exc) {
let err = exc
if (
isList(catchExp) &&
isSymbolFor(catchExp[0], 'catch') &&
isSymbol(catchExp[1])
) {
if (cache) {
;(first as MalSymbol).evaluated = env.get(S_CATCH)
}
if (exc instanceof Error) {
err = exc.message
}
const [, errSym, errBody] = catchExp
const ret = evalExp.call(
this,
errBody,
new Env(env, [errSym], [err]),
cache
)
if (cache) {
origExp[M_EVAL] = ret
}
return ret
} else {
throw err
}
}
}
case 'do': {
if (cache) {
;(first as MalSymbol).evaluated = env.get(S_DO)
}
if (exp.length === 1) {
if (cache && isNode(origExp)) {
origExp[M_EVAL] = null
}
return null
}
evalExp.call(this, exp.slice(1, -1), env, cache)
const ret = exp[exp.length - 1]
exp = ret
break // continue TCO loop
}
case 'if': {
if (cache) {
;(first as MalSymbol).evaluated = env.get(S_IF)
}
const [, _test, thenExp, elseExp] = exp
const test = evalExp.call(this, _test, env, cache)
const ret = test ? thenExp : elseExp !== undefined ? elseExp : null
exp = ret
break // continue TCO loop
}
default: {
// is a function call
// Evaluate all of parameters at first
const [fn, ...params] = exp.map(e => evalExp.call(this, e, env, cache))
if (fn instanceof Function) {
if (cache) {
;(first as MalSymbol).evaluated = fn
}
if (isMalFunc(fn)) {
env = new Env(
fn[M_ENV],
fn[M_PARAMS],
params,
isSymbol(first) ? first.value : undefined
)
exp = fn[M_AST]
// continue TCO loop
break
} else {
const ret = fn.apply({callerEnv: env}, params)
if (cache) {
origExp[M_EVAL] = ret
}
return ret
}
}
}
}
}
throw new Error('Exceed the maximum TCO stacks')
} | the_stack |
import React, { useContext, useState, useEffect } from 'react';
import { DeploymentCenterContext } from '../DeploymentCenterContext';
import DeploymentCenterData from '../DeploymentCenter.data';
import { useTranslation } from 'react-i18next';
import { choiceGroupSubLabel, disconnectLink, disconnectWorkflowInfoStyle } from '../DeploymentCenter.styles';
import { Link, Icon, PanelType, ChoiceGroup, ProgressIndicator } from 'office-ui-fabric-react';
import {
DeploymentCenterGitHubDisconnectProps,
DeploymentDisconnectStatus,
DeployDisconnectStep,
WorkflowFileDeleteOptions,
WorkflowChoiceGroupOption,
} from '../DeploymentCenter.types';
import {
getWorkflowFileName,
getWorkflowFilePath,
getSourceControlsWorkflowFilePath,
getSourceControlsWorkflowFileName,
getTelemetryInfo,
} from '../utility/DeploymentCenterUtility';
import { PortalContext } from '../../../../PortalContext';
import CustomPanel from '../../../../components/CustomPanel/CustomPanel';
import ActionBar from '../../../../components/ActionBar';
import ReactiveFormControl from '../../../../components/form-controls/ReactiveFormControl';
import { getErrorMessage } from '../../../../ApiHelpers/ArmHelper';
import { SiteStateContext } from '../../../../SiteState';
import { clearGitHubActionSourceControlPropertiesManually } from '../utility/GitHubActionUtility';
const DeploymentCenterGitHubDisconnect: React.FC<DeploymentCenterGitHubDisconnectProps> = props => {
const { branch, org, repo, repoUrl, formProps } = props;
const { t } = useTranslation();
const deploymentCenterContext = useContext(DeploymentCenterContext);
const portalContext = useContext(PortalContext);
const siteStateContext = useContext(SiteStateContext);
const deploymentCenterData = new DeploymentCenterData();
const workflowFile = getWorkflowFileName(
branch,
deploymentCenterContext.siteDescriptor ? deploymentCenterContext.siteDescriptor.site : '',
deploymentCenterContext.siteDescriptor ? deploymentCenterContext.siteDescriptor.slot : ''
);
const workflowPath = getWorkflowFilePath(
branch,
deploymentCenterContext.siteDescriptor ? deploymentCenterContext.siteDescriptor.site : '',
deploymentCenterContext.siteDescriptor ? deploymentCenterContext.siteDescriptor.slot : ''
);
const [isDisconnectPanelOpen, setIsDisconnectPanelOpen] = useState<boolean>(false);
const [selectedWorkflowOption, setSelectedWorkflowOption] = useState<WorkflowFileDeleteOptions>(WorkflowFileDeleteOptions.Preserve);
const [isLoading, setIsLoading] = useState<boolean>(false);
const [workflowConfigExists, setWorkflowConfigExists] = useState<boolean>(false);
const [workflowFileName, setWorkflowFileName] = useState<string>(workflowFile);
const [workflowFilePath, setWorkflowFilePath] = useState<string>(workflowPath);
const showDisconnectPanel = () => {
setSelectedWorkflowOption(WorkflowFileDeleteOptions.Preserve);
setIsDisconnectPanelOpen(true);
};
const dismissDisconnectPanel = () => {
setIsDisconnectPanelOpen(false);
};
const updateSelectedWorkflowChoice = (e: any, option: WorkflowChoiceGroupOption) => {
setSelectedWorkflowOption(option.workflowDeleteChoice);
};
const disconnectCallback = async (deleteWorkflowDuringDisconnect: boolean) => {
const notificationId = portalContext.startNotification(t('disconnectingDeployment'), t('disconnectingDeployment'));
dismissDisconnectPanel();
portalContext.log(
getTelemetryInfo('info', 'gitHubDisconnect', 'submit', {
deleteWorkflowDuringDisconnect: deleteWorkflowDuringDisconnect ? 'true' : 'false',
})
);
const deleteSourceControlStatus = await deleteSourceControl(deleteWorkflowDuringDisconnect);
if (deleteSourceControlStatus.isSuccessful) {
formProps.resetForm();
portalContext.stopNotification(notificationId, true, t('disconnectingDeploymentSuccess'));
await deploymentCenterContext.refresh();
} else {
portalContext.stopNotification(
notificationId,
false,
deleteSourceControlStatus.errorMessage ? deleteSourceControlStatus.errorMessage : t('disconnectingDeploymentFail')
);
}
};
// NOTE(michinoy): Eventually the deletion of workflow file will move entirely to the backend API.
// As we are transitioning from having all the logic in the UX to the API, we are passing in the 'deleteWorkflowDuringDisconnect' flag.
// This will make sure we are deleting the workflow from the UX only for now.
const deleteSourceControl = async (deleteWorkflowDuringDisconnect: boolean) => {
return siteStateContext.isKubeApp
? clearMetadataAndConfig(deleteWorkflowDuringDisconnect)
: deleteSourceControlDetails(deleteWorkflowDuringDisconnect);
};
const clearMetadataAndConfig = async (deleteWorkflowDuringDisconnect: boolean) => {
const deleteWorkflowFileStatus = await deleteWorkflowFileManually(deleteWorkflowDuringDisconnect);
if (deleteWorkflowFileStatus.isSuccessful) {
portalContext.log(getTelemetryInfo('info', 'clearMetadataAndConfig', 'submit'));
const response = await clearGitHubActionSourceControlPropertiesManually(deploymentCenterData, deploymentCenterContext.resourceId);
if (!response.metadata.success) {
portalContext.log(
getTelemetryInfo('error', 'clearMetadataAndConfig', 'failed', {
message: getErrorMessage(response.metadata.error),
errorAsString: JSON.stringify(response.metadata.error),
})
);
const failedStatus: DeploymentDisconnectStatus = {
step: DeployDisconnectStep.ClearSCMSettings,
isSuccessful: false,
error: response.metadata.error,
};
const errorMessage = getErrorMessage(response.metadata.error);
if (errorMessage) {
failedStatus.errorMessage = deleteWorkflowDuringDisconnect
? t('disconnectingDeploymentFailWorkflowFileDeleteSucceededWithMessage').format(errorMessage)
: t('disconnectingDeploymentFailWithMessage').format(errorMessage);
} else {
failedStatus.errorMessage = deleteWorkflowDuringDisconnect
? t('disconnectingDeploymentFailWorkflowFileDeleteSucceeded')
: t('disconnectingDeploymentFail');
}
return failedStatus;
} else {
const successStatus: DeploymentDisconnectStatus = {
step: DeployDisconnectStep.ClearSCMSettings,
isSuccessful: true,
};
return successStatus;
}
} else {
return deleteWorkflowFileStatus;
}
};
const deleteSourceControlDetails = async (deleteWorkflowDuringDisconnect: boolean) => {
portalContext.log(getTelemetryInfo('info', 'deleteSourceControlDetails', 'submit'));
const deleteSourceControlDetailsResponse = await deploymentCenterData.deleteSourceControlDetails(
deploymentCenterContext.resourceId,
deleteWorkflowDuringDisconnect
);
if (!deleteSourceControlDetailsResponse.metadata.success) {
portalContext.log(
getTelemetryInfo('error', 'deleteSourceControlDetailsResponse', 'failed', {
message: getErrorMessage(deleteSourceControlDetailsResponse.metadata.error),
errorAsString: JSON.stringify(deleteSourceControlDetailsResponse.metadata.error),
})
);
const failedStatus: DeploymentDisconnectStatus = {
step: DeployDisconnectStep.ClearSCMSettings,
isSuccessful: false,
error: deleteSourceControlDetailsResponse.metadata.error,
};
const errorMessage = getErrorMessage(deleteSourceControlDetailsResponse.metadata.error);
if (errorMessage) {
failedStatus.errorMessage = deleteWorkflowDuringDisconnect
? t('disconnectingDeploymentFailWorkflowFileDeleteSucceededWithMessage').format(errorMessage)
: t('disconnectingDeploymentFailWithMessage').format(errorMessage);
} else {
failedStatus.errorMessage = deleteWorkflowDuringDisconnect
? t('disconnectingDeploymentFailWorkflowFileDeleteSucceeded')
: t('disconnectingDeploymentFail');
}
return failedStatus;
} else {
const successStatus: DeploymentDisconnectStatus = {
step: DeployDisconnectStep.ClearSCMSettings,
isSuccessful: true,
};
return successStatus;
}
};
const deleteWorkflowFileManually = async (deleteWorkflowDuringDisconnect: boolean) => {
const errorMessage = t('githubActionDisconnectWorkflowDeleteFailed').format(workflowFileName, branch, repoUrl);
const successStatus: DeploymentDisconnectStatus = {
step: DeployDisconnectStep.DeleteWorkflowFile,
isSuccessful: true,
};
const failedStatus: DeploymentDisconnectStatus = {
step: DeployDisconnectStep.DeleteWorkflowFile,
isSuccessful: false,
errorMessage: errorMessage,
};
if (!deleteWorkflowDuringDisconnect) {
return successStatus;
} else {
const workflowConfigurationResponse = await deploymentCenterData.getWorkflowConfiguration(
org,
repo,
branch,
workflowFilePath,
deploymentCenterContext.gitHubToken
);
if (workflowConfigurationResponse.metadata.success) {
portalContext.log(
getTelemetryInfo('error', 'deleteActionWorkflow', 'submit', {
org,
repo,
branch,
workflowFilePath,
})
);
const deleteWorkflowFileResponse = await deploymentCenterData.deleteActionWorkflow(
deploymentCenterContext.gitHubToken,
org,
repo,
branch,
workflowFilePath,
t('githubActionWorkflowDeleteCommitMessage'),
workflowConfigurationResponse.data.sha
);
if (deleteWorkflowFileResponse && deleteWorkflowFileResponse.metadata.success) {
return successStatus;
} else {
if (deleteWorkflowFileResponse) {
portalContext.log(
getTelemetryInfo('error', 'deleteSourceControlDetailsResponse', 'failed', {
errorAsString: JSON.stringify(deleteWorkflowFileResponse.metadata.error),
})
);
failedStatus.error = deleteWorkflowFileResponse.metadata.error;
}
return failedStatus;
}
} else {
// (Note t-kakan): not localized due to this string not being shown to users
failedStatus.error = `Workflow file '${workflowFilePath}' not found in branch '${branch}' from repo '${org}/${repo}'`;
return failedStatus;
}
}
};
const fetchWorkflowConfiguration = async () => {
setIsLoading(true);
//(Note stpelleg): Apps deployed to production slot can have siteDescriptor.slot of undefined
const isProductionSlot =
deploymentCenterContext.siteDescriptor &&
(!deploymentCenterContext.siteDescriptor.slot || deploymentCenterContext.siteDescriptor.slot.toLocaleLowerCase() === 'production');
if (isProductionSlot) {
await fetchAppAndSourceControlsWorkflowConfiguration();
} else {
await fetchAppOnlyWorkflowConfiguration();
}
setIsLoading(false);
};
const fetchAppOnlyWorkflowConfiguration = async () => {
const appWorkflowConfigurationResponse = await deploymentCenterData.getWorkflowConfiguration(
org,
repo,
branch,
workflowFilePath,
deploymentCenterContext.gitHubToken
);
setWorkflowConfigExists(appWorkflowConfigurationResponse.metadata.success);
};
//(Note stpelleg): Apps deployed to production using the source controls API have a different workflow file name
// format than ones deployed through the deployment center, so we need two checks for the workflow file.
const fetchAppAndSourceControlsWorkflowConfiguration = async () => {
const sourceControlsWorkflowFilePath = getSourceControlsWorkflowFilePath(
branch,
deploymentCenterContext.siteDescriptor ? deploymentCenterContext.siteDescriptor.site : '',
'production'
);
const [appWorkflowConfigurationResponse, sourceControlsWorkflowConfigurationResponse] = await Promise.all([
deploymentCenterData.getWorkflowConfiguration(org, repo, branch, workflowFilePath, deploymentCenterContext.gitHubToken),
deploymentCenterData.getWorkflowConfiguration(org, repo, branch, sourceControlsWorkflowFilePath, deploymentCenterContext.gitHubToken),
]);
if (appWorkflowConfigurationResponse.metadata.success) {
setWorkflowConfigExists(appWorkflowConfigurationResponse.metadata.success);
} else if (sourceControlsWorkflowConfigurationResponse.metadata.success) {
setWorkflowConfigExists(sourceControlsWorkflowConfigurationResponse.metadata.success);
setWorkflowFilePath(sourceControlsWorkflowFilePath);
setWorkflowFileName(
getSourceControlsWorkflowFileName(
branch,
deploymentCenterContext.siteDescriptor ? deploymentCenterContext.siteDescriptor.site : '',
'production'
)
);
} else {
setWorkflowConfigExists(false);
}
};
const options: WorkflowChoiceGroupOption[] = [
{
key: 'Preserve',
text: t('githubActionWorkflowFilePreserveLabel'),
workflowDeleteChoice: WorkflowFileDeleteOptions.Preserve,
onRenderField: (fieldProps, defaultRenderer) => (
<div>
{defaultRenderer!(fieldProps)}
<div className={choiceGroupSubLabel}>{t('githubActionWorkflowFilePreserveDescription')}</div>
</div>
),
},
{
key: 'Delete',
text: t('githubActionWorkflowFileDeleteLabel'),
workflowDeleteChoice: WorkflowFileDeleteOptions.Delete,
onRenderField: (fieldProps, defaultRenderer) => (
<div>
{defaultRenderer!(fieldProps)}
<div className={choiceGroupSubLabel}>{t('githubActionWorkflowFileDeleteDescription')}</div>
</div>
),
},
];
const actionBarPrimaryButtonProps = {
id: 'save',
title: t('ok'),
onClick: () => disconnectCallback(selectedWorkflowOption === WorkflowFileDeleteOptions.Delete),
disable: isLoading,
};
const actionBarSecondaryButtonProps = {
id: 'cancel',
title: t('cancel'),
onClick: dismissDisconnectPanel,
disable: false,
};
const getProgressIndicator = () => {
return (
<ProgressIndicator
description={t('deploymentCenterGitHubDisconnectLoading')}
ariaValueText={t('deploymentCenterGitHubDisconnectLoadingAriaValue')}
/>
);
};
const getPanelContent = () => {
if (workflowConfigExists) {
return (
<>
{t('githubActionWorkflowFileDeletePanelDescription')}
{getWorkflowFileRepoAndBranchContent()}
<ChoiceGroup selectedKey={selectedWorkflowOption} options={options} onChange={updateSelectedWorkflowChoice} required={true} />
</>
);
} else {
return <h4>{t('githubActionWorkflowFileDeletePanelNoChoiceDescription').format(workflowFileName, branch, repoUrl)}</h4>;
}
};
const getWorkflowFileRepoAndBranchContent = () => {
return (
<div className={disconnectWorkflowInfoStyle}>
<ReactiveFormControl id="deployment-center-workflow-file-name" label={t('githubActionWorkflowFileLabel')}>
<div>{workflowFileName}</div>
</ReactiveFormControl>
<ReactiveFormControl id="deployment-center-repository" label={t('deploymentCenterOAuthRepository')}>
<div>{repoUrl}</div>
</ReactiveFormControl>
<ReactiveFormControl id="deployment-center-organization" label={t('deploymentCenterOAuthBranch')}>
<div>{branch}</div>
</ReactiveFormControl>
</div>
);
};
useEffect(() => {
fetchWorkflowConfiguration();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<>
<Link key="deployment-center-disconnect-link" onClick={showDisconnectPanel} className={disconnectLink} aria-label={t('disconnect')}>
<Icon iconName={'PlugDisconnected'} />
{` ${t('disconnect')}`}
</Link>
<CustomPanel
isOpen={isDisconnectPanelOpen}
onDismiss={dismissDisconnectPanel}
type={PanelType.medium}
headerText={t('githubActionDisconnectConfirmationTitle')}>
{isLoading ? getProgressIndicator() : getPanelContent()}
<ActionBar
id="app-settings-edit-footer"
primaryButton={actionBarPrimaryButtonProps}
secondaryButton={actionBarSecondaryButtonProps}
/>
</CustomPanel>
</>
);
};
export default DeploymentCenterGitHubDisconnect; | the_stack |
Copyright (c) 2020 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
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.
*/
import { EDITOR } from 'internal:constants';
import { IParticleModule, Particle, PARTICLE_MODULE_ORDER } from './particle';
import { Node } from '../core/scene-graph/node';
import { TransformBit } from '../core/scene-graph/node-enum';
import { RenderMode, Space } from './enum';
import { Color, Mat4, Material, pseudoRandom, Quat, randomRangeInt, RenderingSubMesh, Vec3, Vec4 } from '../core';
import { INT_MAX } from '../core/math/bits';
import { particleEmitZAxis } from './particle-general-function';
import { IParticleSystemRenderer } from './renderer/particle-system-renderer-base';
import { Mesh } from '../3d';
import { AABB } from '../core/geometry';
import { scene } from '../core/renderer';
import { BlendFactor } from '../core/gfx';
import { Primitive } from '../primitive/primitive';
import { Root } from '../core/root';
import { legacyCC } from '../core/global-exports';
const _node_mat = new Mat4();
const _node_rol = new Quat();
const _node_scale = new Vec3();
const _anim_module = [
'_colorOverLifetimeModule',
'_sizeOvertimeModule',
'_velocityOvertimeModule',
'_forceOvertimeModule',
'_limitVelocityOvertimeModule',
'_rotationOvertimeModule',
'_textureAnimationModule',
];
export class ParticleCuller {
private _particleSystem: any;
private _processor: IParticleSystemRenderer;
private _node: Node;
private _particlesAll: Particle[];
private _updateList: Map<string, IParticleModule> = new Map<string, IParticleModule>();
private _animateList: Map<string, IParticleModule> = new Map<string, IParticleModule>();
private _runAnimateList: IParticleModule[] = new Array<IParticleModule>();
private _localMat: Mat4 = new Mat4();
private _gravity: Vec4 = new Vec4();
public minPos: Vec3 = new Vec3();
public maxPos: Vec3 = new Vec3();
private _nodePos: Vec3 = new Vec3();
private _nodeSize: Vec3 = new Vec3();
constructor (ps) {
this._particleSystem = ps;
this._processor = this._particleSystem.processor;
this._node = ps.node;
this._particlesAll = [];
this._initModuleList();
}
private _updateBoundingNode () {
this._nodeSize.set(this.maxPos.x - this.minPos.x, this.maxPos.y - this.minPos.y, this.maxPos.z - this.minPos.z);
this._nodePos.set(this.minPos.x + this._nodeSize.x * 0.5, this.minPos.y + this._nodeSize.y * 0.5, this.minPos.z + this._nodeSize.z * 0.5);
}
public setBoundingBoxSize (halfExt: Vec3) {
this.maxPos.x = this._nodePos.x + halfExt.x;
this.maxPos.y = this._nodePos.y + halfExt.y;
this.maxPos.z = this._nodePos.z + halfExt.z;
this.minPos.x = this._nodePos.x - halfExt.x;
this.minPos.y = this._nodePos.y - halfExt.y;
this.minPos.z = this._nodePos.z - halfExt.z;
this._updateBoundingNode();
}
public setBoundingBoxCenter (px, py, pz) {
this.maxPos.x = px + this._nodeSize.x * 0.5;
this.maxPos.y = py + this._nodeSize.y * 0.5;
this.maxPos.z = pz + this._nodeSize.z * 0.5;
this.minPos.x = px - this._nodeSize.x * 0.5;
this.minPos.y = py - this._nodeSize.y * 0.5;
this.minPos.z = pz - this._nodeSize.z * 0.5;
this._updateBoundingNode();
}
private _initModuleList () {
_anim_module.forEach((val) => {
const pm = this._particleSystem[val];
if (pm && pm.enable) {
if (pm.needUpdate) {
this._updateList[pm.name] = pm;
}
if (pm.needAnimate) {
this._animateList[pm.name] = pm;
}
}
});
// reorder
this._runAnimateList.length = 0;
for (let i = 0, len = PARTICLE_MODULE_ORDER.length; i < len; i++) {
const p = this._animateList[PARTICLE_MODULE_ORDER[i]];
if (p) {
this._runAnimateList.push(p);
}
}
}
private _emit (count: number, dt: number, particleLst: Particle[]) {
const ps = this._particleSystem;
const node = this._node;
const loopDelta = (ps.time % ps.duration) / ps.duration; // loop delta value
node.invalidateChildren(TransformBit.POSITION);
if (ps.simulationSpace === Space.World) {
node.getWorldMatrix(_node_mat);
node.getWorldRotation(_node_rol);
}
for (let i = 0; i < count; ++i) {
const particle: Particle = new Particle(ps);
particle.particleSystem = ps;
particle.reset();
const rand = pseudoRandom(randomRangeInt(0, INT_MAX));
if (ps._shapeModule && ps._shapeModule.enable) {
ps._shapeModule.emit(particle);
} else {
Vec3.set(particle.position, 0, 0, 0);
Vec3.copy(particle.velocity, particleEmitZAxis);
}
if (ps._textureAnimationModule && ps._textureAnimationModule.enable) {
ps._textureAnimationModule.init(particle);
}
const curveStartSpeed = ps.startSpeed.evaluate(loopDelta, rand)!;
Vec3.multiplyScalar(particle.velocity, particle.velocity, curveStartSpeed);
if (ps.simulationSpace === Space.World) {
Vec3.transformMat4(particle.position, particle.position, _node_mat);
Vec3.transformQuat(particle.velocity, particle.velocity, _node_rol);
}
Vec3.copy(particle.ultimateVelocity, particle.velocity);
// apply startRotation.
Vec3.set(particle.rotation, 0, 0, 0);
// apply startSize.
if (ps.startSize3D) {
Vec3.set(particle.startSize, ps.startSizeX.evaluate(loopDelta, rand)!,
ps.startSizeY.evaluate(loopDelta, rand)!,
ps.startSizeZ.evaluate(loopDelta, rand)!);
} else {
Vec3.set(particle.startSize, ps.startSizeX.evaluate(loopDelta, rand)!, 1, 1);
particle.startSize.y = particle.startSize.x;
}
Vec3.copy(particle.size, particle.startSize);
// apply startLifetime.
particle.startLifetime = ps.startLifetime.evaluate(loopDelta, rand)! + dt;
particle.remainingLifetime = particle.startLifetime;
particleLst.push(particle);
}
}
private _updateParticles (dt: number, particleLst: Particle[]) {
const ps = this._particleSystem;
ps.node.getWorldMatrix(_node_mat);
switch (ps.scaleSpace) {
case Space.Local:
ps.node.getScale(_node_scale);
break;
case Space.World:
ps.node.getWorldScale(_node_scale);
break;
default:
break;
}
this._updateList.forEach((value: IParticleModule, key: string) => {
value.update(ps.simulationSpace, _node_mat);
});
if (ps.simulationSpace === Space.Local) {
const r:Quat = ps.node.getRotation();
Mat4.fromQuat(this._localMat, r);
this._localMat.transpose(); // just consider rotation, use transpose as invert
}
for (let i = 0; i < particleLst.length; ++i) {
const p: Particle = particleLst[i];
p.remainingLifetime -= dt;
Vec3.set(p.animatedVelocity, 0, 0, 0);
if (ps.simulationSpace === Space.Local) {
const gravityFactor = -ps.gravityModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, pseudoRandom(p.randomSeed))! * 9.8 * dt;
this._gravity.x = 0.0;
this._gravity.y = gravityFactor;
this._gravity.z = 0.0;
this._gravity.w = 1.0;
this._gravity = this._gravity.transformMat4(this._localMat);
p.velocity.x += this._gravity.x;
p.velocity.y += this._gravity.y;
p.velocity.z += this._gravity.z;
} else {
// apply gravity.
p.velocity.y -= ps.gravityModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, pseudoRandom(p.randomSeed))! * 9.8 * dt;
}
Vec3.copy(p.ultimateVelocity, p.velocity);
this._runAnimateList.forEach((value) => {
value.animate(p, dt);
});
Vec3.scaleAndAdd(p.position, p.position, p.ultimateVelocity, dt); // apply velocity.
}
}
private _calculateBounding (isInit: boolean) {
const size: Vec3 = new Vec3();
const position: Vec3 = new Vec3();
const subPos: Vec3 = new Vec3();
const addPos: Vec3 = new Vec3();
const meshSize: Vec3 = new Vec3(1.0, 1.0, 1.0);
if (this._processor.getInfo()!.renderMode === RenderMode.Mesh) {
const mesh: Mesh | null = this._processor.getInfo().mesh;
if (mesh && mesh.struct.minPosition && mesh.struct.maxPosition) {
const meshAABB: AABB = new AABB();
AABB.fromPoints(meshAABB, mesh.struct.minPosition, mesh.struct.maxPosition);
const meshMax = Math.max(meshAABB.halfExtents.x, meshAABB.halfExtents.y, meshAABB.halfExtents.z);
meshSize.set(meshMax, meshMax, meshMax);
}
}
for (let i = 0; i < this._particlesAll.length; ++i) {
const p: Particle = this._particlesAll[i];
Vec3.multiply(size, _node_scale, p.size);
Vec3.multiply(size, size, meshSize);
position.set(p.position);
if (this._particleSystem.simulationSpace !== Space.World) {
Vec3.transformMat4(position, position, this._particleSystem.node._mat);
}
if (isInit && i === 0) {
Vec3.subtract(this.minPos, position, size);
Vec3.add(this.maxPos, position, size);
} else {
Vec3.subtract(subPos, position, size);
Vec3.add(addPos, position, size);
Vec3.min(this.minPos, this.minPos, subPos);
Vec3.max(this.maxPos, this.maxPos, addPos);
}
}
}
public calculatePositions () {
this._emit(this._particleSystem.capacity, 0, this._particlesAll);
const rand = pseudoRandom(randomRangeInt(0, INT_MAX));
this._updateParticles(0, this._particlesAll);
this._calculateBounding(true);
this._updateParticles(this._particleSystem.startLifetime.evaluate(0, rand), this._particlesAll);
this._calculateBounding(false);
this._updateBoundingNode();
}
public clear () {
this._particlesAll.length = 0;
}
public destroy () {
}
} | the_stack |
import assert from 'assert'
import nanoid from 'nanoid'
import add from '../add'
import { where } from '../where'
import { limit } from '../limit'
import onQuery from '.'
import { collection } from '../collection'
import { order } from '../order'
import { startAfter, startAt, endBefore, endAt } from '../cursor'
import { Ref, ref } from '../ref'
import { Doc } from '../doc'
import get from '../get'
import set from '../set'
import sinon from 'sinon'
import { subcollection } from '../subcollection'
import { group } from '../group'
import remove from '../remove'
import { docId } from '../docId'
describe('onQuery', () => {
type Contact = { ownerId: string; name: string; year: number; birthday: Date }
type Message = { ownerId: string; author: Ref<Contact>; text: string }
const contacts = collection<Contact>('contacts')
const messages = collection<Message>('messages')
let ownerId: string
let leshaId: string
let sashaId: string
let tatiId: string
let off: () => void | undefined
function setLesha() {
return set(contacts, leshaId, {
ownerId,
name: 'Lesha',
year: 1995,
birthday: new Date(1995, 6, 2)
})
}
beforeEach(async () => {
ownerId = nanoid()
leshaId = `lesha-${ownerId}`
sashaId = `sasha-${ownerId}`
tatiId = `tati-${ownerId}`
return Promise.all([
setLesha(),
set(contacts, sashaId, {
ownerId,
name: 'Sasha',
year: 1987,
birthday: new Date(1987, 1, 11)
}),
set(contacts, tatiId, {
ownerId,
name: 'Tati',
year: 1989,
birthday: new Date(1989, 6, 10)
})
])
})
afterEach(() => {
off && off()
off = undefined
})
it('queries documents', (done) => {
const spy = sinon.spy()
off = onQuery(contacts, [where('ownerId', '==', ownerId)], (docs) => {
spy(docs.map(({ data: { name } }) => name).sort())
if (spy.calledWithMatch(['Lesha', 'Sasha', 'Tati'])) done()
})
})
it('allows to query by value in maps', async () => {
const spy = sinon.spy()
type Location = { mapId: string; name: string; address: { city: string } }
const locations = collection<Location>('locations')
const mapId = nanoid()
await Promise.all([
add(locations, {
mapId,
name: 'Pizza City',
address: { city: 'New York' }
}),
add(locations, {
mapId,
name: 'Bagels Tower',
address: { city: 'New York' }
}),
add(locations, {
mapId,
name: 'Tacos Cave',
address: { city: 'Houston' }
})
])
return new Promise((resolve) => {
off = onQuery(
locations,
[
where('mapId', '==', mapId),
where(['address', 'city'], '==', 'New York')
],
(docs) => {
spy(docs.map(({ data: { name } }) => name).sort())
if (spy.calledWithMatch(['Bagels Tower', 'Pizza City'])) resolve()
}
)
})
})
it('allows to query using array-contains filter', async () => {
const spy = sinon.spy()
type Tag = 'pets' | 'cats' | 'dogs' | 'food' | 'hotdogs'
type Post = { blogId: string; title: string; tags: Tag[] }
const posts = collection<Post>('posts')
const blogId = nanoid()
await Promise.all([
add(posts, {
blogId,
title: 'Post about cats',
tags: ['pets', 'cats']
}),
add(posts, {
blogId,
title: 'Post about dogs',
tags: ['pets', 'dogs']
}),
add(posts, {
blogId,
title: 'Post about hotdogs',
tags: ['food', 'hotdogs']
})
])
return new Promise((resolve) => {
off = onQuery(
posts,
[
where('blogId', '==', blogId),
where('tags', 'array-contains', 'pets')
],
(docs) => {
spy(docs.map(({ data: { title } }) => title).sort())
if (spy.calledWithMatch(['Post about cats', 'Post about dogs']))
resolve()
}
)
})
})
it('allows to query using in filter', async () => {
const spy = sinon.spy()
type Pet = {
ownerId: string
name: string
type: 'dog' | 'cat' | 'parrot' | 'snake'
}
const pets = collection<Pet>('pets')
const ownerId = nanoid()
await Promise.all([
add(pets, {
ownerId,
name: 'Persik',
type: 'dog'
}),
add(pets, {
ownerId,
name: 'Kimchi',
type: 'cat'
}),
add(pets, {
ownerId,
name: 'Snako',
type: 'snake'
})
])
return new Promise((resolve) => {
off = onQuery(
pets,
[where('ownerId', '==', ownerId), where('type', 'in', ['cat', 'dog'])],
(docs) => {
spy(docs.map(({ data: { name } }) => name).sort())
if (spy.calledWithMatch(['Kimchi', 'Persik'])) resolve()
}
)
})
})
it('allows to query using array-contains-any filter', async () => {
const spy = sinon.spy()
type Tag = 'pets' | 'cats' | 'dogs' | 'wildlife' | 'food' | 'hotdogs'
type Post = { blogId: string; title: string; tags: Tag[] }
const posts = collection<Post>('posts')
const blogId = nanoid()
await Promise.all([
add(posts, {
blogId,
title: 'Post about cats',
tags: ['pets', 'cats']
}),
add(posts, {
blogId,
title: 'Post about dogs',
tags: ['pets', 'dogs']
}),
add(posts, {
blogId,
title: 'Post about hotdogs',
tags: ['food', 'hotdogs']
}),
add(posts, {
blogId,
title: 'Post about kangaroos',
tags: ['wildlife']
})
])
return new Promise((resolve) => {
off = onQuery(
posts,
[
where('blogId', '==', blogId),
where('tags', 'array-contains-any', ['pets', 'wildlife'])
],
(docs) => {
spy(docs.map(({ data: { title } }) => title).sort())
if (
spy.calledWithMatch([
'Post about cats',
'Post about dogs',
'Post about kangaroos'
])
)
resolve()
}
)
})
})
describe('with messages', () => {
beforeEach(async () => {
await Promise.all([
add(messages, { ownerId, author: ref(contacts, sashaId), text: '+1' }),
add(messages, { ownerId, author: ref(contacts, leshaId), text: '+1' }),
add(messages, { ownerId, author: ref(contacts, tatiId), text: 'wut' }),
add(messages, { ownerId, author: ref(contacts, sashaId), text: 'lul' })
])
})
it('expands references', (done) => {
const spy = sinon.spy()
off = onQuery(
messages,
[where('ownerId', '==', ownerId), where('text', '==', '+1')],
async (docs) => {
const authors = await Promise.all(
docs.map((doc) => get(contacts, doc.data.author.id))
)
spy(authors.map(({ data: { name } }) => name).sort())
if (spy.calledWithMatch(['Lesha', 'Sasha'])) done()
}
)
})
it('allows to query by reference', (done) => {
const spy = sinon.spy()
off = onQuery(
messages,
[
where('ownerId', '==', ownerId),
where('author', '==', ref(contacts, sashaId))
],
(docs) => {
spy(docs.map((doc) => doc.data.text).sort())
if (spy.calledWithMatch(['+1', 'lul'])) done()
}
)
})
it('allows querying collection groups', async () => {
const ownerId = nanoid()
const contactMessages = subcollection<Message, Contact>(
'contactMessages',
contacts
)
const sashaRef = ref(contacts, `${ownerId}-sasha`)
const sashasContactMessages = contactMessages(sashaRef)
add(sashasContactMessages, {
ownerId,
author: sashaRef,
text: 'Hello from Sasha!'
})
const tatiRef = ref(contacts, `${ownerId}-tati`)
const tatisContactMessages = contactMessages(tatiRef)
await Promise.all([
add(tatisContactMessages, {
ownerId,
author: tatiRef,
text: 'Hello from Tati!'
}),
add(tatisContactMessages, {
ownerId,
author: tatiRef,
text: 'Hello, again!'
})
])
const allContactMessages = group('contactMessages', [contactMessages])
const spy = sinon.spy()
return new Promise((resolve) => {
off = onQuery(
allContactMessages,
[where('ownerId', '==', ownerId)],
async (messages) => {
spy(messages.map((m) => m.data.text).sort())
if (messages.length === 3) {
await Promise.all([
add(sashasContactMessages, {
ownerId,
author: sashaRef,
text: '1'
}),
add(tatisContactMessages, {
ownerId,
author: tatiRef,
text: '2'
})
])
} else if (messages.length === 5) {
assert(
spy.calledWithMatch([
'Hello from Sasha!',
'Hello from Tati!',
'Hello, again!'
])
)
assert(
spy.calledWithMatch([
'1',
'2',
'Hello from Sasha!',
'Hello from Tati!',
'Hello, again!'
])
)
resolve()
}
}
)
})
})
})
it('allows to query by date', (done) => {
off = onQuery(
contacts,
[
where('ownerId', '==', ownerId),
where('birthday', '==', new Date(1987, 1, 11))
],
(docs) => {
if (docs.length === 1 && docs[0].data.name === 'Sasha') done()
}
)
})
describe('ordering', () => {
it('allows ordering', (done) => {
const spy = sinon.spy()
off = onQuery(
contacts,
[where('ownerId', '==', ownerId), order('year', 'asc')],
(docs) => {
spy(docs.map(({ data: { name } }) => name))
if (spy.calledWithMatch(['Sasha', 'Tati', 'Lesha'])) done()
}
)
})
it('allows ordering by desc', (done) => {
const spy = sinon.spy()
off = onQuery(
contacts,
[where('ownerId', '==', ownerId), order('year', 'desc')],
(docs) => {
spy(docs.map(({ data: { name } }) => name))
if (spy.calledWithMatch(['Lesha', 'Tati', 'Sasha'])) done()
}
)
})
describe('with messages', () => {
beforeEach(() =>
Promise.all([
add(messages, {
ownerId,
author: ref(contacts, sashaId),
text: '+1'
}),
add(messages, {
ownerId,
author: ref(contacts, leshaId),
text: '+1'
}),
add(messages, {
ownerId,
author: ref(contacts, tatiId),
text: 'wut'
}),
add(messages, {
ownerId,
author: ref(contacts, sashaId),
text: 'lul'
})
])
)
it('allows ordering by references', (done) => {
const spy = sinon.spy()
off = onQuery(
messages,
[
where('ownerId', '==', ownerId),
order('author', 'desc'),
order('text')
],
async (docs) => {
const messagesLog = await Promise.all(
docs.map((doc) =>
get(contacts, doc.data.author.id).then(
(contact) => `${contact.data.name}: ${doc.data.text}`
)
)
)
spy(messagesLog)
if (
spy.calledWithMatch([
'Tati: wut',
'Sasha: +1',
'Sasha: lul',
'Lesha: +1'
])
)
done()
}
)
})
})
it('allows ordering by date', (done) => {
const spy = sinon.spy()
off = onQuery(
contacts,
[where('ownerId', '==', ownerId), order('birthday', 'asc')],
(docs) => {
spy(docs.map(({ data: { name } }) => name))
if (spy.calledWithMatch(['Sasha', 'Tati', 'Lesha'])) done()
}
)
})
})
describe('limiting', () => {
it('allows to limit response length', (done) => {
const spy = sinon.spy()
off = onQuery(
contacts,
[where('ownerId', '==', ownerId), order('year', 'asc'), limit(2)],
(docs) => {
spy(docs.map(({ data: { name } }) => name))
if (spy.calledWithMatch(['Sasha', 'Tati'])) done()
}
)
})
})
describe('paginating', () => {
describe('startAfter', () => {
let page1Off: () => void
let page2Off: () => void
afterEach(() => {
page1Off && page1Off()
page2Off && page2Off()
})
it('allows to paginate', (done) => {
const spyPage1 = sinon.spy()
const spyPage2 = sinon.spy()
page1Off = onQuery(
contacts,
[
where('ownerId', '==', ownerId),
order('year', 'asc', [startAfter(undefined)]),
limit(2)
],
(page1Docs) => {
spyPage1(page1Docs.map(({ data: { name } }) => name))
if (spyPage1.calledWithMatch(['Sasha', 'Tati'])) {
page1Off()
page2Off = onQuery(
contacts,
[
where('ownerId', '==', ownerId),
order('year', 'asc', [startAfter(page1Docs[1].data.year)]),
limit(2)
],
(page2Docs) => {
spyPage2(page2Docs.map(({ data: { name } }) => name))
if (spyPage2.calledWithMatch(['Lesha'])) done()
}
)
}
}
)
})
})
describe('startAt', () => {
it('allows to paginate', (done) => {
const spy = sinon.spy()
off = onQuery(
contacts,
[
where('ownerId', '==', ownerId),
order('year', 'asc', [startAt(1989)]),
limit(2)
],
(docs) => {
spy(docs.map(({ data: { name } }) => name))
if (spy.calledWithMatch(['Tati', 'Lesha'])) done()
}
)
})
})
describe('endBefore', () => {
it('allows to paginate', (done) => {
const spy = sinon.spy()
off = onQuery(
contacts,
[
where('ownerId', '==', ownerId),
order('year', 'asc', [endBefore(1989)]),
limit(2)
],
(docs) => {
spy(docs.map(({ data: { name } }) => name))
if (spy.calledWithMatch(['Sasha'])) done()
}
)
})
})
describe('endAt', () => {
it('allows to paginate', (done) => {
const spy = sinon.spy()
off = onQuery(
contacts,
[
where('ownerId', '==', ownerId),
order('year', 'asc', [endAt(1989)]),
limit(2)
],
(docs) => {
spy(docs.map(({ data: { name } }) => name))
if (spy.calledWithMatch(['Sasha', 'Tati'])) done()
}
)
})
})
it('uses asc ordering method by default', (done) => {
const spy = sinon.spy()
off = onQuery(
contacts,
[
where('ownerId', '==', ownerId),
order('year', [startAt(1989)]),
limit(2)
],
(docs) => {
spy(docs.map(({ data: { name } }) => name))
if (spy.calledWithMatch(['Tati', 'Lesha'])) done()
}
)
})
it('allows specify multiple cursor conditions', async () => {
const spy = sinon.spy()
type City = { mapId: string; name: string; state: string }
const cities = collection<City>('cities')
const mapId = nanoid()
await Promise.all([
add(cities, {
mapId,
name: 'Springfield',
state: 'Massachusetts'
}),
add(cities, {
mapId,
name: 'Springfield',
state: 'Missouri'
}),
add(cities, {
mapId,
name: 'Springfield',
state: 'Wisconsin'
})
])
return new Promise(async (resolve) => {
off = await onQuery(
cities,
[
where('mapId', '==', mapId),
order('name', 'asc', [startAt('Springfield')]),
order('state', 'asc', [startAt('Missouri')]),
limit(2)
],
(docs) => {
spy(docs.map(({ data: { name, state } }) => `${name}, ${state}`))
if (
spy.calledWithMatch([
'Springfield, Missouri',
'Springfield, Wisconsin'
])
)
resolve()
}
)
})
})
it('allows to combine cursors', (done) => {
const spy = sinon.spy()
off = onQuery(
contacts,
[
where('ownerId', '==', ownerId),
order('year', 'asc', [startAt(1989), endAt(1989)]),
limit(2)
],
(docs) => {
spy(docs.map(({ data: { name } }) => name))
if (spy.calledWithMatch(['Tati'])) done()
}
)
})
it('allows to pass docs as cursors', async (done) => {
const tati = await get(contacts, tatiId)
off = onQuery(
contacts,
[
where('ownerId', '==', ownerId),
order('year', 'asc', [startAt(tati)]),
limit(2)
],
(docs) => {
off()
assert.deepEqual(
docs.map(({ data: { name } }) => name),
['Tati', 'Lesha']
)
done()
}
)
})
it('allows using dates as cursors', (done) => {
const spy = sinon.spy()
off = onQuery(
contacts,
[
where('ownerId', '==', ownerId),
order('birthday', 'asc', [startAt(new Date(1989, 6, 10))]),
limit(2)
],
(docs) => {
spy(docs.map(({ data: { name } }) => name))
if (spy.calledWithMatch(['Tati', 'Lesha'])) done()
}
)
})
})
describe('docId', () => {
type Counter = { n: number }
const shardedCounters = collection<Counter>('shardedCounters')
it('allows to query by documentId', async (done) => {
await Promise.all([
set(shardedCounters, `draft-0`, { n: 0 }),
set(shardedCounters, `draft-1`, { n: 0 }),
set(shardedCounters, `published-0`, { n: 0 }),
set(shardedCounters, `published-1`, { n: 0 }),
set(shardedCounters, `suspended-0`, { n: 0 }),
set(shardedCounters, `suspended-1`, { n: 0 })
])
const spy = sinon.spy()
off = onQuery(
shardedCounters,
[where(docId, '>=', 'published'), where(docId, '<', 'publishee')],
(docs) => {
spy(docs.map((doc) => doc.ref.id))
if (spy.calledWithMatch(['published-0', 'published-1'])) done()
}
)
})
it('allows ordering by documentId', () => {
const offs: Array<() => void> = []
;(off) => offs.map((o) => o())
return Promise.all([
new Promise((resolve) => {
const spy = sinon.spy()
offs.push(
onQuery(
shardedCounters,
[
where(docId, '>=', 'published'),
where(docId, '<', 'publishee'),
order(docId, 'desc')
],
(descend) => {
spy(descend.map((doc) => doc.ref.id))
if (spy.calledWithMatch(['published-1', 'published-0']))
resolve()
}
)
)
}),
new Promise((resolve) => {
const spy = sinon.spy()
offs.push(
onQuery(
shardedCounters,
[
where(docId, '>=', 'published'),
where(docId, '<', 'publishee'),
order(docId, 'asc')
],
(ascend) => {
spy(ascend.map((doc) => doc.ref.id))
if (spy.calledWithMatch(['published-0', 'published-1']))
resolve()
}
)
)
})
])
})
it('allows cursors to use documentId', (done) => {
const spy = sinon.spy()
off = onQuery(
shardedCounters,
[order(docId, 'asc', [startAt('draft-1'), endAt('published-1')])],
(docs) => {
spy(docs.map((doc) => doc.ref.id))
if (spy.calledWithMatch(['draft-1', 'published-0', 'published-1']))
done()
}
)
})
})
describe('empty', () => {
it('should notify with values all indicate empty', (done) => {
off = onQuery(
collection<{ ability: string[] }>('penguin'),
[where('ability', 'array-contains', 'fly')],
(docs, { changes, empty }) => {
expect(empty).toBeTruthy()
expect(docs).toHaveLength(0)
expect(changes()).toHaveLength(0)
done()
}
)
})
})
describe('real-time', () => {
const theoId = `theo-${ownerId}`
afterEach(async () => {
await remove(contacts, theoId)
})
it('subscribes to updates', (done) => {
let c = 0
off = onQuery(
contacts,
[
where('ownerId', '==', ownerId),
// TODO: Figure out why when a timestamp is used, the order is incorrect
// order('birthday', 'asc', [startAt(new Date(1989, 6, 10))]),
order('year', 'asc', [startAt(1989)]),
limit(3)
],
async (docs, { changes }) => {
const names = docs.map(({ data: { name } }) => name).sort()
const docChanges = changes()
.map(({ type, doc: { data: { name } } }) => ({ type, name }))
.sort((a, b) => a.name.localeCompare(b.name))
switch (++c) {
case 1:
expect(names).toEqual(['Lesha', 'Tati'])
expect(docChanges).toEqual([
{ type: 'added', name: 'Lesha' },
{ type: 'added', name: 'Tati' }
])
await set(contacts, theoId, {
ownerId,
name: 'Theodor',
year: 2019,
birthday: new Date(2019, 5, 4)
})
return
case 2:
expect(names).toEqual(['Lesha', 'Tati', 'Theodor'])
expect(docChanges).toEqual([{ type: 'added', name: 'Theodor' }])
await remove(contacts, leshaId)
return
case 3:
expect(docChanges).toEqual([{ type: 'removed', name: 'Theodor' }])
done()
}
}
)
})
// TODO: WTF browser Firebase returns elements gradually unlike Node.js version.
// TODO: For whatever reason this test fails within the emulator environment
if (typeof window === 'undefined' && !process.env.FIRESTORE_EMULATOR_HOST) {
it('returns function that unsubscribes from the updates', () => {
return new Promise(async (resolve) => {
const spy = sinon.spy()
const on = () => {
off = onQuery(
contacts,
[
where('ownerId', '==', ownerId),
// TODO: Figure out why when a timestamp is used, the order is incorrect
// order('birthday', 'asc', [startAt(new Date(1989, 6, 10))]),
order('year', 'asc', [startAt(1989)]),
limit(3)
],
async (docs) => {
const names = docs.map(({ data: { name } }) => name)
spy(names)
if (
spy.calledWithMatch(['Tati', 'Theodor']) &&
spy.neverCalledWithMatch(['Tati', 'Lesha', 'Theodor'])
)
resolve()
}
)
}
on()
off()
await remove(contacts, leshaId)
on()
})
})
}
// TODO: For whatever reason this test fails within the emulator environment
if (!process.env.FIRESTORE_EMULATOR_HOST) {
it('calls onError when query is invalid', (done) => {
const onResult = sinon.spy()
off = onQuery(
contacts,
[
where('ownerId', '==', ownerId),
where('year', '>', 1989),
where('birthday', '>', new Date(1989, 6, 10))
],
onResult,
(err) => {
assert(!onResult.called)
assert(
// Node.js:
err.message.match(
/Cannot have inequality filters on multiple properties: birthday/
) ||
// Browser:
err.message.match(/Invalid query/)
)
done()
}
)
})
}
})
}) | the_stack |
import { when } from 'jest-when';
import { Store } from 'redux';
import * as Actions from '../../src/redux/Actions';
import { initialState } from '../../src/redux/State';
// tslint:disable-next-line: import-name
import createStore from '../../src/redux/Store';
import { ReduxAction, ReduxConstants } from '../../src/typings/ReduxConstants';
import * as CleanupService from '../../src/services/CleanupService';
import ContextMenuEvents from '../../src/services/ContextMenuEvents';
import * as Lib from '../../src/services/Libs';
import StoreUser from '../../src/services/StoreUser';
jest.requireActual('../../src/redux/Actions');
const spyActions: JestSpyObject = global.generateSpies(Actions);
jest.requireMock('../../src/services/CleanupService');
const spyCleanupService: JestSpyObject = global.generateSpies(CleanupService);
jest.requireActual('../../src/services/Libs');
const spyLib: JestSpyObject = global.generateSpies(Lib);
const store: Store<State, ReduxAction> = createStore(initialState);
StoreUser.init(store);
class TestStore extends StoreUser {
public static addCache(payload: any) {
StoreUser.store.dispatch({
payload,
type: ReduxConstants.ADD_CACHE,
});
}
public static changeSetting(
name: SettingID,
value: string | boolean | number,
) {
StoreUser.store.dispatch(Actions.updateSetting({ name, value }));
}
public static resetSetting() {
StoreUser.store.dispatch(Actions.resetSettings());
}
}
class TestContextMenuEvents extends ContextMenuEvents {
public static getIsInitialized() {
return ContextMenuEvents.isInitialized;
}
public static setIsInitialized(value: boolean) {
ContextMenuEvents.isInitialized = value;
}
public static spyAddNewExpression = jest.spyOn(
ContextMenuEvents,
'addNewExpression' as never,
);
}
const sampleTab: browser.tabs.Tab = {
active: true,
cookieStoreId: 'firefox-default',
discarded: false,
hidden: false,
highlighted: false,
incognito: false,
index: 0,
isArticle: false,
isInReaderMode: false,
lastAccessed: 12345678,
pinned: false,
selected: true,
url: 'https://www.example.com',
windowId: 1,
};
const defaultOnClickData: browser.contextMenus.OnClickData = {
editable: false,
menuItemId: 'replaceMe',
modifiers: [],
};
const sampleClickLink: browser.contextMenus.OnClickData = {
...defaultOnClickData,
linkUrl: 'https://link.cad',
};
const sampleClickPage: browser.contextMenus.OnClickData = {
...defaultOnClickData,
pageUrl: 'https://page.cad',
};
const sampleClickText: browser.contextMenus.OnClickData = {
...defaultOnClickData,
selectionText: 'selectedText',
};
const sampleClickTextMultiple: browser.contextMenus.OnClickData = {
...defaultOnClickData,
selectionText: 'selectedText, MultipleText, ThirdText',
};
describe('ContextMenuEvents', () => {
beforeAll(() => {
when(global.browser.runtime.getManifest)
.calledWith()
.mockReturnValue({ version: '0.12.34' } as never);
});
afterEach(() => {
TestStore.resetSetting();
});
describe('menuInit', () => {
it('should do nothing if browser.contextMenus do not exist', () => {
// Override setup of browser.contextMenus
const jestContextMenus = global.browser.contextMenus;
global.browser.contextMenus = undefined;
ContextMenuEvents.menuInit();
expect(spyLib.getSetting).not.toHaveBeenCalled();
// Restore browser.contextMenus for future tests
global.browser.contextMenus = jestContextMenus;
});
it('should do nothing if contextMenus setting is disabled', () => {
TestStore.changeSetting(SettingID.CONTEXT_MENUS, false);
ContextMenuEvents.menuInit();
expect(global.browser.contextMenus.create).not.toHaveBeenCalled();
});
it('should create its menus contextMenus setting is enabled and none was created beforehand', () => {
when(global.browser.contextMenus.onClicked.hasListener)
.calledWith(expect.any(Function))
.mockReturnValue(false);
TestStore.changeSetting(SettingID.CONTEXT_MENUS, true);
ContextMenuEvents.menuInit();
expect(TestContextMenuEvents.getIsInitialized()).toBe(true);
expect(global.browser.contextMenus.create).toHaveBeenCalledTimes(35);
expect(
global.browser.contextMenus.onClicked.addListener,
).toHaveBeenCalledTimes(1);
});
it('should not add another listener if one was already added', () => {
when(global.browser.contextMenus.onClicked.hasListener)
.calledWith(expect.any(Function))
.mockReturnValue(true);
TestStore.changeSetting(SettingID.CONTEXT_MENUS, true);
TestContextMenuEvents.setIsInitialized(false);
ContextMenuEvents.menuInit();
expect(
global.browser.contextMenus.onClicked.addListener,
).not.toHaveBeenCalled();
});
it('should do nothing if contextMenus setting is enabled and menus were already created', () => {
TestStore.changeSetting(SettingID.CONTEXT_MENUS, true);
TestContextMenuEvents.setIsInitialized(true);
ContextMenuEvents.menuInit();
expect(global.browser.contextMenus.create).not.toHaveBeenCalled();
});
});
describe('menuClear', () => {
it('should work', async () => {
TestContextMenuEvents.setIsInitialized(true);
await ContextMenuEvents.menuClear();
expect(
global.browser.contextMenus.onClicked.removeListener,
).toHaveBeenCalledTimes(1);
expect(TestContextMenuEvents.getIsInitialized()).toBe(false);
});
});
describe('updateMenuItemCheckbox', () => {
it('should work', () => {
when(global.browser.contextMenus.update)
.calledWith(expect.any(String), expect.any(Object))
.mockResolvedValue(true as never);
ContextMenuEvents.updateMenuItemCheckbox('test', true);
expect(global.browser.contextMenus.update).toHaveBeenCalledTimes(1);
});
});
// While the above test does also call onCreatedOrUpdated, we need a fail catch
describe('onCreatedOrUpdated', () => {
it('should show error if failed', () => {
global.browser.runtime.lastError = 'testError';
ContextMenuEvents.onCreatedOrUpdated();
// The if statements both perform cadLog, so we need to check for the error one.
expect(spyLib.cadLog.mock.calls[0][0].msg.indexOf('testError')).not.toBe(
-1,
);
expect(spyLib.cadLog.mock.calls[0][0].type).toBe('error');
global.browser.runtime.lastError = undefined;
});
});
// This test block will also consume coverage for addNewExpression
describe('onContextMenuClicked - aka the big switch statement', () => {
beforeAll(() => {
// Required otherwise NodeJS will complain about unhandledPromiseRejects
when(spyCleanupService.cleanCookiesOperation)
.calledWith(expect.any(Object), expect.any(Object))
.mockResolvedValue(undefined as never);
when(spyCleanupService.clearCookiesForThisDomain)
.calledWith(expect.any(Object), expect.any(Object))
.mockResolvedValue(true as never);
when(spyCleanupService.clearLocalStorageForThisDomain)
.calledWith(expect.any(Object), expect.any(Object))
.mockResolvedValue(true as never);
});
it('should show warning through cadLog if menuId given is unknown', () => {
ContextMenuEvents.onContextMenuClicked(defaultOnClickData, sampleTab);
expect(
spyLib.cadLog.mock.calls[1][0].msg.indexOf('unknown menu id'),
).not.toBe(-1);
expect(spyLib.cadLog.mock.calls[1][0].type).toBe('warn');
});
// Manual Clean Menu
it('Trigger Normal Clean', () => {
ContextMenuEvents.onContextMenuClicked(
{
...defaultOnClickData,
menuItemId: ContextMenuEvents.MenuID.CLEAN,
},
sampleTab,
);
expect(spyCleanupService.cleanCookiesOperation).toHaveBeenCalledWith(
expect.any(Object),
{
greyCleanup: false,
ignoreOpenTabs: false,
},
);
});
it('Trigger Clean, Include Open Tabs', () => {
ContextMenuEvents.onContextMenuClicked(
{
...defaultOnClickData,
menuItemId: ContextMenuEvents.MenuID.CLEAN_OPEN,
},
sampleTab,
);
expect(spyCleanupService.cleanCookiesOperation).toHaveBeenCalledWith(
expect.any(Object),
{
greyCleanup: false,
ignoreOpenTabs: true,
},
);
});
it('Trigger Clear All Site Data For This Domain', () => {
ContextMenuEvents.onContextMenuClicked(
{
...defaultOnClickData,
menuItemId: `${ContextMenuEvents.MenuID.MANUAL_CLEAN_SITEDATA}All`,
},
sampleTab,
);
expect(spyCleanupService.clearSiteDataForThisDomain).toHaveBeenCalledWith(
expect.any(Object),
'All',
expect.any(String),
);
});
it('Clear Site Data For This Domain was clicked, but hostname was blank', () => {
ContextMenuEvents.onContextMenuClicked(
{
...defaultOnClickData,
menuItemId: `${ContextMenuEvents.MenuID.MANUAL_CLEAN_SITEDATA}All`,
},
{ ...sampleTab, url: 'about:blank' },
);
expect(
spyCleanupService.clearSiteDataForThisDomain,
).not.toHaveBeenCalled();
});
it('Trigger Clear Cache For This Domain', () => {
ContextMenuEvents.onContextMenuClicked(
{
...defaultOnClickData,
menuItemId: `${ContextMenuEvents.MenuID.MANUAL_CLEAN_SITEDATA}Cache`,
},
sampleTab,
);
expect(spyCleanupService.clearSiteDataForThisDomain).toHaveBeenCalledWith(
expect.any(Object),
'Cache',
expect.any(String),
);
});
it('Trigger Clear Cookies For This Domain', () => {
ContextMenuEvents.onContextMenuClicked(
{
...defaultOnClickData,
menuItemId: `${ContextMenuEvents.MenuID.MANUAL_CLEAN_SITEDATA}Cookies`,
},
sampleTab,
);
expect(spyCleanupService.clearCookiesForThisDomain).toHaveBeenCalled();
});
it('Trigger Clear IndexedDB For This Domain', () => {
ContextMenuEvents.onContextMenuClicked(
{
...defaultOnClickData,
menuItemId: `${ContextMenuEvents.MenuID.MANUAL_CLEAN_SITEDATA}IndexedDB`,
},
sampleTab,
);
expect(spyCleanupService.clearSiteDataForThisDomain).toHaveBeenCalledWith(
expect.any(Object),
'IndexedDB',
expect.any(String),
);
});
it('Trigger Clear LocalStorage For This Domain', () => {
ContextMenuEvents.onContextMenuClicked(
{
...defaultOnClickData,
menuItemId: `${ContextMenuEvents.MenuID.MANUAL_CLEAN_SITEDATA}LocalStorage`,
},
sampleTab,
);
expect(
spyCleanupService.clearLocalStorageForThisDomain,
).toHaveBeenCalledTimes(1);
});
it('Trigger Clear Plugin Data For This Domain', () => {
ContextMenuEvents.onContextMenuClicked(
{
...defaultOnClickData,
menuItemId: `${ContextMenuEvents.MenuID.MANUAL_CLEAN_SITEDATA}PluginData`,
},
sampleTab,
);
expect(spyCleanupService.clearSiteDataForThisDomain).toHaveBeenCalledWith(
expect.any(Object),
'PluginData',
expect.any(String),
);
});
it('Trigger Clear Service Workers For This Domain', () => {
ContextMenuEvents.onContextMenuClicked(
{
...defaultOnClickData,
menuItemId: `${ContextMenuEvents.MenuID.MANUAL_CLEAN_SITEDATA}ServiceWorkers`,
},
sampleTab,
);
expect(spyCleanupService.clearSiteDataForThisDomain).toHaveBeenCalledWith(
expect.any(Object),
'ServiceWorkers',
expect.any(String),
);
});
it('Unknown Site Data Type was pass in. Extreme case.', () => {
ContextMenuEvents.onContextMenuClicked(
{
...defaultOnClickData,
menuItemId: `${ContextMenuEvents.MenuID.MANUAL_CLEAN_SITEDATA}Test`,
},
sampleTab,
);
expect(
spyCleanupService.clearSiteDataForThisDomain,
).not.toHaveBeenCalled();
});
// Add Expression via link
it('Trigger LINK_ADD_GREY_DOMAIN', () => {
ContextMenuEvents.onContextMenuClicked(
{
...sampleClickLink,
menuItemId: ContextMenuEvents.MenuID.LINK_ADD_GREY_DOMAIN,
},
sampleTab,
);
expect(TestContextMenuEvents.spyAddNewExpression).toHaveBeenCalledWith(
'link.cad',
ListType.GREY,
'firefox-default',
);
});
it('Trigger LINK_ADD_WHITE_DOMAIN', () => {
ContextMenuEvents.onContextMenuClicked(
{
...sampleClickLink,
menuItemId: ContextMenuEvents.MenuID.LINK_ADD_WHITE_DOMAIN,
},
sampleTab,
);
expect(TestContextMenuEvents.spyAddNewExpression).toHaveBeenCalledWith(
'link.cad',
ListType.WHITE,
'firefox-default',
);
});
it('Trigger LINK_ADD_GREY_SUBS', () => {
ContextMenuEvents.onContextMenuClicked(
{
...sampleClickLink,
menuItemId: ContextMenuEvents.MenuID.LINK_ADD_GREY_SUBS,
},
sampleTab,
);
expect(TestContextMenuEvents.spyAddNewExpression).toHaveBeenCalledWith(
'*.link.cad',
ListType.GREY,
'firefox-default',
);
});
it('Trigger LINK_ADD_WHITE_SUBS', () => {
ContextMenuEvents.onContextMenuClicked(
{
...sampleClickLink,
menuItemId: ContextMenuEvents.MenuID.LINK_ADD_WHITE_SUBS,
},
sampleTab,
);
expect(TestContextMenuEvents.spyAddNewExpression).toHaveBeenCalledWith(
'*.link.cad',
ListType.WHITE,
'firefox-default',
);
});
// Add Expression via Page
it('Trigger PAGE_ADD_GREY_DOMAIN', () => {
ContextMenuEvents.onContextMenuClicked(
{
...sampleClickPage,
menuItemId: ContextMenuEvents.MenuID.PAGE_ADD_GREY_DOMAIN,
},
sampleTab,
);
expect(TestContextMenuEvents.spyAddNewExpression).toHaveBeenCalledWith(
'page.cad',
ListType.GREY,
'firefox-default',
);
});
it('Trigger PAGE_ADD_WHITE_DOMAIN', () => {
ContextMenuEvents.onContextMenuClicked(
{
...sampleClickPage,
menuItemId: ContextMenuEvents.MenuID.PAGE_ADD_WHITE_DOMAIN,
},
sampleTab,
);
expect(TestContextMenuEvents.spyAddNewExpression).toHaveBeenCalledWith(
'page.cad',
ListType.WHITE,
'firefox-default',
);
});
it('Trigger PAGE_ADD_GREY_SUBS', () => {
ContextMenuEvents.onContextMenuClicked(
{
...sampleClickPage,
menuItemId: ContextMenuEvents.MenuID.PAGE_ADD_GREY_SUBS,
},
sampleTab,
);
expect(TestContextMenuEvents.spyAddNewExpression).toHaveBeenCalledWith(
'*.page.cad',
ListType.GREY,
'firefox-default',
);
});
it('Trigger PAGE_ADD_WHITE_SUBS', () => {
ContextMenuEvents.onContextMenuClicked(
{
...sampleClickPage,
menuItemId: ContextMenuEvents.MenuID.PAGE_ADD_WHITE_SUBS,
},
sampleTab,
);
expect(TestContextMenuEvents.spyAddNewExpression).toHaveBeenCalledWith(
'*.page.cad',
ListType.WHITE,
'firefox-default',
);
});
// Add Expression via Selected Text
it('Trigger SELECT_ADD_GREY_DOMAIN', () => {
ContextMenuEvents.onContextMenuClicked(
{
...sampleClickText,
menuItemId: ContextMenuEvents.MenuID.SELECT_ADD_GREY_DOMAIN,
},
sampleTab,
);
expect(TestContextMenuEvents.spyAddNewExpression).toHaveBeenCalledWith(
'selectedText',
ListType.GREY,
'firefox-default',
);
});
it('Trigger SELECT_ADD_GREY_DOMAIN and contextualIdentities was enabled', () => {
TestStore.changeSetting(SettingID.CONTEXTUAL_IDENTITIES, true);
TestStore.addCache({
key: 'firefox-container-1',
value: 'Personal',
});
ContextMenuEvents.onContextMenuClicked(
{
...sampleClickText,
menuItemId: ContextMenuEvents.MenuID.SELECT_ADD_GREY_DOMAIN,
},
{ ...sampleTab, cookieStoreId: 'firefox-container-1' },
);
expect(TestContextMenuEvents.spyAddNewExpression).toHaveBeenCalledWith(
'selectedText',
ListType.GREY,
'firefox-container-1',
);
});
it('Trigger SELECT_ADD_GREY_DOMAIN and contextualIdentities was enabled with no matching container', () => {
TestStore.changeSetting(SettingID.CONTEXTUAL_IDENTITIES, true);
ContextMenuEvents.onContextMenuClicked(
{
...sampleClickText,
menuItemId: ContextMenuEvents.MenuID.SELECT_ADD_GREY_DOMAIN,
},
{ ...sampleTab, cookieStoreId: 'firefox-container-2' },
);
expect(TestContextMenuEvents.spyAddNewExpression).toHaveBeenCalledWith(
'selectedText',
ListType.GREY,
'firefox-container-2',
);
});
it('Trigger SELECT_ADD_WHITE_DOMAIN', () => {
ContextMenuEvents.onContextMenuClicked(
{
...sampleClickText,
menuItemId: ContextMenuEvents.MenuID.SELECT_ADD_WHITE_DOMAIN,
},
sampleTab,
);
expect(TestContextMenuEvents.spyAddNewExpression).toHaveBeenCalledWith(
'selectedText',
ListType.WHITE,
'firefox-default',
);
});
it('Trigger SELECT_ADD_GREY_SUBS', () => {
ContextMenuEvents.onContextMenuClicked(
{
...sampleClickText,
menuItemId: ContextMenuEvents.MenuID.SELECT_ADD_GREY_SUBS,
},
sampleTab,
);
expect(TestContextMenuEvents.spyAddNewExpression).toHaveBeenCalledWith(
'*.selectedText',
ListType.GREY,
'firefox-default',
);
});
it('Trigger SELECT_ADD_WHITE_SUBS', () => {
ContextMenuEvents.onContextMenuClicked(
{
...sampleClickText,
menuItemId: ContextMenuEvents.MenuID.SELECT_ADD_WHITE_SUBS,
},
sampleTab,
);
expect(TestContextMenuEvents.spyAddNewExpression).toHaveBeenCalledWith(
'*.selectedText',
ListType.WHITE,
'firefox-default',
);
});
it('Trigger SELECT_ADD_WHITE_SUBS with multiple comma-separated values', () => {
ContextMenuEvents.onContextMenuClicked(
{
...sampleClickTextMultiple,
menuItemId: ContextMenuEvents.MenuID.SELECT_ADD_WHITE_SUBS,
},
sampleTab,
);
expect(TestContextMenuEvents.spyAddNewExpression).toHaveBeenCalledTimes(
3,
);
});
it('Trigger SELECT_ADD_WHITE_SUBS with whitespaces only', () => {
ContextMenuEvents.onContextMenuClicked(
{
...defaultOnClickData,
menuItemId: ContextMenuEvents.MenuID.SELECT_ADD_WHITE_SUBS,
selectionText: ' ',
},
sampleTab,
);
expect(global.browser.i18n.getMessage).toHaveBeenCalledWith(
'addNewExpressionNotificationFailed',
);
expect(spyActions.addExpressionUI).not.toHaveBeenCalled();
});
it('Trigger SELECT_ADD_WHITE_SUBS with undefined cookieStoreId (Chrome)', () => {
ContextMenuEvents.onContextMenuClicked(
{
...sampleClickText,
menuItemId: ContextMenuEvents.MenuID.SELECT_ADD_WHITE_SUBS,
},
{ ...sampleTab, cookieStoreId: undefined },
);
expect(TestContextMenuEvents.spyAddNewExpression).toHaveBeenCalledWith(
'*.selectedText',
ListType.WHITE,
'',
);
});
it('Trigger SELECT_ADD_WHITE_SUBS with undefined inputs to addNewExpression', () => {
ContextMenuEvents.onContextMenuClicked(
{
...defaultOnClickData,
selectionText: undefined,
menuItemId: ContextMenuEvents.MenuID.SELECT_ADD_WHITE_SUBS,
},
{ ...sampleTab, cookieStoreId: undefined },
);
expect(TestContextMenuEvents.spyAddNewExpression).toHaveBeenCalledWith(
'*.',
ListType.WHITE,
'',
);
});
it('Trigger Toggle of ACTIVE_MODE', () => {
ContextMenuEvents.onContextMenuClicked(
{
...defaultOnClickData,
menuItemId: ContextMenuEvents.MenuID.ACTIVE_MODE,
checked: true,
wasChecked: false,
},
sampleTab,
);
expect(spyActions.updateSetting).toHaveBeenCalledWith({
name: SettingID.ACTIVE_MODE,
value: true,
});
});
it('Trigger ACTIVE_MODE and both checked and wasChecked was same value (no updateSetting call)', () => {
ContextMenuEvents.onContextMenuClicked(
{
...defaultOnClickData,
menuItemId: ContextMenuEvents.MenuID.ACTIVE_MODE,
checked: true,
wasChecked: true,
},
sampleTab,
);
expect(spyActions.updateSetting).not.toHaveBeenCalled();
});
it('Trigger Open Settings', () => {
ContextMenuEvents.onContextMenuClicked(
{
...defaultOnClickData,
menuItemId: ContextMenuEvents.MenuID.SETTINGS,
},
sampleTab,
);
expect(global.browser.tabs.create).toHaveBeenCalledTimes(1);
});
});
}); | the_stack |
// <reference path="scanner.ts"/>
/////////////////////////////////////////////////////////////////////////
//
// RefScript
type INode = ts.Node<Immutable>
type INodeLinks = ts.NodeLinks<Immutable>
type ISymbol = ts.Symbol<Immutable>
type ISymbolLinks = ts.SymbolLinks<Immutable>
type IType = ts.Type<Immutable>
type ISignature = ts.Signature<Immutable>
type IDeclaration = ts.Declaration<Immutable>
type ISourceFile = ts.SourceFile<Immutable>
/*@ predicate non_zero (b) = (b /= lit "#x00000000" (BitVec Size32)) */
/*@ predicate typeflags_any (v) = (v = lit "#x00000001" (BitVec Size32)) */
/*@ predicate typeflags_string (v) = (v = lit "#x00000002" (BitVec Size32)) */
/*@ predicate typeflags_number (v) = (v = lit "#x00000004" (BitVec Size32)) */
/*@ predicate typeflags_boolean (v) = (v = lit "#x00000008" (BitVec Size32)) */
/*@ predicate typeflags_void (v) = (v = lit "#x00000010" (BitVec Size32)) */
/*@ predicate typeflags_undefined (v) = (v = lit "#x00000020" (BitVec Size32)) */
/*@ predicate typeflags_null (v) = (v = lit "#x00000040" (BitVec Size32)) */
/*@ predicate typeflags_enum (v) = (v = lit "#x00000080" (BitVec Size32)) */
/*@ predicate typeflags_stringliteral (v) = (v = lit "#x00000100" (BitVec Size32)) */
/*@ predicate typeflags_typeparameter (v) = (v = lit "#x00000200" (BitVec Size32)) */
/*@ predicate typeflags_class (v) = (v = lit "#x00000400" (BitVec Size32)) */
/*@ predicate typeflags_interface (v) = (v = lit "#x00000800" (BitVec Size32)) */
/*@ predicate typeflags_reference (v) = (v = lit "#x00001000" (BitVec Size32)) */
/*@ predicate typeflags_anonymous (v) = (v = lit "#x00002000" (BitVec Size32)) */
/*@ predicate typeflags_fromsignature (v) = (v = lit "#x00004000" (BitVec Size32)) */
/*@ predicate typeflags_objecttype (v) = (v = lit "#x00003C00" (BitVec Size32)) */
/*@ predicate symbolflags_variable (v) = (v = lit "#x00000001" (BitVec Size32)) */
/*@ predicate symbolflags_property (v) = (v = lit "#x00000002" (BitVec Size32)) */
/*@ predicate symbolflags_enummember (v) = (v = lit "#x00000004" (BitVec Size32)) */
/*@ predicate symbolflags_function (v) = (v = lit "#x00000008" (BitVec Size32)) */
/*@ predicate symbolflags_class (v) = (v = lit "#x00000010" (BitVec Size32)) */
/*@ predicate symbolflags_interface (v) = (v = lit "#x00000020" (BitVec Size32)) */
/*@ predicate symbolflags_enum (v) = (v = lit "#x00000040" (BitVec Size32)) */
/*@ predicate symbolflags_valuemodule (v) = (v = lit "#x00000080" (BitVec Size32)) */
/*@ predicate symbolflags_namespacemodule (v) = (v = lit "#x00000100" (BitVec Size32)) */
/*@ predicate symbolflags_typeliteral (v) = (v = lit "#x00000200" (BitVec Size32)) */
/*@ predicate symbolflags_objectliteral (v) = (v = lit "#x00000400" (BitVec Size32)) */
/*@ predicate symbolflags_method (v) = (v = lit "#x00000800" (BitVec Size32)) */
/*@ predicate symbolflags_constructor (v) = (v = lit "#x00001000" (BitVec Size32)) */
/*@ predicate symbolflags_getaccessor (v) = (v = lit "#x00002000" (BitVec Size32)) */
/*@ predicate symbolflags_setaccessor (v) = (v = lit "#x00004000" (BitVec Size32)) */
/*@ predicate symbolflags_callsignature (v) = (v = lit "#x00008000" (BitVec Size32)) */
/*@ predicate symbolflags_constructsignature (v) = (v = lit "#x00010000" (BitVec Size32)) */
/*@ predicate symbolflags_indexsignature (v) = (v = lit "#x00020000" (BitVec Size32)) */
/*@ predicate symbolflags_typeparameter (v) = (v = lit "#x00040000" (BitVec Size32)) */
/*@ predicate symbolflags_exportvalue (v) = (v = lit "#x00080000" (BitVec Size32)) */
/*@ predicate symbolflags_exporttype (v) = (v = lit "#x00100000" (BitVec Size32)) */
/*@ predicate symbolflags_exportnamespace (v) = (v = lit "#x00200000" (BitVec Size32)) */
/*@ predicate symbolflags_import (v) = (v = lit "#x00400000" (BitVec Size32)) */
/*@ predicate symbolflags_instantiated (v) = (v = lit "#x00800000" (BitVec Size32)) */
/*@ predicate symbolflags_merged (v) = (v = lit "#x01000000" (BitVec Size32)) */
/*@ predicate symbolflags_transient (v) = (v = lit "#x02000000" (BitVec Size32)) */
/*@ predicate symbolflags_prototype (v) = (v = lit "#x04000000" (BitVec Size32)) */
/*@ predicate mask_typeflags_any (v) = (non_zero(bvand v (lit "#x00000001" (BitVec Size32)))) */
/*@ predicate mask_typeflags_string (v) = (non_zero(bvand v (lit "#x00000002" (BitVec Size32)))) */
/*@ predicate mask_typeflags_number (v) = (non_zero(bvand v (lit "#x00000004" (BitVec Size32)))) */
/*@ predicate mask_typeflags_boolean (v) = (non_zero(bvand v (lit "#x00000008" (BitVec Size32)))) */
/*@ predicate mask_typeflags_void (v) = (non_zero(bvand v (lit "#x00000010" (BitVec Size32)))) */
/*@ predicate mask_typeflags_undefined (v) = (non_zero(bvand v (lit "#x00000020" (BitVec Size32)))) */
/*@ predicate mask_typeflags_null (v) = (non_zero(bvand v (lit "#x00000040" (BitVec Size32)))) */
/*@ predicate mask_typeflags_enum (v) = (non_zero(bvand v (lit "#x00000080" (BitVec Size32)))) */
/*@ predicate mask_typeflags_stringliteral (v) = (non_zero(bvand v (lit "#x00000100" (BitVec Size32)))) */
/*@ predicate mask_typeflags_typeparameter (v) = (non_zero(bvand v (lit "#x00000200" (BitVec Size32)))) */
/*@ predicate mask_typeflags_class (v) = (non_zero(bvand v (lit "#x00000400" (BitVec Size32)))) */
/*@ predicate mask_typeflags_interface (v) = (non_zero(bvand v (lit "#x00000800" (BitVec Size32)))) */
/*@ predicate mask_typeflags_reference (v) = (non_zero(bvand v (lit "#x00001000" (BitVec Size32)))) */
/*@ predicate mask_typeflags_anonymous (v) = (non_zero(bvand v (lit "#x00002000" (BitVec Size32)))) */
/*@ predicate mask_typeflags_fromsignature (v) = (non_zero(bvand v (lit "#x00004000" (BitVec Size32)))) */
/*@ predicate mask_typeflags_objecttype (v) = (non_zero(bvand v (lit "#x00003C00" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_variable (v) = (non_zero(bvand v (lit "#x00000001" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_property (v) = (non_zero(bvand v (lit "#x00000002" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_enummember (v) = (non_zero(bvand v (lit "#x00000004" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_function (v) = (non_zero(bvand v (lit "#x00000008" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_class (v) = (non_zero(bvand v (lit "#x00000010" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_interface (v) = (non_zero(bvand v (lit "#x00000020" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_enum (v) = (non_zero(bvand v (lit "#x00000040" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_valuemodule (v) = (non_zero(bvand v (lit "#x00000080" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_namespacemodule (v) = (non_zero(bvand v (lit "#x00000100" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_typeliteral (v) = (non_zero(bvand v (lit "#x00000200" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_objectliteral (v) = (non_zero(bvand v (lit "#x00000400" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_method (v) = (non_zero(bvand v (lit "#x00000800" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_constructor (v) = (non_zero(bvand v (lit "#x00001000" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_getaccessor (v) = (non_zero(bvand v (lit "#x00002000" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_setaccessor (v) = (non_zero(bvand v (lit "#x00004000" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_callsignature (v) = (non_zero(bvand v (lit "#x00008000" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_constructsignature(v) = (non_zero(bvand v (lit "#x00010000" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_indexsignature (v) = (non_zero(bvand v (lit "#x00020000" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_typeparameter (v) = (non_zero(bvand v (lit "#x00040000" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_exportvalue (v) = (non_zero(bvand v (lit "#x00080000" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_exporttype (v) = (non_zero(bvand v (lit "#x00100000" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_exportnamespace (v) = (non_zero(bvand v (lit "#x00200000" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_import (v) = (non_zero(bvand v (lit "#x00400000" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_instantiated (v) = (non_zero(bvand v (lit "#x00800000" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_merged (v) = (non_zero(bvand v (lit "#x01000000" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_transient (v) = (non_zero(bvand v (lit "#x02000000" (BitVec Size32)))) */
/*@ predicate mask_symbolflags_prototype (v) = (non_zero(bvand v (lit "#x04000000" (BitVec Size32)))) */
/*@ predicate type_flags(v,o) = (mask_typeflags_objecttype(v) => extends_interface(o,"ts.ObjectType")) &&
(mask_typeflags_anonymous (v) => extends_interface(o,"ts.ResolvedObjectType")) &&
(mask_typeflags_reference (v) => extends_interface(o,"ts.TypeReference"))
*/
//
/////////////////////////////////////////////////////////////////////////
module ts {
export interface Map<M extends ReadOnly, T> {
[index: string]: T;
}
export interface TextRange<M extends ReadOnly> {
pos: number;
end: number;
}
// token > SyntaxKind.Identifer => token is a keyword
export enum SyntaxKind {
Unknown,
EndOfFileToken,
// Literals
NumericLiteral,
StringLiteral,
RegularExpressionLiteral,
// Punctuation
OpenBraceToken,
CloseBraceToken,
OpenParenToken,
CloseParenToken,
OpenBracketToken,
CloseBracketToken,
DotToken,
// DotDotDotToken,
// SemicolonToken,
// CommaToken,
// LessThanToken,
// GreaterThanToken,
// LessThanEqualsToken,
// GreaterThanEqualsToken,
// EqualsEqualsToken,
// ExclamationEqualsToken,
// EqualsEqualsEqualsToken,
// ExclamationEqualsEqualsToken,
// EqualsGreaterThanToken,
// PlusToken,
// MinusToken,
// AsteriskToken,
// SlashToken,
// PercentToken,
// PlusPlusToken,
// MinusMinusToken,
// LessThanLessThanToken,
// GreaterThanGreaterThanToken,
// GreaterThanGreaterThanGreaterThanToken,
// AmpersandToken,
// BarToken,
// CaretToken,
// ExclamationToken,
// TildeToken,
// AmpersandAmpersandToken,
// BarBarToken,
// QuestionToken,
// ColonToken,
// // Assignments
// EqualsToken,
// PlusEqualsToken,
// MinusEqualsToken,
// AsteriskEqualsToken,
// SlashEqualsToken,
// PercentEqualsToken,
// LessThanLessThanEqualsToken,
// GreaterThanGreaterThanEqualsToken,
// GreaterThanGreaterThanGreaterThanEqualsToken,
// AmpersandEqualsToken,
// BarEqualsToken,
// CaretEqualsToken,
// // Identifiers
// Identifier,
// // Reserved words
// BreakKeyword,
// CaseKeyword,
// CatchKeyword,
// ClassKeyword,
// ConstKeyword,
// ContinueKeyword,
// DebuggerKeyword,
// DefaultKeyword,
// DeleteKeyword,
// DoKeyword,
// ElseKeyword,
// EnumKeyword,
// ExportKeyword,
// ExtendsKeyword,
// FalseKeyword,
// FinallyKeyword,
// ForKeyword,
// FunctionKeyword,
// IfKeyword,
// ImportKeyword,
// InKeyword,
// InstanceOfKeyword,
// NewKeyword,
// NullKeyword,
// ReturnKeyword,
// SuperKeyword,
// SwitchKeyword,
// ThisKeyword,
// ThrowKeyword,
// TrueKeyword,
// TryKeyword,
// TypeOfKeyword,
// VarKeyword,
// VoidKeyword,
// WhileKeyword,
// WithKeyword,
// // Strict mode reserved words
// ImplementsKeyword,
// InterfaceKeyword,
// LetKeyword,
// PackageKeyword,
// PrivateKeyword,
// ProtectedKeyword,
// PublicKeyword,
// StaticKeyword,
// YieldKeyword,
// // TypeScript keywords
// AnyKeyword,
// BooleanKeyword,
// ConstructorKeyword,
// DeclareKeyword,
// GetKeyword,
// ModuleKeyword,
// RequireKeyword,
// NumberKeyword,
// SetKeyword,
// StringKeyword,
// // Parse tree nodes
// Missing,
// // Names
// QualifiedName,
// Signature elements
TypeParameter,
Parameter,
// // TypeMember
// Property,
// Method,
// Constructor,
// GetAccessor,
// SetAccessor,
// CallSignature,
// ConstructSignature,
// IndexSignature,
// // Type
// TypeReference,
// TypeQuery,
// TypeLiteral,
// ArrayType,
// // Expression
// ArrayLiteral,
// ObjectLiteral,
// PropertyAssignment,
// PropertyAccess,
// IndexedAccess,
// CallExpression,
// NewExpression,
// TypeAssertion,
// ParenExpression,
// FunctionExpression,
// ArrowFunction,
// PrefixOperator,
// PostfixOperator,
// BinaryExpression,
// ConditionalExpression,
// OmittedExpression,
// // Element
// Block,
// VariableStatement,
// EmptyStatement,
// ExpressionStatement,
// IfStatement,
// DoStatement,
// WhileStatement,
// ForStatement,
// ForInStatement,
// ContinueStatement,
// BreakStatement,
// ReturnStatement,
// WithStatement,
// SwitchStatement,
// CaseClause,
// DefaultClause,
// LabelledStatement,
// ThrowStatement,
// TryStatement,
// TryBlock,
// CatchBlock,
// FinallyBlock,
// DebuggerStatement,
// VariableDeclaration,
// FunctionDeclaration,
// FunctionBlock,
ClassDeclaration,
InterfaceDeclaration,
EnumDeclaration,
ModuleDeclaration,
// ModuleBlock,
ImportDeclaration,
// ExportAssignment,
// // Enum
// EnumMember,
// Top-level nodes
SourceFile,
Program,
// // Synthesized list
// SyntaxList,
// // Enum value count
// Count,
//
// // Markers
// FirstAssignment = EqualsToken,
// LastAssignment = CaretEqualsToken,
// FirstReservedWord = BreakKeyword,
// LastReservedWord = WithKeyword,
// FirstKeyword = BreakKeyword,
// LastKeyword = StringKeyword,
// FirstFutureReservedWord = ImplementsKeyword,
// LastFutureReservedWord = YieldKeyword,
// FirstTypeNode = TypeReference,
// LastTypeNode = ArrayType,
// FirstPunctuation = OpenBraceToken,
// LastPunctuation = CaretEqualsToken
}
export enum NodeFlags {
Export = 0x00000001, // Declarations
Ambient = 0x00000002, // Declarations
QuestionMark = 0x00000004, // Parameter/Property/Method
Rest = 0x00000008, // Parameter
Public = 0x00000010, // Property/Method
Private = 0x00000020, // Property/Method
Static = 0x00000040, // Property/Method
MultiLine = 0x00000080, // Multi-line array or object literal
Synthetic = 0x00000100, // Synthetic node (for full fidelity)
DeclarationFile = 0x00000200, // Node<M> is a .d.ts file
// TODO
// Modifier = Export | Ambient | Public | Private | Static
}
export interface Node<M extends ReadOnly> extends TextRange<M> {
/*@ (Immutable) kind: SyntaxKind */
kind: SyntaxKind;
/*@ (Immutable) flags: bitvector32 */
flags: NodeFlags;
/*@ (Mutable) id?: number */
id?: number; // Unique id (used to look up NodeLinks)
/*@ parent?: INode */
parent?: Node<M>; // Parent node (initialized by binding)
symbol?: Symbol<M>; // Symbol declared by node (initialized by binding)
locals?: SymbolTable<M>; // Locals associated with node (initialized by binding)
nextContainer?: Node<M>; // Next container in declaration order (initialized by binding)
localSymbol?: Symbol<M>; // Local symbol declared by node (initialized by binding only for exported nodes)
}
export interface NodeArray<M extends ReadOnly, T> extends Array<M, T>, TextRange<M> { }
export interface Identifier<M extends ReadOnly> extends Node<M> {
text: string; // Text of identifier (with escapes converted to characters)
}
export interface QualifiedName<M extends ReadOnly> extends Node<M> {
// Must have same layout as PropertyAccess
left: EntityName<M>;
right: Identifier<M>;
}
export interface EntityName<M extends ReadOnly> extends Node<M> {
// Identifier, QualifiedName, or Missing
}
export interface ParsedSignature<M extends ReadOnly> {
typeParameters?: NodeArray<M, TypeParameterDeclaration<M>>;
parameters: NodeArray<M, ParameterDeclaration<M>>;
type?: TypeNode<M>;
}
export interface Declaration<M extends ReadOnly> extends Node<M> {
name?: Identifier<M>;
}
export interface TypeParameterDeclaration<M extends ReadOnly> extends Declaration<M> {
constraint?: TypeNode<M>;
}
export interface SignatureDeclaration<M extends ReadOnly> extends Declaration<M>, ParsedSignature<M> { }
export interface VariableDeclaration<M extends ReadOnly> extends Declaration<M> {
type?: TypeNode<M>;
initializer?: Expression<M>;
}
export interface PropertyDeclaration<M extends ReadOnly> extends VariableDeclaration<M> { }
export interface ParameterDeclaration<M extends ReadOnly> extends VariableDeclaration<M> { }
export interface FunctionDeclaration<M extends ReadOnly> extends Declaration<M>, ParsedSignature<M> {
body?: Node<M>; // Block or Expression
}
export interface MethodDeclaration<M extends ReadOnly> extends FunctionDeclaration<M> { }
export interface ConstructorDeclaration<M extends ReadOnly> extends FunctionDeclaration<M> { }
export interface AccessorDeclaration<M extends ReadOnly> extends FunctionDeclaration<M> { }
export interface TypeNode<M extends ReadOnly> extends Node<M> { }
export interface TypeReferenceNode<M extends ReadOnly> extends TypeNode<M> {
typeName: EntityName<M>;
typeArguments?: NodeArray<M, TypeNode<M>>;
}
export interface TypeQueryNode<M extends ReadOnly> extends TypeNode<M> {
exprName: EntityName<M>;
}
export interface TypeLiteralNode<M extends ReadOnly> extends TypeNode<M> {
members: NodeArray<M, Node<M>>;
}
export interface ArrayTypeNode<M extends ReadOnly> extends TypeNode<M> {
elementType: TypeNode<M>;
}
export interface StringLiteralTypeNode<M extends ReadOnly> extends TypeNode<M> {
text: string;
}
export interface Expression<M extends ReadOnly> extends Node<M> {
contextualType?: Type<M>; // Used to temporarily assign a contextual type during overload resolution
}
export interface UnaryExpression<M extends ReadOnly> extends Expression<M> {
operator: SyntaxKind;
operand: Expression<M>;
}
export interface BinaryExpression<M extends ReadOnly> extends Expression<M> {
left: Expression<M>;
operator: SyntaxKind;
right: Expression<M>;
}
export interface ConditionalExpression<M extends ReadOnly> extends Expression<M> {
condition: Expression<M>;
whenTrue: Expression<M>;
whenFalse: Expression<M>;
}
export interface FunctionExpression<M extends ReadOnly> extends Expression<M>, FunctionDeclaration<M> {
body: Node<M>; // Required, whereas the member inherited from FunctionDeclaration is optional
}
// The text property of a LiteralExpression stores the interpreted value of the literal in text form. For a StringLiteral
// this means quotes have been removed and escapes have been converted to actual characters. For a NumericLiteral, the
// stored value is the toString() representation of the number. For example 1, 1.00, and 1e0 are all stored as just "1".
export interface LiteralExpression<M extends ReadOnly> extends Expression<M> {
text: string;
}
export interface ParenExpression<M extends ReadOnly> extends Expression<M> {
expression: Expression<M>;
}
export interface ArrayLiteral<M extends ReadOnly> extends Expression<M> {
elements: NodeArray<M, Expression<M>>;
}
export interface ObjectLiteral<M extends ReadOnly> extends Expression<M> {
properties: NodeArray<M, Node<M>>;
}
export interface PropertyAccess<M extends ReadOnly> extends Expression<M> {
left: Expression<M>;
right: Identifier<M>;
}
export interface IndexedAccess<M extends ReadOnly> extends Expression<M> {
object: Expression<M>;
index: Expression<M>;
}
export interface CallExpression<M extends ReadOnly> extends Expression<M> {
func: Expression<M>;
typeArguments?: NodeArray<M, TypeNode<M>>;
arguments: NodeArray<M, Expression<M>>;
}
export interface NewExpression<M extends ReadOnly> extends CallExpression<M> { }
export interface TypeAssertion<M extends ReadOnly> extends Expression<M> {
type: TypeNode<M>;
operand: Expression<M>;
}
export interface Statement<M extends ReadOnly> extends Node<M> { }
export interface Block<M extends ReadOnly> extends Statement<M> {
statements: NodeArray<M, Statement<M>>;
}
export interface VariableStatement<M extends ReadOnly> extends Statement<M> {
declarations: NodeArray<M, VariableDeclaration<M>>;
}
export interface ExpressionStatement<M extends ReadOnly> extends Statement<M> {
expression: Expression<M>;
}
export interface IfStatement<M extends ReadOnly> extends Statement<M> {
expression: Expression<M>;
thenStatement: Statement<M>;
elseStatement?: Statement<M>;
}
export interface IterationStatement<M extends ReadOnly> extends Statement<M> {
statement: Statement<M>;
}
export interface DoStatement<M extends ReadOnly> extends IterationStatement<M> {
expression: Expression<M>;
}
export interface WhileStatement<M extends ReadOnly> extends IterationStatement<M> {
expression: Expression<M>;
}
export interface ForStatement<M extends ReadOnly> extends IterationStatement<M> {
declarations?: NodeArray<M, VariableDeclaration<M>>;
initializer?: Expression<M>;
condition?: Expression<M>;
iterator?: Expression<M>;
}
export interface ForInStatement<M extends ReadOnly> extends IterationStatement<M> {
declaration?: VariableDeclaration<M>;
variable?: Expression<M>;
expression: Expression<M>;
}
export interface BreakOrContinueStatement<M extends ReadOnly> extends Statement<M> {
label?: Identifier<M>;
}
export interface ReturnStatement<M extends ReadOnly> extends Statement<M> {
expression?: Expression<M>;
}
export interface WithStatement<M extends ReadOnly> extends Statement<M> {
expression: Expression<M>;
statement: Statement<M>;
}
export interface SwitchStatement<M extends ReadOnly> extends Statement<M> {
expression: Expression<M>;
clauses: NodeArray<M, CaseOrDefaultClause<M>>;
}
export interface CaseOrDefaultClause<M extends ReadOnly> extends Node<M> {
expression?: Expression<M>;
statements: NodeArray<M, Statement<M>>;
}
export interface LabelledStatement<M extends ReadOnly> extends Statement<M> {
label: Identifier<M>;
statement: Statement<M>;
}
export interface ThrowStatement<M extends ReadOnly> extends Statement<M> {
expression: Expression<M>;
}
export interface TryStatement<M extends ReadOnly> extends Statement<M> {
tryBlock: Block<M>;
catchBlock?: CatchBlock<M>;
finallyBlock?: Block<M>;
}
export interface CatchBlock<M extends ReadOnly> extends Block<M> {
variable: Identifier<M>;
}
export interface ClassDeclaration<M extends ReadOnly> extends Declaration<M> {
typeParameters?: NodeArray<M, TypeParameterDeclaration<M>>;
baseType?: TypeReferenceNode<M>;
implementedTypes?: NodeArray<M, TypeReferenceNode<M>>;
members: NodeArray<M, Node<M>>;
}
export interface InterfaceDeclaration<M extends ReadOnly> extends Declaration<M> {
typeParameters?: NodeArray<M, TypeParameterDeclaration<M>>;
baseTypes?: NodeArray<M, TypeReferenceNode<M>>;
members: NodeArray<M, Node<M>>;
}
export interface EnumMember<M extends ReadOnly> extends Declaration<M> {
initializer?: Expression<M>;
}
export interface EnumDeclaration<M extends ReadOnly> extends Declaration<M> {
members: NodeArray<M, EnumMember<M>>;
}
export interface ModuleDeclaration<M extends ReadOnly> extends Declaration<M> {
body: Node<M>; // Block or ModuleDeclaration
}
export interface ImportDeclaration<M extends ReadOnly> extends Declaration<M> {
entityName?: EntityName<M>;
externalModuleName?: LiteralExpression<M>;
}
export interface ExportAssignment<M extends ReadOnly> extends Statement<M> {
exportName: Identifier<M>;
}
export interface FileReference<M extends ReadOnly> extends TextRange<M> {
filename: string;
}
export interface Comment<M extends ReadOnly> extends TextRange<M> {
hasTrailingNewLine?: boolean;
}
export interface SourceFile<M extends ReadOnly> extends Block<M> {
filename: string;
text: string;
getLineAndCharacterFromPosition(position: number): { line: number; character: number };
getPositionFromLineAndCharacter(line: number, character: number): number;
amdDependencies: string[];
referencedFiles: Array<M, FileReference<M>>;
syntacticErrors: Array<M, Diagnostic<M>>;
semanticErrors: Array<M, Diagnostic<M>>;
hasNoDefaultLib: boolean;
externalModuleIndicator: Node<M>; // The first node that causes this file to be an external module
nodeCount: number;
identifierCount: number;
symbolCount: number;
isOpen: boolean;
version: string;
languageVersion: ScriptTarget;
identifiers: Map<M, string>;
}
export interface Program<M extends ReadOnly> {
getSourceFile(filename: string): SourceFile<M>;
getSourceFiles(): Array<M, SourceFile<M>>;
getCompilerOptions(): CompilerOptions<M>;
getCompilerHost(): CompilerHost<M>;
getDiagnostics(sourceFile?: SourceFile<M>): Array<M, Diagnostic<M>>;
getGlobalDiagnostics(): Array<M, Diagnostic<M>>;
getTypeChecker(fullTypeCheckMode: boolean): TypeChecker<M>;
getCommonSourceDirectory(): string;
}
export interface SourceMapSpan<M extends ReadOnly> {
/** Line number in the js file*/
emittedLine: number;
/** Column number in the js file */
emittedColumn: number;
/** Line number in the ts file */
sourceLine: number;
/** Column number in the ts file */
sourceColumn: number;
/** Optional name (index into names array) associated with this span */
nameIndex?: number;
/** ts file (index into sources array) associated with this span*/
sourceIndex: number;
}
export interface SourceMapData<M extends ReadOnly> {
/** Where the sourcemap file is written */
sourceMapFilePath: string;
/** source map url written in the js file */
jsSourceMappingURL: string;
/** Source map's file field - js file name*/
sourceMapFile: string;
/** Source map's sourceRoot field - location where the sources will be present if not "" */
sourceMapSourceRoot: string;
/** Source map's sources field - list of sources that can be indexed in this source map*/
sourceMapSources: string[];
/** input source file (which one can use on program to get the file)
this is one to one mapping with the sourceMapSources list*/
inputSourceFileNames: string[];
/** Source map's names field - list of names that can be indexed in this source map*/
sourceMapNames?: string[];
/** Source map's mapping field - encoded source map spans*/
sourceMapMappings: string;
/** Raw source map spans that were encoded into the sourceMapMappings*/
sourceMapDecodedMappings: Array<M, SourceMapSpan<M>>;
}
export interface EmitResult<M extends ReadOnly> {
errors: Array<M, Diagnostic<M>>;
sourceMaps: Array<M, SourceMapData<M>>; // Array of sourceMapData if compiler emitted sourcemaps
}
export interface TypeChecker<M extends ReadOnly> {
// TODO: Gradually add these
// getProgram(): Program;
// getDiagnostics(sourceFile?: SourceFile): Diagnostic[];
// getGlobalDiagnostics(): Diagnostic[];
// getNodeCount(): number;
// getIdentifierCount(): number;
// getSymbolCount(): number;
// getTypeCount(): number;
// checkProgram(): void;
// emitFiles(): EmitResult;
// getParentOfSymbol(symbol: Symbol): Symbol;
// getTypeOfSymbol(symbol: Symbol): Type;
// getPropertiesOfType(type: Type): Symbol[];
// getPropertyOfType(type: Type, propetyName: string): Symbol;
// getSignaturesOfType(type: Type, kind: SignatureKind): Signature[];
// getIndexTypeOfType(type: Type, kind: IndexKind): Type;
// getReturnTypeOfSignature(signature: Signature): Type;
// getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[];
// getSymbolInfo(node: Node): Symbol;
// getTypeOfNode(node: Node): Type;
// getApparentType(type: Type): ApparentType;
// typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string;
// symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string;
// getAugmentedPropertiesOfApparentType(type: Type): Symbol[];
// getRootSymbol(symbol: Symbol): Symbol;
// getContextualType(node: Node): Type;
}
export interface TextWriter<M extends ReadOnly> {
write(s: string): void;
writeSymbol(symbol: Symbol<M>, enclosingDeclaration?: Node<M>, meaning?: SymbolFlags): void;
writeLine(): void;
increaseIndent(): void;
decreaseIndent(): void;
getText(): string;
}
export enum TypeFormatFlags {
None = 0x00000000,
WriteArrayAsGenericType = 0x00000001, // Write Array<T> instead T[]
UseTypeOfFunction = 0x00000002, // Write typeof instead of function type literal
NoTruncation = 0x00000004, // Don't truncate typeToString result
}
export enum SymbolAccessibility {
Accessible,
NotAccessible,
CannotBeNamed
}
export interface SymbolAccessiblityResult<M extends ReadOnly> {
accessibility: SymbolAccessibility;
errorSymbolName?: string // Optional symbol name that results in error
errorModuleName?: string // If the symbol is not visible from module, module's name
aliasesToMakeVisible?: Array<M, ImportDeclaration<M>>; // aliases that need to have this symbol visible
}
export interface EmitResolver<M extends ReadOnly> {
getProgram(): Program<M>;
getLocalNameOfContainer(container: Declaration<M>): string;
getExpressionNamePrefix(node: Identifier<M>): string;
getPropertyAccessSubstitution(node: PropertyAccess<M>): string;
getExportAssignmentName(node: SourceFile<M>): string;
isReferencedImportDeclaration(node: ImportDeclaration<M>): boolean;
isTopLevelValueImportedViaEntityName(node: ImportDeclaration<M>): boolean;
getNodeCheckFlags(node: Node<M>): NodeCheckFlags;
getEnumMemberValue(node: EnumMember<M>): number;
shouldEmitDeclarations(): boolean;
isDeclarationVisible(node: Declaration<M>): boolean;
isImplementationOfOverload(node: FunctionDeclaration<M>): boolean;
writeTypeAtLocation(location: Node<M>, enclosingDeclaration: Node<M>, flags: TypeFormatFlags, writer: TextWriter<M>): void;
writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration<M>, enclosingDeclaration: Node<M>, flags: TypeFormatFlags, writer: TextWriter<M>): void;
writeSymbol(symbol: Symbol<M>, enclosingDeclaration: Node<M>, meaning: SymbolFlags, writer: TextWriter<M>): void;
isSymbolAccessible(symbol: Symbol<M>, enclosingDeclaration: Node<M>, meaning: SymbolFlags): SymbolAccessiblityResult<M>;
isImportDeclarationEntityNameReferenceDeclarationVisibile(entityName: EntityName<M>): SymbolAccessiblityResult<M>;
}
export enum SymbolFlags {
Variable = 0x00000001, // Variable or parameter
Property = 0x00000002, // Property or enum member
EnumMember = 0x00000004, // Enum member
Function = 0x00000008, // Function
Class = 0x00000010, // Class
Interface = 0x00000020, // Interface
Enum = 0x00000040, // Enum
ValueModule = 0x00000080, // Instantiated module
NamespaceModule = 0x00000100, // Uninstantiated module
TypeLiteral = 0x00000200, // Type Literal
ObjectLiteral = 0x00000400, // Object Literal
Method = 0x00000800, // Method
Constructor = 0x00001000, // Constructor
GetAccessor = 0x00002000, // Get accessor
SetAccessor = 0x00004000, // Set accessor
CallSignature = 0x00008000, // Call signature
ConstructSignature = 0x00010000, // Construct signature
IndexSignature = 0x00020000, // Index signature
TypeParameter = 0x00040000, // Type parameter
// Export markers (see comment in declareModuleMember in binder)
ExportValue = 0x00080000, // Exported value marker
ExportType = 0x00100000, // Exported type marker
ExportNamespace = 0x00200000, // Exported namespace marker
Import = 0x00400000, // Import
Instantiated = 0x00800000, // Instantiated symbol
Merged = 0x01000000, // Merged symbol (created during program binding)
Transient = 0x02000000, // Transient symbol (created during type check)
Prototype = 0x04000000, // Symbol for the prototype property (without source code representation)
// TODO
// Value = Variable | Property | EnumMember | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor,
// Type = Class | Interface | Enum | TypeLiteral | ObjectLiteral | TypeParameter,
// Namespace = ValueModule | NamespaceModule,
// Module = ValueModule | NamespaceModule,
// Accessor = GetAccessor | SetAccessor,
// Signature = CallSignature | ConstructSignature | IndexSignature,
//
// ParameterExcludes = Value,
// VariableExcludes = Value & ~Variable,
// PropertyExcludes = Value,
// EnumMemberExcludes = Value,
// FunctionExcludes = Value & ~(Function | ValueModule),
// ClassExcludes = (Value | Type) & ~ValueModule,
// InterfaceExcludes = Type & ~Interface,
// EnumExcludes = (Value | Type) & ~(Enum | ValueModule),
// ValueModuleExcludes = Value & ~(Function | Class | Enum | ValueModule),
// NamespaceModuleExcludes = 0,
// MethodExcludes = Value & ~Method,
// GetAccessorExcludes = Value & ~SetAccessor,
// SetAccessorExcludes = Value & ~GetAccessor,
// TypeParameterExcludes = Type & ~TypeParameter,
//
// // Imports collide with all other imports with the same name.
// ImportExcludes = Import,
//
// ModuleMember = Variable | Function | Class | Interface | Enum | Module | Import,
//
// ExportHasLocal = Function | Class | Enum | ValueModule,
//
// HasLocals = Function | Module | Method | Constructor | Accessor | Signature,
// HasExports = Class | Enum | Module,
// HasMembers = Class | Interface | TypeLiteral | ObjectLiteral,
//
// IsContainer = HasLocals | HasExports | HasMembers,
// PropertyOrAccessor = Property | Accessor,
// Export = ExportNamespace | ExportType | ExportValue,
}
export interface Symbol<M extends ReadOnly> {
/*@ (Immutable) flags: { v: bitvector32 | mask_symbolflags_transient v <=> extends_interface this "ts.TransientSymbol" } */
flags: SymbolFlags; // Symbol flags
name: string; // Name of symbol
/*@ (Mutable) id: number */
id?: number; // Unique id (used to look up SymbolLinks)
/*@ (Mutable) mergeId: number */
mergeId?: number; // Merge id (used to look up merged symbol)
/*@ declarations : IArray<IDeclaration> */
declarations?: Array<M, Declaration<M>>; // Declarations associated with this symbol
/*@ (Mutable) parent?: ISymbol */
parent?: Symbol<M>; // Parent symbol
members?: SymbolTable<M>; // Class, interface or literal instance members
exports?: SymbolTable<M>; // Module exports
exportSymbol?: Symbol<M>; // Exported symbol associated with this symbol
valueDeclaration?: Declaration<M> // First value declaration of the symbol
}
export interface SymbolLinks<M extends ReadOnly> {
target?: Symbol<M>; // Resolved (non-alias) target of an alias
type?: Type<M>; // Type of value symbol
declaredType?: Type<M>; // Type of class, interface, enum, or type parameter
mapper?: TypeMapper<M>; // Type mapper for instantiation alias
referenced?: boolean; // True if alias symbol has been referenced as a value
exportAssignSymbol?: Symbol<M>; // Symbol exported from external module
}
export interface TransientSymbol<M extends ReadOnly> extends Symbol<M>, SymbolLinks<M> { }
// export interface SymbolTable {
export interface SymbolTable<M extends ReadOnly> extends Map<M, Symbol<M>> {
[index: string]: Symbol<Immutable>;
}
export enum NodeCheckFlags {
TypeChecked = 0x00000001, // Node<M> has been type checked
LexicalThis = 0x00000002, // Lexical 'this' reference
CaptureThis = 0x00000004, // Lexical 'this' used in body
EmitExtends = 0x00000008, // Emit __extends
SuperInstance = 0x00000010, // Instance 'super' reference
SuperStatic = 0x00000020, // Static 'super' reference
ContextChecked = 0x00000040, // Contextual types have been assigned
}
export interface NodeLinks<M extends ReadOnly> {
resolvedType?: Type<M>; // Cached type of type node
resolvedSignature?: Signature<M>; // Cached signature of signature node or call expression
resolvedSymbol?: Symbol<M>; // Cached name resolution result
flags?: NodeCheckFlags; // Set of flags specific to Node
enumMemberValue?: number; // Constant value of enum member
/*@ (Mutable) isIllegalTypeReferenceInConstraint?: boolean */
isIllegalTypeReferenceInConstraint?: boolean; // Is type reference in constraint refers to the type parameter from the same list
isVisible?: boolean; // Is this node visible
localModuleName?: string; // Local name for module instance
}
export enum TypeFlags {
Any = 0x00000001,
String = 0x00000002,
Number = 0x00000004,
Boolean = 0x00000008,
Void = 0x00000010,
Undefined = 0x00000020,
Null = 0x00000040,
Enum = 0x00000080, // Enum type
StringLiteral = 0x00000100, // String literal type
TypeParameter = 0x00000200, // Type parameter
Class = 0x00000400, // Class
Interface = 0x00000800, // Interface
Reference = 0x00001000, // Generic type reference
Anonymous = 0x00002000, // Anonymous
FromSignature = 0x00004000, // Created for signature assignment check
//// TODO
//Intrinsic = Any | String | Number | Boolean | Void | Undefined | Null,
//StringLike = String | StringLiteral,
//NumberLike = Number | Enum,
//ObjectType = Class | Interface | Reference | Anonymous
// PV : hardcoding the result here
ObjectType = 0x00003C00,
}
// Properties common to all types
export interface Type<M extends ReadOnly> {
/*@ (Immutable) flags: { v: bitvector32 | type_flags(v,this) } */
flags: TypeFlags; // Flags
id: number; // Unique ID
/*@ (Immutable) symbol?: ISymbol */
symbol?: Symbol<M>; // Symbol associated with type (if any)
}
// Intrinsic types (TypeFlags.Intrinsic)
export interface IntrinsicType<M extends ReadOnly> extends Type<M> {
intrinsicName: string; // Name of intrinsic type
}
// String literal types (TypeFlags.StringLiteral)
export interface StringLiteralType<M extends ReadOnly> extends Type<M> {
text: string; // Text of string literal
}
// Object types (TypeFlags.ObjectType)
export interface ObjectType<M extends ReadOnly> extends Type<M> { }
export interface ApparentType<M extends ReadOnly> extends Type<M> {
// This property is not used. It is just to make the type system think ApparentType
// is a strict subtype of Type.
_apparentTypeBrand: any;
}
// Class and interface types (TypeFlags.Class and TypeFlags.Interface)
export interface InterfaceType<M extends ReadOnly> extends ObjectType<M> {
typeParameters : Array<M, TypeParameter<M>>; // Type parameters (undefined if non-generic)
baseTypes : Array<M, ObjectType<M>>; // Base types
declaredProperties : Array<M, Symbol<M>>; // Declared members
declaredCallSignatures : Array<M, Signature<M>>; // Declared call signatures
declaredConstructSignatures: Array<M, Signature<M>>; // Declared construct signatures
declaredStringIndexType : Type<M>; // Declared string index type
declaredNumberIndexType : Type<M>; // Declared numeric index type
}
// Type references (TypeFlags.Reference)
export interface TypeReference<M extends ReadOnly> extends ObjectType<M> {
target: GenericType<Immutable>; // Type reference target
/*@ (Immutable) typeArguments: IArray<IType> */
typeArguments: IArray<IType>; // Type reference type arguments
}
// Generic class and interface types
export interface GenericType<M extends ReadOnly> extends InterfaceType<M>, TypeReference<M> {
// TODO : make the Map<...> work as well
/*@ (Immutable) instantiations: (Mutable) { [x:string]: TypeReference<Immutable> } */
instantiations: Map<M, TypeReference<M>>; // Generic instantiation cache
openReferenceTargets: Array<M, GenericType<M>>; // Open type reference targets
openReferenceChecks: Map<M, boolean>; // Open type reference check cache
}
// Resolved object type
export interface ResolvedObjectType<M extends ReadOnly> extends ObjectType<M> {
members: SymbolTable<Immutable>; // Properties by name
properties: IArray<ISymbol>; // Properties
callSignatures: IArray<ISignature>; // Call signatures of type
constructSignatures: IArray<ISignature>; // Construct signatures of type
stringIndexType: Type<M>; // String index type
numberIndexType: Type<M>; // Numeric index type
}
// Type parameters (TypeFlags.TypeParameter)
export interface TypeParameter<M extends ReadOnly> extends Type<M> {
constraint: Type<M>; // Constraint
target?: TypeParameter<M>; // Instantiation target
mapper?: TypeMapper<M>; // Instantiation mapper
}
export enum SignatureKind {
Call,
Construct,
}
export interface Signature<M extends ReadOnly> {
declaration: SignatureDeclaration<M>; // Originating declaration
typeParameters: Array<M, TypeParameter<M>>; // Type parameters (undefined if non-generic)
parameters: Array<M, Symbol<M>>; // Parameters
resolvedReturnType: Type<M>; // Resolved return type
minArgumentCount: number; // Number of non-optional parameters
hasRestParameter: boolean; // True if last parameter is rest parameter
hasStringLiterals: boolean; // True if instantiated
target?: Signature<M>; // Instantiation target
mapper?: TypeMapper<M>; // Instantiation mapper
erasedSignatureCache?: Signature<M>; // Erased version of signature (deferred)
isolatedSignatureType?: ObjectType<M>; // A manufactured type that just contains the signature for purposes of signature comparison
}
export enum IndexKind {
String,
Number,
}
export interface TypeMapper<M extends ReadOnly> {
<N extends ReadOnly>(t: Type<N>): Type<N>;
}
export interface InferenceContext<M extends ReadOnly> {
typeParameters: Array<M, TypeParameter<M>>;
inferences: Array<M, Array<M, Type<M>>>;
inferredTypes: Array<M, Type<M>>;
}
export interface DiagnosticMessage<M extends ReadOnly> {
key: string;
category: DiagnosticCategory;
code: number;
}
// A linked list of formatted diagnostic messages to be used as part of a multiline message.
// It is built from the bottom up, leaving the head to be the "main" diagnostic.
// While it seems that DiagnosticMessageChain is structurally similar to DiagnosticMessage,
// the difference is that messages are all preformatted in DMC.
export interface DiagnosticMessageChain<M extends ReadOnly> {
messageText: string;
category: DiagnosticCategory;
code: number;
next?: DiagnosticMessageChain<M>;
}
export interface Diagnostic<M extends ReadOnly> {
file: SourceFile<M>;
start: number;
length: number;
messageText: string;
category: DiagnosticCategory;
code: number;
}
export enum DiagnosticCategory {
Warning,
Error,
Message,
}
export interface CompilerOptions<M extends ReadOnly> {
charset?: string;
codepage?: number;
declaration?: boolean;
diagnostics?: boolean;
emitBOM?: boolean;
help?: boolean;
locale?: string;
mapRoot?: string;
module?: ModuleKind;
noErrorTruncation?: boolean;
noImplicitAny?: boolean;
noLib?: boolean;
noLibCheck?: boolean;
noResolve?: boolean;
out?: string;
outDir?: string;
removeComments?: boolean;
sourceMap?: boolean;
sourceRoot?: string;
target?: ScriptTarget;
version?: boolean;
watch?: boolean;
[option: string]: any;
}
export enum ModuleKind {
None,
CommonJS,
AMD,
}
export enum ScriptTarget {
ES3,
ES5,
}
export interface ParsedCommandLine<M extends ReadOnly> {
options: CompilerOptions<M>;
filenames: string[];
errors: Array<M, Diagnostic<M>>;
}
export interface CommandLineOption<M extends ReadOnly> {
name: string;
type: any; // "string", "number", "boolean", or an object literal mapping named values to actual values
shortName?: string; // A short pneumonic for convenience - for instance, 'h' can be used in place of 'help'.
description?: DiagnosticMessage<M>; // The message describing what the command line switch does
paramName?: DiagnosticMessage<M>; // The name to be used for a non-boolean option's parameter.
error?: DiagnosticMessage<M>; // The error given when the argument does not fit a customized 'type'.
}
export enum CharacterCodes {
nullCharacter = 0x00000000, // 0,
maxAsciiCharacter = 0x0000007F, // 0x7F,
// TODO
// lineFeed = 0x0A, // \n
// carriageReturn = 0x0D, // \r
// lineSeparator = 0x2028,
// paragraphSeparator = 0x2029,
// nextLine = 0x0085,
//
// // Unicode 3.0 space characters
// space = 0x0020, // " "
// nonBreakingSpace = 0x00A0, //
// enQuad = 0x2000,
// emQuad = 0x2001,
// enSpace = 0x2002,
// emSpace = 0x2003,
// threePerEmSpace = 0x2004,
// fourPerEmSpace = 0x2005,
// sixPerEmSpace = 0x2006,
// figureSpace = 0x2007,
// punctuationSpace = 0x2008,
// thinSpace = 0x2009,
// hairSpace = 0x200A,
// zeroWidthSpace = 0x200B,
// narrowNoBreakSpace = 0x202F,
// ideographicSpace = 0x3000,
// mathematicalSpace = 0x205F,
// ogham = 0x1680,
//
// _ = 0x5F,
// $ = 0x24,
//
// _0 = 0x30,
// _1 = 0x31,
// _2 = 0x32,
// _3 = 0x33,
// _4 = 0x34,
// _5 = 0x35,
// _6 = 0x36,
// _7 = 0x37,
// _8 = 0x38,
// _9 = 0x39,
//
// a = 0x61,
// b = 0x62,
// c = 0x63,
// d = 0x64,
// e = 0x65,
// f = 0x66,
// g = 0x67,
// h = 0x68,
// i = 0x69,
// j = 0x6A,
// k = 0x6B,
// l = 0x6C,
// m = 0x6D,
// n = 0x6E,
// o = 0x6F,
// p = 0x70,
// q = 0x71,
// r = 0x72,
// s = 0x73,
// t = 0x74,
// u = 0x75,
// v = 0x76,
// w = 0x77,
// x = 0x78,
// y = 0x79,
// z = 0x7A,
//
// A = 0x41,
// B = 0x42,
// C = 0x43,
// D = 0x44,
// E = 0x45,
// F = 0x46,
// G = 0x47,
// H = 0x48,
// I = 0x49,
// J = 0x4A,
// K = 0x4B,
// L = 0x4C,
// M = 0x4D,
// N = 0x4E,
// O = 0x4F,
// P = 0x50,
// Q = 0x51,
// R = 0x52,
// S = 0x53,
// T = 0x54,
// U = 0x55,
// V = 0x56,
// W = 0x57,
// X = 0x58,
// Y = 0x59,
// Z = 0x5a,
//
// ampersand = 0x26, // &
// asterisk = 0x2A, // *
// at = 0x40, // @
// backslash = 0x5C, // \
// bar = 0x7C, // |
// caret = 0x5E, // ^
// closeBrace = 0x7D, // }
// closeBracket = 0x5D, // ]
// closeParen = 0x29, // )
// colon = 0x3A, // :
// comma = 0x2C, // ,
// dot = 0x2E, // .
// doubleQuote = 0x22, // "
// equals = 0x3D, // =
// exclamation = 0x21, // !
// greaterThan = 0x3E, // >
// lessThan = 0x3C, // <
// minus = 0x2D, // -
// openBrace = 0x7B, // {
// openBracket = 0x5B, // [
// openParen = 0x28, // (
// percent = 0x25, // %
// plus = 0x2B, // +
// question = 0x3F, // ?
// semicolon = 0x3B, // ;
// singleQuote = 0x27, // '
// slash = 0x2F, // /
// tilde = 0x7E, // ~
//
// backspace = 0x08, // \b
// formFeed = 0x0C, // \f
// byteOrderMark = 0xFEFF,
// tab = 0x09, // \t
// verticalTab = 0x0B, // \v
}
export interface CancellationToken<M extends ReadOnly> {
isCancellationRequested(): boolean;
}
export interface CompilerHost<M extends ReadOnly> {
getSourceFile(filename: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile<M>;
getDefaultLibFilename(): string;
getCancellationToken? (): CancellationToken<M>;
writeFile(filename: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void;
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
}
} | the_stack |
namespace LiteMolPluginInstance {
// For the plugin CSS, look to Plugin/Skin
// There is also an icon font in assets/font -- CSS path to it is in Plugin/Skin/LiteMol-plugin.scss
// To compile the scss, refer to README.md in the root dir.
import Plugin = LiteMol.Plugin;
import Views = Plugin.Views;
import Bootstrap = LiteMol.Bootstrap;
import Entity = Bootstrap.Entity;
// everything same as before, only the namespace changed.
import Query = LiteMol.Core.Structure.Query;
// You can look at what transforms are available in Bootstrap/Entity/Transformer
// They are well described there and params are given as interfaces.
import Transformer = Bootstrap.Entity.Transformer;
import Tree = Bootstrap.Tree;
import Transform = Tree.Transform;
import LayoutRegion = Bootstrap.Components.LayoutRegion;
import CoreVis = LiteMol.Visualization;
import Visualization = Bootstrap.Visualization;
// all commands and events can be found in Bootstrap/Event folder.
// easy to follow the types and parameters in VSCode.
// you can subsribe to any command or event using <Event/Command>.getStream(plugin.context).subscribe(e => ....)
import Command = Bootstrap.Command;
import Event = Bootstrap.Event;
function addButton(name: string, action: () => void) {
let actions = document.getElementById('actions') as HTMLDivElement;
let button = document.createElement('button');
button.innerText = name;
button.onclick = action;
actions.appendChild(button);
}
function addSeparator() {
let actions = document.getElementById('actions') as HTMLDivElement;
actions.appendChild(document.createElement('hr'));
}
function addHeader(title: string) {
let actions = document.getElementById('actions') as HTMLDivElement;
let h = document.createElement('h4');
h.innerText = title;
actions.appendChild(h);
}
function addTextInput(id: string, value: string, placeholder?: string) {
let actions = document.getElementById('actions') as HTMLDivElement;
let input = document.createElement('input') as HTMLInputElement;
input.id = id;
input.type = 'text';
input.placeholder = placeholder!;
input.value = value;
actions.appendChild(input);
}
function addHoverArea(title: string, mouseEnter: () => void, mouseLeave: () => void) {
let actions = document.getElementById('actions') as HTMLDivElement;
let div = document.createElement('div') as HTMLDivElement;
div.innerText = title;
div.className = 'hover-area';
div.onmouseenter = () => {
if (plugin) mouseEnter();
}
div.onmouseleave = () => {
if (plugin) mouseLeave();
}
actions.appendChild(div);
}
let moleculeId = '1cbs';
let plugin: Plugin.Controller;
let interactivityTarget = document.getElementById('interactions')!;
function showInteraction(type: string, i: Bootstrap.Interactivity.Molecule.SelectionInfo | undefined) {
if (!i) { // can be undefined meaning "empty interaction"
interactivityTarget.innerHTML = `${type}: nothing<br/>` + interactivityTarget.innerHTML;
return;
}
// you have access to atoms, residues, chains, entities in the info object.
interactivityTarget.innerHTML = `${type}: ${i.residues[0].authName} ${i.residues[0].chain.authAsymId} ${i.residues[0].authSeqNumber}<br/>` + interactivityTarget.innerHTML;
}
// this applies the transforms we will build later
// it results a promise-like object that you can "then/catch".
function applyTransforms(actions: Tree.Transform.Source) {
return plugin.applyTransform(actions);
}
function selectNodes(what: Tree.Selector<Bootstrap.Entity.Any>) {
return plugin.context.select(what);
}
function cleanUp() {
// the themes will reset automatically, but you need to cleanup all the other stuff you've created that you dont want to persist
Command.Tree.RemoveNode.dispatch(plugin.context, 'sequence-selection');
}
addHeader('Create & Destroy');
addButton('Create Plugin', () => {
// you will want to do a browser version check here
// it will not work on IE <= 10 (no way around this, no WebGL in IE10)
// also needs ES6 Map and Set -- so check browser compatibility for that, you can try a polyfill using modernizr or something
plugin = create(document.getElementById('app')!);
let select = Event.Molecule.ModelSelect.getStream(plugin.context).subscribe(e => showInteraction('select', e.data));
// to stop listening, select.dispose();
let highlight = Event.Molecule.ModelHighlight.getStream(plugin.context).subscribe(e => showInteraction('highlight', e.data));
Command.Visual.ResetScene.getStream(plugin.context).subscribe(() => cleanUp());
Command.Visual.ResetTheme.getStream(plugin.context).subscribe(() => cleanUp());
// you can use this to view the event/command stream
//plugin.context.dispatcher.LOG_DISPATCH_STREAM = true;
});
addButton('Destroy Plugin', () => { plugin.destroy(); plugin = <any>void 0; });
addSeparator();
addHeader('Layout');
addButton('Show Controls', () => Command.Layout.SetState.dispatch(plugin.context, { hideControls: false }));
addButton('Hide Controls', () => Command.Layout.SetState.dispatch(plugin.context, { hideControls: true }));
addButton('Expand', () => Command.Layout.SetState.dispatch(plugin.context, { isExpanded: true }));
addButton('Set Background', () => Command.Layout.SetViewportOptions.dispatch(plugin.context, { clearColor: CoreVis.Color.fromRgb(255, 255, 255) }));
addSeparator();
addButton('Collapsed Controls: Portrait', () => {
let container = document.getElementById('app')! as HTMLElement;
container.className = 'app-portrait';
plugin.command(Command.Layout.SetState, { collapsedControlsLayout: Bootstrap.Components.CollapsedControlsLayout.Portrait, hideControls: false });
});
addButton('Collapsed Controls: Landscape', () => {
let container = document.getElementById('app')! as HTMLElement;
container.className = 'app-landscape';
plugin.command(Command.Layout.SetState, { collapsedControlsLayout: Bootstrap.Components.CollapsedControlsLayout.Landscape, hideControls: false });
});
addButton('Collapsed Controls: Outside (Default)', () => {
let container = document.getElementById('app')! as HTMLElement;
container.className = 'app-default';
plugin.command(Command.Layout.SetState, { collapsedControlsLayout: Bootstrap.Components.CollapsedControlsLayout.Outside, hideControls: false });
});
addSeparator();
addButton('Control Regions: Hide Left and Bottom, Sticky Right', () => {
plugin.command(Command.Layout.SetState, {
regionStates: {
[Bootstrap.Components.LayoutRegion.Left]: 'Hidden',
[Bootstrap.Components.LayoutRegion.Bottom]: 'Hidden',
[Bootstrap.Components.LayoutRegion.Right]: 'Sticky'
},
hideControls: false
});
});
addButton('Control Regions: Show All', () => {
plugin.command(Command.Layout.SetState, { regionStates: { }, hideControls: false });
});
addSeparator();
addButton('Components: Default', () => {
plugin.instance.setComponents(DefaultComponents);
});
addButton('Components: Without Log', () => {
plugin.instance.setComponents(NoLogComponents);
});
addButton('Fog Factor = 0.5', () => {
plugin.context.scene.scene.updateOptions({ fogFactor: 0.5 });
});
addButton('Fog Factor = 1.0', () => {
plugin.context.scene.scene.updateOptions({ fogFactor: 1.0 });
});
addSeparator();
addButton('Toggle "Model" sub-tree', () => {
const e = plugin.selectEntities('model')[0];
if (!e) return;
plugin.command(Bootstrap.Command.Entity.ToggleExpanded, e);
});
addSeparator()
addHeader('Basics');
addButton('Load Molecule', () => {
let id = moleculeId;
// this builds the transforms needed to create a molecule
let action = Transform.build()
.add(plugin.context.tree.root, Transformer.Data.Download, { url: `https://www.ebi.ac.uk/pdbe/static/entry/${id}_updated.cif`, type: 'String', id })
.then(Transformer.Data.ParseCif, { id }, { isBinding: true })
.then(Transformer.Molecule.CreateFromMmCif, { blockIndex: 0 }, { isBinding: true })
.then(Transformer.Molecule.CreateModel, { modelIndex: 0 }, { isBinding: false, ref: 'model' })
.then(Transformer.Molecule.CreateMacromoleculeVisual, { polymer: true, polymerRef: 'polymer-visual', het: true, water: true });
// can also add hetRef and waterRef; the refs allow us to reference the model and visual later.
applyTransforms(action)
//.then(() => nextAction())
//.catch(e => reportError(e));
});
addButton('Load Ligand', () => {
// in the ligand instance, you will want to NOT include Bootstrap.Behaviour.ShowInteractionOnSelect(5)
let ligandStyle: Visualization.Molecule.Style<Visualization.Molecule.BallsAndSticksParams> = {
type: 'BallsAndSticks',
params: { useVDW: true, vdwScaling: 0.25, bondRadius: 0.13, detail: 'Automatic' },
theme: { template: Visualization.Molecule.Default.ElementSymbolThemeTemplate, colors: Visualization.Molecule.Default.ElementSymbolThemeTemplate.colors, transparency: { alpha: 1.0 } }
}
let ambStyle: Visualization.Molecule.Style<Visualization.Molecule.BallsAndSticksParams> = {
type: 'BallsAndSticks',
params: { useVDW: false, atomRadius: 0.15, bondRadius: 0.07, detail: 'Automatic' },
theme: { template: Visualization.Molecule.Default.UniformThemeTemplate, colors: Visualization.Molecule.Default.UniformThemeTemplate.colors!.set('Uniform', { r: 0.4, g: 0.4, b: 0.4 }), transparency: { alpha: 0.75 } }
}
let ligandQ = Query.residues({ name: 'REA' }); // here you will fill in the whole info
let ambQ = Query.residues({ name: 'REA' }).ambientResidues(5); // adjust the radius
let id = '1cbs:REA'
let url = `https://cs.litemol.org/1cbs/ligandInteraction?name=REA`; // here you will fill in the full server etc ...
let action = Transform.build()
.add(plugin.context.tree.root, Transformer.Data.Download, { url, type: 'String', id })
.then(Transformer.Data.ParseCif, { id }, { isBinding: true })
.then(Transformer.Molecule.CreateFromMmCif, { blockIndex: 0 }, { isBinding: true })
.then(Transformer.Molecule.CreateModel, { modelIndex: 0 }, { isBinding: false, ref: 'ligand-model' });
action.then(Transformer.Molecule.CreateSelectionFromQuery, { query: ambQ, name: 'Ambience' }, { isBinding: true })
.then(Transformer.Molecule.CreateVisual, { style: ambStyle });
action.then(Transformer.Molecule.CreateSelectionFromQuery, { query: ligandQ, name: 'Ligand' }, { isBinding: true })
.then(Transformer.Molecule.CreateVisual, { style: ligandStyle }, { ref: 'ligand-visual' });
applyTransforms(action)
.then(() => {
// we select the ligand to display the density around it if it's loaded
Command.Molecule.CreateSelectInteraction.dispatch(plugin.context, { entity: selectNodes('ligand-visual')[0], query: Query.everything() })
});
//.catch(e => reportError(e));
});
addButton('Load Density', () => {
let id = moleculeId;
// this builds the transforms needed to create a molecule
let action = Transform.build()
.add(plugin.context.tree.root, LiteMol.Viewer.PDBe.Data.DownloadDensity, { id }, { ref: 'density' })
applyTransforms(action);
});
addButton('Toggle Density', () => {
let density = selectNodes('density')[0];
if (!density) return;
Command.Entity.SetVisibility.dispatch(plugin.context, { entity: density, visible: density.state.visibility === Bootstrap.Entity.Visibility.None });
});
function createSelectionTheme(color: CoreVis.Color) {
// for more options also see Bootstrap/Visualization/Molecule/Theme
let colors = LiteMol.Core.Utils.FastMap.create<string, CoreVis.Color>();
colors.set('Uniform', CoreVis.Color.fromHex(0xffffff));
colors.set('Selection', color);
colors.set('Highlight', CoreVis.Theme.Default.HighlightColor);
return Visualization.Molecule.uniformThemeProvider(<any>void 0, { colors });
}
addButton('Select, Extract, Focus', () => {
let visual = selectNodes('polymer-visual')[0] as any;
if (!visual) return;
let query = Query.sequence('1', 'A', { seqNumber: 10 }, { seqNumber: 25 });
let theme = createSelectionTheme(CoreVis.Color.fromHex(0x123456));
let action = Transform.build()
.add(visual, Transformer.Molecule.CreateSelectionFromQuery, { query, name: 'My name' }, { ref: 'sequence-selection' })
// here you can create a custom style using code similar to what's in 'Load Ligand'
.then(Transformer.Molecule.CreateVisual, { style: Visualization.Molecule.Default.ForType.get('BallsAndSticks') });
applyTransforms(action).then(() => {
Command.Visual.UpdateBasicTheme.dispatch(plugin.context, { visual, theme });
Command.Entity.Focus.dispatch(plugin.context, selectNodes('sequence-selection'))
// alternatively, you can do this
//Command.Molecule.FocusQuery.dispatch(plugin.context, { model: selectNodes('model')[0] as any, query })
});
});
addButton('Color Sequences', () => {
let model = plugin.selectEntities('model')[0] as Bootstrap.Entity.Molecule.Model;
if (!model) return;
const coloring: CustomTheme.ColorDefinition = {
base: { r: 255, g: 255, b: 255 },
entries: [
{ entity_id: '1', struct_asym_id: 'A', start_residue_number: 10, end_residue_number: 25, color: { r: 255, g: 128, b: 64 } },
{ entity_id: '1', struct_asym_id: 'A', start_residue_number: 40, end_residue_number: 60, color: { r: 64, g: 128, b: 255 } }
]
}
const theme = CustomTheme.createTheme(model.props.model, coloring);
// instead of "polymer-visual", "model" or any valid ref can be used: all "child" visuals will be colored.
CustomTheme.applyTheme(plugin, 'polymer-visual', theme);
});
addButton('Focus Query', () => {
let model = selectNodes('model')[0] as any;
if (!model) return;
let query = Query.sequence('1', 'A', { seqNumber: 10 }, { seqNumber: 25 });
Command.Molecule.FocusQuery.dispatch(plugin.context, { model, query });
});
addButton('Color Chains', () => {
let visual = selectNodes('polymer-visual')[0] as any;
let model = selectNodes('model')[0] as any;
if (!model || !visual) return;
let colors = new Map<string, CoreVis.Color>();
colors.set('A', CoreVis.Color.fromRgb(125, 169, 12));
// etc.
let theme = Visualization.Molecule.createColorMapThemeProvider(
// here you can also use m.atoms.residueIndex, m.residues.name/.... etc.
// you can also get more creative and use "composite properties"
// for this check Bootstrap/Visualization/Theme.ts and Visualization/Base/Theme.ts and it should be clear hwo to do that.
//
// You can create "validation based" coloring using this approach as it is not implemented in the plugin for now.
m => ({ index: m.data.atoms.chainIndex, property: m.data.chains.asymId }),
colors,
// this a fallback color used for elements not in the set
CoreVis.Color.fromRgb(0, 0, 123))
// apply it to the model, you can also specify props, check Bootstrap/Visualization/Theme.ts
(model);
Command.Visual.UpdateBasicTheme.dispatch(plugin.context, { visual, theme });
// if you also want to color the ligands and waters, you have to safe references to them and do it manually.
});
addButton('Highlight On', () => {
let model = selectNodes('model')[0] as any;
if (!model) return;
let query = Query.sequence('1', 'A', { seqNumber: 10 }, { seqNumber: 25 });
Command.Molecule.Highlight.dispatch(plugin.context, { model, query, isOn: true });
});
addButton('Highlight Off', () => {
let model = selectNodes('model')[0] as any;
if (!model) return;
let query = Query.sequence('1', 'A', { seqNumber: 10 }, { seqNumber: 25 });
Command.Molecule.Highlight.dispatch(plugin.context, { model, query, isOn: false });
});
addButton('Reset Theme, Sel, Highlight', () => {
Command.Visual.ResetTheme.dispatch(plugin.context, void 0);
cleanUp();
});
import AQ = Query.Algebraic;
addButton('Algebraic Query', () => {
let model = selectNodes('model')[0] as any;
if (!model) return;
//let query = AQ.query(AQ.sidechain);
let query = AQ.query(AQ.equal(AQ.residueName, AQ.value('ALA')));
let action = Transform.build()
.add(model, Transformer.Molecule.CreateSelectionFromQuery, { query, name: 'Alg. query' }, { ref: 'alg-selection' })
.then(Transformer.Molecule.CreateVisual, { style: Visualization.Molecule.Default.ForType.get('BallsAndSticks') });
applyTransforms(action);
});
addSeparator();
addHeader('Multiple Models');
addTextInput('models-pdbid', '1grm', '4 letter PDB id...');
addButton('Clear, Download, and Parse', () => {
let id = (((document.getElementById('models-pdbid') as HTMLInputElement).value) || '').trim().toLowerCase();
if (id.length !== 4) {
console.log('id must be a 4 letter string.');
return;
}
Bootstrap.Command.Tree.RemoveNode.dispatch(plugin.context, plugin.context.tree.root);
// this builds the transforms needed to create a molecule
let action = Transform.build()
.add(plugin.context.tree.root, Transformer.Data.Download, { url: `https://www.ebi.ac.uk/pdbe/static/entry/${id}_updated.cif`, type: <'String'>'String', id })
.then(Transformer.Molecule.CreateFromData, { format: LiteMol.Core.Formats.Molecule.SupportedFormats.mmCIF }, { ref: 'molecule' })
//.then(Transformer.Molecule.CreateModel, { modelIndex: 0 }, { isBinding: false, ref: 'model' })
//.then(Transformer.Molecule.CreateMacromoleculeVisual, { polymer: true, polymerRef: 'polymer-visual', het: true, water: true });
// can also add hetRef and waterRef; the refs allow us to reference the model and visual later.
applyTransforms(action)
//.then(() => nextAction())
//.catch(e => reportError(e));
});
addButton('Create All Models', () => {
// this function can be called 'automatically' in applyTransforms(action).then(....) from 'Clear, Download, and Parse';
let molecule = plugin.context.select('molecule' /* accessed by ref created in 'Clear, Download, and Parse' */)[0] as Bootstrap.Entity.Molecule.Molecule;
if (!molecule) {
console.log('Molecule not loaded.');
return;
}
let count = molecule.props.molecule.models.length;
let action = Transform.build();
let colors = Bootstrap.Immutable.Map<string, LiteMol.Visualization.Color>()
.set('Selection', LiteMol.Visualization.Theme.Default.SelectionColor)
.set('Highlight', LiteMol.Visualization.Theme.Default.HighlightColor);
for (let i = 0; i < count; i++) {
// More styles in Bootstrap/Visualization/Molecule/Styles.ts
let style: Bootstrap.Visualization.Molecule.Style<Bootstrap.Visualization.Molecule.DetailParams> = {
type: 'Cartoons',
params: { detail: 'Automatic' },
theme: {
template: Bootstrap.Visualization.Molecule.Default.UniformThemeTemplate,
colors: colors.set('Uniform', LiteMol.Visualization.Molecule.Colors.DefaultPallete[i]),
transparency: { }
}
};
action
.add(molecule, Transformer.Molecule.CreateModel, { modelIndex: i }, { isBinding: false, ref: 'model-' + i })
.then(Transformer.Molecule.CreateVisual, { style }, { ref: 'model-visual-' + i });
}
applyTransforms(action);
});
addButton('Toggle Model 2 Visibility', () => {
let entity = plugin.context.select('model-1' /* indexed from 0 */)[0];
if (!entity) return;
Bootstrap.Command.Entity.SetVisibility.dispatch(plugin.context, { entity, visible: entity.state.visibility === Bootstrap.Entity.Visibility.Full ? false : true} );
});
addHoverArea('Hover to Highlight Model 1', () => {
Bootstrap.Command.Entity.Highlight.dispatch(plugin.context, { entities: plugin.context.select('model-visual-0' /* indexed from 0 */), isOn: true });
}, () => {
Bootstrap.Command.Entity.Highlight.dispatch(plugin.context, { entities: plugin.context.select('model-visual-0' /* indexed from 0 */), isOn: false });
});
const DefaultComponents = [
Plugin.Components.Visualization.HighlightInfo(LayoutRegion.Main, true),
Plugin.Components.Entity.Current('LiteMol', Plugin.VERSION.number)(LayoutRegion.Right, true),
Plugin.Components.Transform.View(LayoutRegion.Right),
Plugin.Components.Context.Log(LayoutRegion.Bottom, true),
Plugin.Components.Context.Overlay(LayoutRegion.Root),
Plugin.Components.Context.Toast(LayoutRegion.Main, true),
Plugin.Components.Context.BackgroundTasks(LayoutRegion.Main, true)
];
const NoLogComponents = [
Plugin.Components.Visualization.HighlightInfo(LayoutRegion.Main, true),
Plugin.Components.Entity.Current('LiteMol', Plugin.VERSION.number)(LayoutRegion.Right, true),
Plugin.Components.Transform.View(LayoutRegion.Right),
Plugin.Components.Context.Overlay(LayoutRegion.Root),
Plugin.Components.Context.Toast(LayoutRegion.Main, true),
Plugin.Components.Context.BackgroundTasks(LayoutRegion.Main, true)
];
export function create(target: HTMLElement) {
let customSpecification: Plugin.Specification = {
settings: {
// currently these are all the 'global' settings available
'molecule.model.defaultQuery': `residues({ name: 'ALA' })`,
'molecule.model.defaultAssemblyName': '1',
'molecule.coordinateStreaming.defaultId': '1jj2',
'molecule.coordinateStreaming.defaultServer': 'https://cs.litemol.org/',
'molecule.coordinateStreaming.defaultRadius': 10,
'density.defaultVisualBehaviourRadius': 5
},
transforms: [
// These are the controls that are available in the UI. Removing any of them wont break anything, but the user
// be able to create a particular thing if he deletes something.
{ transformer: LiteMol.Viewer.DataSources.DownloadMolecule, view: Views.Transform.Data.WithUrlIdField },
{ transformer: Transformer.Molecule.OpenMoleculeFromFile, view: Views.Transform.Molecule.OpenFile },
{ transformer: Transformer.Data.Download, view: Views.Transform.Data.Download },
{ transformer: Transformer.Data.OpenFile, view: Views.Transform.Data.OpenFile },
// this uses the custom view defined in the CustomTransformView.tsx
//{ transformer: Transformer.Molecule.CoordinateStreaming.InitStreaming, view: Views.Transform.Molecule.InitCoordinateStreaming },
{ transformer: Transformer.Molecule.CoordinateStreaming.InitStreaming, view: LiteMol.Example.CoordianteStreamingCustomView },
// Raw data transforms
{ transformer: Transformer.Data.ParseCif, view: Views.Transform.Empty },
{ transformer: Transformer.Density.ParseData, view: Views.Transform.Density.ParseData },
// Molecule(model) transforms
{ transformer: Transformer.Molecule.CreateFromMmCif, view: Views.Transform.Molecule.CreateFromMmCif },
{ transformer: Transformer.Molecule.CreateModel, view: Views.Transform.Molecule.CreateModel },
{ transformer: Transformer.Molecule.CreateSelection, view: Views.Transform.Molecule.CreateSelection },
{ transformer: Transformer.Molecule.CreateAssembly, view: Views.Transform.Molecule.CreateAssembly },
{ transformer: Transformer.Molecule.CreateSymmetryMates, view: Views.Transform.Molecule.CreateSymmetryMates },
{ transformer: Transformer.Molecule.CreateMacromoleculeVisual, view: Views.Transform.Empty },
{ transformer: Transformer.Molecule.CreateVisual, view: Views.Transform.Molecule.CreateVisual },
// density transforms
{ transformer: Transformer.Density.CreateVisual, view: Views.Transform.Density.CreateVisual },
{ transformer: Transformer.Density.CreateVisualBehaviour, view: Views.Transform.Density.CreateVisualBehaviour },
// Coordinate streaming
{ transformer: Transformer.Molecule.CoordinateStreaming.CreateBehaviour, view: Views.Transform.Empty },
// Validation report
{ transformer: LiteMol.Viewer.PDBe.Validation.DownloadAndCreate, view: Views.Transform.Empty },
{ transformer: LiteMol.Viewer.PDBe.Validation.ApplyTheme, view: Views.Transform.Empty }
],
behaviours: [
// you will find the source of all behaviours in the Bootstrap/Behaviour directory
// keep these 2
Bootstrap.Behaviour.SetEntityToCurrentWhenAdded,
Bootstrap.Behaviour.FocusCameraOnSelect,
// this colors the visual when a selection is created on it.
Bootstrap.Behaviour.ApplySelectionToVisual,
// you will most likely not want this as this could cause trouble
//Bootstrap.Behaviour.CreateVisualWhenModelIsAdded,
// this colors the visual when it's selected by mouse or touch
Bootstrap.Behaviour.ApplyInteractivitySelection,
// this shows what atom/residue is the pointer currently over
Bootstrap.Behaviour.Molecule.HighlightElementInfo,
// when the same element is clicked twice in a row, the selection is emptied
Bootstrap.Behaviour.UnselectElementOnRepeatedClick,
// distance to the last "clicked" element
Bootstrap.Behaviour.Molecule.DistanceToLastClickedElement,
// when somethinh is selected, this will create an "overlay visual" of the selected residue and show every other residue within 5ang
// you will not want to use this for the ligand pages, where you create the same thing this does at startup
Bootstrap.Behaviour.Molecule.ShowInteractionOnSelect(5),
// this tracks what is downloaded and some basic actions. Does not send any private data etc.
// While it is not required for any functionality, we as authors are very much interested in basic
// usage statistics of the application and would appriciate if this behaviour is used.
Bootstrap.Behaviour.GoogleAnalytics('UA-77062725-1')
],
components: DefaultComponents,
viewport: {
// dont touch this either
view: Views.Visualization.Viewport,
controlsView: Views.Visualization.ViewportControls
},
layoutView: Views.Layout, // nor this
tree: {
// or this
region: LayoutRegion.Left,
view: Views.Entity.Tree
}
}
let plugin = Plugin.create({ target, customSpecification, layoutState: { hideControls: true } });
plugin.context.logger.message(`LiteMol Plugin Commands Example ${Plugin.VERSION.number}`);
return plugin;
}
} | the_stack |
import {
combineLatest as observableCombineLatest,
concat as observableConcat,
fromEvent as observableFromEvent,
merge as observableMerge,
of as observableOf,
BehaviorSubject,
Observable,
Subject,
} from "rxjs";
import {
bufferCount,
distinctUntilChanged,
filter,
first,
map,
publishReplay,
refCount,
scan,
share,
startWith,
switchMap,
take,
takeUntil,
withLatestFrom,
} from "rxjs/operators";
import { MouseClaim } from "./interfaces/MouseClaim";
import { MousePixelDeferral } from "./interfaces/MousePixelDeferral";
import { SubscriptionHolder } from "../util/SubscriptionHolder";
type Button =
| 0
| 2;
// MouseEvent.button
const LEFT_BUTTON: Button = 0;
const RIGHT_BUTTON: Button = 2;
// MouseEvent.buttons
const BUTTONS_MAP = {
[LEFT_BUTTON]: 1,
[RIGHT_BUTTON]: 2
};
type PointerType =
| "mouse"
| "pen"
| "touch";
interface FirefoxBrowser {
InstallTrigger: undefined;
}
export class MouseService {
private _activeSubject$: BehaviorSubject<boolean>;
private _active$: Observable<boolean>;
private _domMouseDown$: Observable<PointerEvent>;
private _domMouseMove$: Observable<PointerEvent>;
private _domMouseDragStart$: Observable<PointerEvent>;
private _domMouseDrag$: Observable<PointerEvent>;
private _domMouseDragEnd$: Observable<MouseEvent | FocusEvent>;
private _documentMouseMove$: Observable<PointerEvent>;
private _documentMouseUp$: Observable<PointerEvent>;
private _mouseDown$: Observable<PointerEvent>;
private _mouseEnter$: Observable<PointerEvent>;
private _mouseMove$: Observable<PointerEvent>;
private _mouseLeave$: Observable<PointerEvent>;
private _mouseUp$: Observable<PointerEvent>;
private _mouseOut$: Observable<PointerEvent>;
private _mouseOver$: Observable<PointerEvent>;
private _contextMenu$: Observable<MouseEvent>;
private _consistentContextMenu$: Observable<MouseEvent>;
private _click$: Observable<MouseEvent>;
private _dblClick$: Observable<MouseEvent>;
private _deferPixelClaims$: Subject<MousePixelDeferral>;
private _deferPixels$: Observable<number>;
private _proximateClick$: Observable<MouseEvent>;
private _staticClick$: Observable<MouseEvent>;
private _mouseWheel$: Observable<WheelEvent>;
private _mouseDragStart$: Observable<PointerEvent>;
private _mouseDrag$: Observable<PointerEvent>;
private _mouseDragEnd$: Observable<PointerEvent | FocusEvent>;
private _mouseRightDragStart$: Observable<PointerEvent>;
private _mouseRightDrag$: Observable<PointerEvent>;
private _mouseRightDragEnd$: Observable<PointerEvent | FocusEvent>;
private _claimMouse$: Subject<MouseClaim>;
private _claimWheel$: Subject<MouseClaim>;
private _mouseOwner$: Observable<string>;
private _wheelOwner$: Observable<string>;
private _windowBlur$: Observable<FocusEvent>;
private _subscriptions: SubscriptionHolder = new SubscriptionHolder();
constructor(
container: EventTarget,
canvasContainer: EventTarget,
domContainer: EventTarget,
doc: EventTarget) {
const subs = this._subscriptions;
this._activeSubject$ = new BehaviorSubject<boolean>(false);
this._active$ = this._activeSubject$
.pipe(
distinctUntilChanged(),
publishReplay(1),
refCount());
this._claimMouse$ = new Subject<MouseClaim>();
this._claimWheel$ = new Subject<MouseClaim>();
this._deferPixelClaims$ = new Subject<MousePixelDeferral>();
this._deferPixels$ = this._deferPixelClaims$
.pipe(
scan(
(claims: { [key: string]: number }, claim: MousePixelDeferral): { [key: string]: number } => {
if (claim.deferPixels == null) {
delete claims[claim.name];
} else {
claims[claim.name] = claim.deferPixels;
}
return claims;
},
{}),
map(
(claims: { [key: string]: number }): number => {
let deferPixelMax: number = -1;
for (const key in claims) {
if (!claims.hasOwnProperty(key)) {
continue;
}
const deferPixels: number = claims[key];
if (deferPixels > deferPixelMax) {
deferPixelMax = deferPixels;
}
}
return deferPixelMax;
}),
startWith(-1),
publishReplay(1),
refCount());
subs.push(this._deferPixels$.subscribe((): void => { /* noop */ }));
this._documentMouseMove$ =
observableFromEvent<PointerEvent>(doc, "pointermove")
.pipe(filter(this._isMousePen));
this._documentMouseUp$ =
observableFromEvent<PointerEvent>(doc, "pointerup")
.pipe(filter(this._isMousePen));
this._mouseDown$ =
observableFromEvent<PointerEvent>(canvasContainer, "pointerdown")
.pipe(filter(this._isMousePen));
this._mouseEnter$ =
observableFromEvent<PointerEvent>(canvasContainer, "pointerenter")
.pipe(filter(this._isMousePen));
this._mouseLeave$ =
observableFromEvent<PointerEvent>(canvasContainer, "pointerleave")
.pipe(filter(this._isMousePen));
this._mouseMove$ =
observableFromEvent<PointerEvent>(canvasContainer, "pointermove")
.pipe(filter(this._isMousePen));
this._mouseUp$ =
observableFromEvent<PointerEvent>(canvasContainer, "pointerup")
.pipe(filter(this._isMousePen));
this._mouseOut$ =
observableFromEvent<PointerEvent>(canvasContainer, "pointerout")
.pipe(filter(this._isMousePen));
this._mouseOver$ =
observableFromEvent<PointerEvent>(canvasContainer, "pointerover")
.pipe(filter(this._isMousePen));
this._domMouseDown$ =
observableFromEvent<PointerEvent>(domContainer, "pointerdown")
.pipe(filter(this._isMousePen));
this._domMouseMove$ =
observableFromEvent<PointerEvent>(domContainer, "pointermove")
.pipe(filter(this._isMousePen));
this._click$ =
observableFromEvent<MouseEvent>(canvasContainer, "click");
this._contextMenu$ =
observableFromEvent<MouseEvent>(canvasContainer, "contextmenu");
this._windowBlur$ =
observableFromEvent<FocusEvent>(window, "blur");
this._dblClick$ = observableMerge(
observableFromEvent<MouseEvent>(container, "click"),
observableFromEvent<MouseEvent>(canvasContainer, "dblclick"))
.pipe(
bufferCount(3, 1),
filter(
(events: MouseEvent[]): boolean => {
const event1: MouseEvent = events[0];
const event2: MouseEvent = events[1];
const event3: MouseEvent = events[2];
return event1.type === "click" &&
event2.type === "click" &&
event3.type === "dblclick" &&
(<HTMLElement>event1.target).parentNode === canvasContainer &&
(<HTMLElement>event2.target).parentNode === canvasContainer;
}),
map(
(events: MouseEvent[]): MouseEvent => {
return events[2];
}),
share());
subs.push(observableMerge(
this._domMouseDown$,
this._domMouseMove$,
this._dblClick$,
this._contextMenu$)
.subscribe(
(event: MouseEvent): void => {
event.preventDefault();
}));
this._mouseWheel$ = observableMerge(
observableFromEvent<WheelEvent>(canvasContainer, "wheel"),
observableFromEvent<WheelEvent>(domContainer, "wheel"))
.pipe(share());
this._consistentContextMenu$ =
observableMerge(
this._mouseDown$,
this._mouseMove$,
this._mouseOut$,
this._mouseUp$,
this._contextMenu$)
.pipe(
bufferCount(3, 1),
filter(
(events: MouseEvent[]): boolean => {
// fire context menu on mouse up both on mac and windows
return events[0].type === "pointerdown" &&
events[1].type === "contextmenu" &&
events[2].type === "pointerup";
}),
map(
(events: MouseEvent[]): MouseEvent => {
return events[1];
}),
share());
const dragStop$ =
observableMerge(
this._windowBlur$,
this._documentMouseMove$
.pipe(
filter(
(e: PointerEvent): boolean => {
return this._buttonReleased(e, LEFT_BUTTON);
})),
this._documentMouseUp$
.pipe(
filter(
(e: PointerEvent): boolean => {
return this._mouseButton(e) === LEFT_BUTTON;
})))
.pipe(share());
const mouseDragInitiate$ =
this._createMouseDragInitiate$(
LEFT_BUTTON,
this._mouseDown$,
dragStop$,
true)
.pipe(share());
this._mouseDragStart$ =
this._createMouseDragStart$(mouseDragInitiate$)
.pipe(share());
this._mouseDrag$ =
this._createMouseDrag$(mouseDragInitiate$, dragStop$)
.pipe(share());
this._mouseDragEnd$ =
this._createMouseDragEnd$(this._mouseDragStart$, dragStop$)
.pipe(share());
const domMouseDragInitiate$ =
this._createMouseDragInitiate$(
LEFT_BUTTON,
this._domMouseDown$,
dragStop$,
false)
.pipe(share());
this._domMouseDragStart$ =
this._createMouseDragStart$(domMouseDragInitiate$)
.pipe(share());
this._domMouseDrag$ =
this._createMouseDrag$(domMouseDragInitiate$, dragStop$)
.pipe(share());
this._domMouseDragEnd$ =
this._createMouseDragEnd$(this._domMouseDragStart$, dragStop$)
.pipe(share());
const rightDragStop$ =
observableMerge(
this._windowBlur$,
this._documentMouseMove$.pipe(
filter(
(e: PointerEvent): boolean => {
return this._buttonReleased(e, RIGHT_BUTTON);
})),
this._documentMouseUp$.pipe(
filter(
(e: PointerEvent): boolean => {
return this._mouseButton(e) === RIGHT_BUTTON;
})))
.pipe(share());
const mouseRightDragInitiate$ =
this._createMouseDragInitiate$(
RIGHT_BUTTON,
this._mouseDown$,
rightDragStop$,
true)
.pipe(share());
this._mouseRightDragStart$ =
this._createMouseDragStart$(mouseRightDragInitiate$)
.pipe(share());
this._mouseRightDrag$ =
this._createMouseDrag$(mouseRightDragInitiate$, rightDragStop$)
.pipe(share());
this._mouseRightDragEnd$ =
this._createMouseDragEnd$(this._mouseRightDragStart$, rightDragStop$)
.pipe(share());
this._proximateClick$ = this._mouseDown$
.pipe(
switchMap(
(mouseDown: PointerEvent): Observable<MouseEvent> => {
return this._click$.pipe(
takeUntil(this._createDeferredMouseMove$(mouseDown, this._documentMouseMove$)),
take(1));
}),
share());
this._staticClick$ = this._mouseDown$
.pipe(
switchMap(
(): Observable<MouseEvent> => {
return this._click$.pipe(
takeUntil(this._documentMouseMove$),
take(1));
}),
share());
subs.push(this._mouseDragStart$.subscribe());
subs.push(this._mouseDrag$.subscribe());
subs.push(this._mouseDragEnd$.subscribe());
subs.push(this._domMouseDragStart$.subscribe());
subs.push(this._domMouseDrag$.subscribe());
subs.push(this._domMouseDragEnd$.subscribe());
subs.push(this._mouseRightDragStart$.subscribe());
subs.push(this._mouseRightDrag$.subscribe());
subs.push(this._mouseRightDragEnd$.subscribe());
subs.push(this._staticClick$.subscribe());
this._mouseOwner$ = this._createOwner$(this._claimMouse$)
.pipe(
publishReplay(1),
refCount());
this._wheelOwner$ = this._createOwner$(this._claimWheel$)
.pipe(
publishReplay(1),
refCount());
subs.push(this._mouseOwner$.subscribe(() => { /* noop */ }));
subs.push(this._wheelOwner$.subscribe(() => { /* noop */ }));
}
public get active$(): Observable<boolean> {
return this._active$;
}
public get activate$(): Subject<boolean> {
return this._activeSubject$;
}
public get documentMouseMove$(): Observable<MouseEvent> {
return this._documentMouseMove$;
}
public get documentMouseUp$(): Observable<MouseEvent> {
return this._documentMouseUp$;
}
public get domMouseDragStart$(): Observable<MouseEvent> {
return this._domMouseDragStart$;
}
public get domMouseDrag$(): Observable<MouseEvent> {
return this._domMouseDrag$;
}
public get domMouseDragEnd$(): Observable<MouseEvent | FocusEvent> {
return this._domMouseDragEnd$;
}
public get domMouseDown$(): Observable<MouseEvent> {
return this._domMouseDown$;
}
public get domMouseMove$(): Observable<MouseEvent> {
return this._domMouseMove$;
}
public get mouseOwner$(): Observable<string> {
return this._mouseOwner$;
}
public get mouseDown$(): Observable<MouseEvent> {
return this._mouseDown$;
}
public get mouseEnter$(): Observable<MouseEvent> {
return this._mouseEnter$;
}
public get mouseMove$(): Observable<MouseEvent> {
return this._mouseMove$;
}
public get mouseLeave$(): Observable<MouseEvent> {
return this._mouseLeave$;
}
public get mouseOut$(): Observable<MouseEvent> {
return this._mouseOut$;
}
public get mouseOver$(): Observable<MouseEvent> {
return this._mouseOver$;
}
public get mouseUp$(): Observable<MouseEvent> {
return this._mouseUp$;
}
public get click$(): Observable<MouseEvent> {
return this._click$;
}
public get dblClick$(): Observable<MouseEvent> {
return this._dblClick$;
}
public get contextMenu$(): Observable<MouseEvent> {
return this._consistentContextMenu$;
}
public get mouseWheel$(): Observable<WheelEvent> {
return this._mouseWheel$;
}
public get mouseDragStart$(): Observable<MouseEvent> {
return this._mouseDragStart$;
}
public get mouseDrag$(): Observable<MouseEvent> {
return this._mouseDrag$;
}
public get mouseDragEnd$(): Observable<MouseEvent | FocusEvent> {
return this._mouseDragEnd$;
}
public get mouseRightDragStart$(): Observable<MouseEvent> {
return this._mouseRightDragStart$;
}
public get mouseRightDrag$(): Observable<MouseEvent> {
return this._mouseRightDrag$;
}
public get mouseRightDragEnd$(): Observable<MouseEvent | FocusEvent> {
return this._mouseRightDragEnd$;
}
public get proximateClick$(): Observable<MouseEvent> {
return this._proximateClick$;
}
public get staticClick$(): Observable<MouseEvent> {
return this._staticClick$;
}
public get windowBlur$(): Observable<FocusEvent> {
return this._windowBlur$;
}
public dispose(): void {
this._subscriptions.unsubscribe();
}
public claimMouse(name: string, zindex: number): void {
this._claimMouse$.next({ name: name, zindex: zindex });
}
public unclaimMouse(name: string): void {
this._claimMouse$.next({ name: name, zindex: null });
}
public deferPixels(name: string, deferPixels: number): void {
this._deferPixelClaims$.next({ name: name, deferPixels: deferPixels });
}
public undeferPixels(name: string): void {
this._deferPixelClaims$.next({ name: name, deferPixels: null });
}
public claimWheel(name: string, zindex: number): void {
this._claimWheel$.next({ name: name, zindex: zindex });
}
public unclaimWheel(name: string): void {
this._claimWheel$.next({ name: name, zindex: null });
}
public filtered$<T>(name: string, observable$: Observable<T>): Observable<T> {
return this._filtered(name, observable$, this._mouseOwner$);
}
public filteredWheel$<T>(name: string, observable$: Observable<T>): Observable<T> {
return this._filtered(name, observable$, this._wheelOwner$);
}
private _createDeferredMouseMove$(
origin: PointerEvent,
mouseMove$: Observable<PointerEvent>): Observable<PointerEvent> {
return mouseMove$.pipe(
map(
(mouseMove: PointerEvent): [PointerEvent, number] => {
const deltaX: number = mouseMove.clientX - origin.clientX;
const deltaY: number = mouseMove.clientY - origin.clientY;
return [mouseMove, Math.sqrt(deltaX * deltaX + deltaY * deltaY)];
}),
withLatestFrom(this._deferPixels$),
filter(
([[, delta], deferPixels]: [[PointerEvent, number], number]): boolean => {
return delta > deferPixels;
}),
map(
([[mouseMove]]: [[PointerEvent, number], number]): PointerEvent => {
return mouseMove;
}));
}
private _createMouseDrag$(
mouseDragStartInitiate$: Observable<[PointerEvent, PointerEvent]>,
stop$: Observable<Event>): Observable<PointerEvent> {
return mouseDragStartInitiate$.pipe(
map(
([, mouseMove]: [PointerEvent, PointerEvent]): PointerEvent => {
return mouseMove;
}),
switchMap(
(mouseMove: PointerEvent): Observable<PointerEvent> => {
return observableConcat(
observableOf(mouseMove),
this._documentMouseMove$).pipe(
takeUntil(stop$));
}));
}
private _createMouseDragEnd$<T>(mouseDragStart$: Observable<PointerEvent>, stop$: Observable<T>): Observable<T> {
return mouseDragStart$.pipe(
switchMap(
(): Observable<T> => {
return stop$.pipe(first());
}));
}
private _createMouseDragStart$(mouseDragStartInitiate$: Observable<[PointerEvent, PointerEvent]>): Observable<PointerEvent> {
return mouseDragStartInitiate$.pipe(
map(
([mouseDown]: [PointerEvent, PointerEvent]): PointerEvent => {
return mouseDown;
}));
}
private _createMouseDragInitiate$(
button: number,
mouseDown$: Observable<PointerEvent>,
stop$: Observable<Event>,
defer: boolean): Observable<[PointerEvent, PointerEvent]> {
return mouseDown$.pipe(
filter(
(mouseDown: PointerEvent): boolean => {
return this._mouseButton(mouseDown) === button;
}),
switchMap(
(mouseDown: PointerEvent): Observable<[PointerEvent, PointerEvent]> => {
return observableCombineLatest(
observableOf(mouseDown),
defer ?
this._createDeferredMouseMove$(mouseDown, this._documentMouseMove$) :
this._documentMouseMove$).pipe(
takeUntil(stop$),
take(1));
}));
}
private _createOwner$(claim$: Observable<MouseClaim>): Observable<string> {
return claim$.pipe(
scan(
(claims: { [key: string]: number }, claim: MouseClaim): { [key: string]: number } => {
if (claim.zindex == null) {
delete claims[claim.name];
} else {
claims[claim.name] = claim.zindex;
}
return claims;
},
{}),
map(
(claims: { [key: string]: number }): string => {
let owner: string = null;
let zIndexMax: number = -1;
for (const name in claims) {
if (!claims.hasOwnProperty(name)) {
continue;
}
if (claims[name] > zIndexMax) {
zIndexMax = claims[name];
owner = name;
}
}
return owner;
}),
startWith(null));
}
private _filtered<T>(
name: string,
observable$: Observable<T>,
owner$: Observable<string>): Observable<T> {
return observable$.pipe(
withLatestFrom(owner$),
filter(
([, owner]: [T, string]): boolean => {
return owner === name;
}),
map(
([item]: [T, string]): T => {
return item;
}));
}
private _mouseButton(event: PointerEvent): number {
const upOrDown = event.type === "pointerdown" || event.type === "pointerup";
const InstallTrigger = (<FirefoxBrowser><unknown>window).InstallTrigger;
if (upOrDown &&
typeof InstallTrigger !== 'undefined' &&
event.button === RIGHT_BUTTON && event.ctrlKey &&
window.navigator.platform.toUpperCase().indexOf('MAC') >= 0) {
// Fix for the fact that Firefox (detected by InstallTrigger)
// on Mac determines e.button = 2 when using Control + left click.
return LEFT_BUTTON;
}
return event.button;
}
private _buttonReleased(event: PointerEvent, button: Button): boolean {
// Right button `mouseup` is not fired in
// Chrome on Mac outside the window or iframe. If
// the button is no longer pressed during move
// it may have been released and drag stop
// should be emitted.
const flag = BUTTONS_MAP[button];
return event.buttons === undefined || (event.buttons & flag) !== flag;
}
private _isMousePen(event: PointerEvent): boolean {
const type = <PointerType>event.pointerType;
return type === "mouse" || type === "pen";
}
} | the_stack |
import { HDateTime } from './HDateTime'
import { HDate } from './HDate'
import { HStr } from './HStr'
import { ZincReader } from './ZincReader'
import { valueIsKind } from './HVal'
import { Kind } from './Kind'
import { HaysonDate, HaysonDateTime } from './hayson'
/**
* Relative span mode.
*/
export enum SpanMode {
today = 'today',
yesterday = 'yesterday',
thisWeek = 'thisWeek',
lastWeek = 'lastWeek',
thisMonth = 'thisMonth',
lastMonth = 'lastMonth',
thisQuarter = 'thisQuarter',
lastQuarter = 'lastQuarter',
thisYear = 'thisYear',
lastYear = 'lastYear',
}
/**
* The arguments for a relative span.
*/
export interface RelativeSpan {
mode: SpanMode
timezone?: string
}
function isRelativeSpan(args: unknown): args is RelativeSpan {
return !!(args as RelativeSpan)?.mode
}
/**
* The arguments for a single date span.
*/
export interface SingleDateSpan {
start: HDate
timezone?: string
}
/**
* The arguments for a double date span.
*/
export interface DoubleDateSpan {
start: HDate
end: HDate
timezone?: string
}
/**
* The arguments for a double date time span.
*/
export interface DoubleDateTimeSpan {
start: HDateTime
end: HDateTime
timezone?: string
}
/**
* A JSON encoded Span.
*/
export interface SpanJsonData {
mode?: SpanMode
start?: HaysonDate | HaysonDateTime
end?: HaysonDate | HaysonDateTime
timezone?: string
}
/**
* Models a range of time using an inclusive starting timestamp and exclusive ending timestamp.
*
* Please note, due to the lack of date time support in vanilla JavaScript, this implementation relies
* on using a third party library with proper timezone and locale support. See {@link HSpan.toLuxonInterval}
* and {@link HSpan.toMomentRange}.
*/
export class HSpan {
/**
* The relative mode. If undefined the span is absolute.
*/
public readonly mode?: SpanMode
/**
* Inclusive starting time.
*/
public readonly start?: HDateTime | HDate
/**
* Exclusive ending time.
*/
public readonly end?: HDateTime | HDate
/**
* The timezone to use.
*/
public readonly timezone: string
/**
* Construct a new span.
*
* @param options.mode The span mode.
* @param options.start The starting date or date time.
* @param options.end The ending date or date time.
* @param options.timezone Optional timezone identifier.
*/
public constructor(
args:
| RelativeSpan
| SingleDateSpan
| DoubleDateSpan
| DoubleDateTimeSpan
) {
this.timezone = args.timezone ?? ''
if (isRelativeSpan(args)) {
this.mode = args.mode
} else {
this.start = (args as
| SingleDateSpan
| DoubleDateSpan
| DoubleDateTimeSpan).start
this.end = (args as DoubleDateSpan | DoubleDateTimeSpan).end
}
}
/**
* Create a span from a encoded string or undefined if it can't be decoded.
*
* Decode from string format:
* - relative `SpanMode` mode name
* - absolute single date: 'YYYY-MM-DD'
* - absolute date span: 'YYYY-MM-DD,YYYY-MM-DD'
* - absolute date time span: 'YYYY-MM-DDThh:mm:ss.FFF zzzz,YYYY-MM-DDThh:mm:ss.FFF zzzz'
*
* @param str The string to decode.
* @returns The decoded span or undefined.
*/
public static fromStr(str: string): HSpan | undefined {
const mode = SpanMode[str as SpanMode]
if (mode) {
return new HSpan({ mode })
}
// Parse single or double dates.
const [, start, end] = /^([^,]+)(?:,([^,]+))?$/.exec(str) ?? []
// Absolute single date: 'YYYY-MM-DD'.
if (start && !end) {
const startVal = ZincReader.readValue(start)
if (valueIsKind<HDate>(startVal, Kind.Date)) {
return new HSpan({
start: startVal,
})
}
}
// Absolute date span: 'YYYY-MM-DD,YYYY-MM-DD' or
// absolute date time span: 'YYYY-MM-DDThh:mm:ss.FFF zzzz,YYYY-MM-DDThh:mm:ss.FFF zzzz'
if (start && end) {
const startVal = ZincReader.readValue(start)
const endVal = ZincReader.readValue(end)
if (
valueIsKind<HDate>(startVal, Kind.Date) &&
valueIsKind<HDate>(endVal, Kind.Date)
) {
return new HSpan({
start: startVal,
end: endVal,
})
}
if (
valueIsKind<HDateTime>(startVal, Kind.DateTime) &&
valueIsKind<HDateTime>(endVal, Kind.DateTime)
) {
return new HSpan({
start: startVal,
end: endVal,
})
}
}
return undefined
}
/**
* @returns Encodes the span as a string value.
*/
public toString(): string {
if (this.isRelative()) {
return this.mode as string
}
if (this.start && !this.end) {
return this.start.toZinc()
}
return `${this.start?.toZinc()},${this.end?.toZinc()}`
}
/**
* @returns an Axon representation of this span.
*/
public toAxon(): string {
return `toSpan(${HStr.make(this.toString()).toAxon()})`
}
/**
* @returns A JSON representation of a span.
*/
public toJSON(): SpanJsonData {
const data: SpanJsonData = {}
if (this.isRelative()) {
data.mode = this.mode
} else {
if (this.start) {
data.start = this.start.toJSON()
}
if (this.end) {
data.end = this.end.toJSON()
}
}
return data
}
/**
* @returns True if the span is relative.
*/
public isRelative(): boolean {
return !!this.mode
}
/**
* Convert the span to a [Luxon](https://moment.github.io/luxon/index.html) interval.
*
* The `haystack-core` has zero runtime dependencies and supports web, node and deno environments.
* However vanilla JavaScript lacks support for various calendar functions required to
* make `HSpan` useful.
*
* Warning: at the time of writing, the first day of the week does not vary between locales with Luxon.
*
* ```typescript
* import { DateTime, Interval } from 'luxon'
*
* ...
* const interval = new HSpan({ mode: SpanMode.today })
* .toLuxonInterval({ DateTime, Interval })
* ```
*
* @link [Luxon](https://moment.github.io/luxon/index.html)
*
* @param options.DateTime The luxon DateTime class.
* @param options.Interval The luxon Interval class.
* @returns A luxon interval.
*/
public toLuxonInterval<IntervalType>(
{
DateTime,
Interval,
}: {
DateTime: any
Interval: {
fromDateTimes(start: any, end: any): IntervalType
}
},
_now?: Date
): IntervalType {
const isValidTimeZone = (timezone: string): boolean =>
!!DateTime.now().setZone(timezone).isValid
const getTimeZone = (timezone: string): string =>
HDateTime.getIANATimeZone(timezone, isValidTimeZone) || 'local'
if (this.isRelative()) {
const now = DateTime.fromJSDate(_now ?? new Date(), {
zone: getTimeZone(this.timezone),
})
switch (this.mode) {
case SpanMode.today:
return Interval.fromDateTimes(
now.startOf('day'),
now.endOf('day')
)
case SpanMode.yesterday:
const yesterday = now.minus({ days: 1 })
return Interval.fromDateTimes(
yesterday.startOf('day'),
yesterday.endOf('day')
)
case SpanMode.thisWeek:
return Interval.fromDateTimes(
now.startOf('week'),
now.endOf('week')
)
case SpanMode.lastWeek:
const lastWeek = now.minus({ week: 1 })
return Interval.fromDateTimes(
lastWeek.startOf('week'),
lastWeek.endOf('week')
)
case SpanMode.thisMonth:
return Interval.fromDateTimes(
now.startOf('month'),
now.endOf('month')
)
case SpanMode.lastMonth:
const lastMonth = now.minus({ month: 1 })
return Interval.fromDateTimes(
lastMonth.startOf('month'),
lastMonth.endOf('month')
)
case SpanMode.thisQuarter:
return Interval.fromDateTimes(
now.startOf('quarter'),
now.endOf('quarter')
)
case SpanMode.lastQuarter:
const lastQuarter = now.minus({ quarter: 1 })
return Interval.fromDateTimes(
lastQuarter.startOf('quarter'),
lastQuarter.endOf('quarter')
)
case SpanMode.thisYear:
return Interval.fromDateTimes(
now.startOf('year'),
now.endOf('year')
)
case SpanMode.lastYear:
const lastYear = now.minus({ year: 1 })
return Interval.fromDateTimes(
lastYear.startOf('year'),
lastYear.endOf('year')
)
default:
throw new Error(`Invalid relative span ${this.mode}`)
}
} else {
if (valueIsKind<HDate>(this.start, Kind.Date) && !this.end) {
const start = DateTime.fromJSDate(this.start.date, {
zone: this.timezone,
})
return Interval.fromDateTimes(
start.startOf('day'),
start.endOf('day')
)
} else if (this.start && this.end) {
const start = valueIsKind<HDate>(this.start, Kind.Date)
? DateTime.fromJSDate(this.start.date, {
zone: getTimeZone(this.timezone),
}).startOf('day')
: DateTime.fromJSDate(this.start.date, {
zone: getTimeZone(
this.start.timezone || this.timezone
),
})
const end = valueIsKind<HDate>(this.end, Kind.Date)
? DateTime.fromJSDate(this.end.date, {
zone: getTimeZone(this.timezone),
}).endOf('day')
: DateTime.fromJSDate(this.end.date, {
zone: getTimeZone(
this.end.timezone || this.timezone
),
})
return Interval.fromDateTimes(start, end)
} else {
throw new Error('Invalid absolute span')
}
}
}
/**
* Convert the span to a moment range.
*
* ```typescript
* import * as Moment from 'moment-timezone'
* import { extendMoment } from 'moment-range'
* const moment = extendMoment(Moment)
* ...
* const range = new HSpan({ mode: SpanMode.today })
* .toMomentRange(moment)
* ```
*
* @link [Moment with timezones](https://momentjs.com/timezone/docs/)
* @link [Moment range](https://github.com/rotaready/moment-range)
*/
toMomentRange<MomentType>(
moment: () => MomentType,
_now?: Date
): MomentType {
const _moment = moment as any
const isValidTimeZone = (timezone: string): boolean =>
!!_moment.tz.zone(timezone)
const getTimeZone = (timezone: string): string =>
HDateTime.getIANATimeZone(timezone, isValidTimeZone) ||
_moment.tz.guess()
const now = _moment(_now ?? new Date()).tz(getTimeZone(this.timezone))
if (this.isRelative()) {
switch (this.mode) {
case SpanMode.today:
return _moment.range(
now.clone().startOf('day'),
now.clone().endOf('day')
)
case SpanMode.yesterday:
return _moment.range(
now.clone().subtract(1, 'day').startOf('day'),
now.clone().subtract(1, 'day').endOf('day')
)
case SpanMode.thisWeek:
return _moment.range(
now.clone().startOf('week'),
now.clone().endOf('week')
)
case SpanMode.lastWeek:
return _moment.range(
now.clone().subtract(1, 'week').startOf('week'),
now.clone().subtract(1, 'week').endOf('week')
)
case SpanMode.thisMonth:
return _moment.range(
now.clone().startOf('month'),
now.clone().endOf('month')
)
case SpanMode.lastMonth:
return _moment.range(
now.clone().subtract(1, 'month').startOf('month'),
now.clone().subtract(1, 'month').endOf('month')
)
case SpanMode.thisQuarter:
return _moment.range(
now.clone().startOf('quarter'),
now.clone().endOf('quarter')
)
case SpanMode.lastQuarter:
return _moment.range(
now.clone().subtract(1, 'quarter').startOf('quarter'),
now.clone().subtract(1, 'quarter').endOf('quarter')
)
case SpanMode.thisYear:
return _moment.range(
now.clone().startOf('year'),
now.clone().endOf('year')
)
case SpanMode.lastYear:
return _moment.range(
now.clone().subtract(1, 'year').startOf('year'),
now.clone().subtract(1, 'year').endOf('year')
)
default:
throw new Error(`Invalid relative span ${this.mode}`)
}
} else {
if (valueIsKind<HDate>(this.start, Kind.Date) && !this.end) {
const start = _moment(this.start.date).tz(
getTimeZone(this.timezone)
)
return _moment.range(
start.clone().startOf('day'),
start.clone().endOf('day')
)
} else if (this.start && this.end) {
const start = valueIsKind<HDate>(this.start, Kind.Date)
? _moment(this.start.date)
.tz(getTimeZone(this.timezone))
.startOf('day')
: _moment(this.start.date).tz(
getTimeZone(this.start.timezone || this.timezone)
)
const end = valueIsKind<HDate>(this.end, Kind.Date)
? _moment(this.end.date)
.tz(getTimeZone(this.timezone))
.endOf('day')
: _moment(this.end.date).tz(
getTimeZone(this.end.timezone || this.timezone)
)
return _moment.range(start, end)
} else {
throw new Error('Invalid absolute span')
}
}
}
} | the_stack |
import {Record, Map, Range, List, Set}from "immutable";
import ColumnHeader from "./column-header";
import RowHeader from "./row-header";
import {CellPoint} from "../common";
import {CellRange} from "../common";
import {BORDER_POSITION} from "../common";
import {KeyValuePair} from "../common";
import {FreezePane} from "../common";
import Cell from "./cell";
import Scroll from "./scroll";
import Border from "./border";
import {OBJECT_TYPE} from "./object-type";
import {Sticky} from "./sticky";
const emptyCell = new Cell();
const emptyBorder = new Border();
export {
OBJECT_TYPE
};
// テーブルに参照ポイントの適用を行う
function refsApply(table: Map<string, Cell>,
prevKV: KeyValuePair<string, Cell>,
nextKV: KeyValuePair<string, Cell>) {
// 参照セルの値を更新
// 前回情報の参照ポイントを除去
prevKV.value.refs.forEach((ref) => {
if (table.has(ref)) {
const cell = table.get(ref).deleteChildId(prevKV.key);
table = table.set(ref, cell);
}
});
// 今回情報の参照ポイントを追加
nextKV.value.refs.forEach((ref) => {
if (table.has(ref)) {
const cell = table.get(ref).addChildId(nextKV.key);
table = table.set(ref, cell);
}
});
return table;
}
function childReSolve(
sheet: Sheet,
cellPoint: CellPoint | string,
doneIds?:Set<string>) {
//let sheet = this.setTable(table);
if (doneIds === null){
doneIds = <Set<string>>Set();
}
const cell = sheet.getCell(cellPoint);
//if (cell.text !== prevCell.text) {
cell.childIds.forEach(id => {
if(doneIds.contains(id)){
return;
}
const oldChildCell = sheet.table.get(id);
const newChildCell = oldChildCell.solveCalc(sheet);
if (oldChildCell.text !== newChildCell.text){
sheet = sheet.setTable(sheet.table.set(id, newChildCell));
doneIds = doneIds.add(id);
sheet = childReSolve(sheet, id, doneIds);
}
});
return sheet;
}
// JSONからテーブル情報を生成
function JsonToTable(json) {
let table = <Map<string, Cell>>Map();
if (!json) {
return table;
}
for (var key in json) {
const cell = Cell.fromJS(json[key]);
table = table.set(key, cell);
}
return table;
}
function JsonToBorders(json) {
let borders = <Map<string, Border>>Map();
if (!json) {
return borders;
}
for (var key in json) {
const border = Border.fromJS(json[key]);
borders = borders.set(key, border);
}
return borders;
}
/**
* 表示情報
*/
export class Sheet extends Record({
columnHeader: new ColumnHeader(),
rowHeader: new RowHeader(),
freezePane: null,
table: Map(),
stickies: List(),
borders: Map(),
scroll: new Scroll(),
zoom: 100,
onChangeCell: (prevCell: Cell, nextCell: Cell) => {
return nextCell;
}
}) {
columnHeader: ColumnHeader;
rowHeader: RowHeader;
table: Map<string, Cell>;
freezePane: FreezePane;
stickies: any;
borders: Map<string, Border>;
//scroll: Scroll;
zoom: number;
onChangeCell: (prev: Cell, nextCell: Cell) => Cell;
static create() {
return new Sheet();
}
// JSONから本クラスを生成
static fromJS(json) {
const sheet = new Sheet();
const zoom = Number(json.zoom) || 100;
// テーブル情報を変換
return sheet
.setTable(JsonToTable(json.cells))
.setBorders(JsonToBorders(json.borders))
.setColumnHeader(ColumnHeader.fromJS(json.columnHeader))
.setRowHeader(RowHeader.fromJS(json.rowHeader))
.setZoom(zoom)
.setFreezePane(json.freezePane);
}
private tableToMinJS() {
let json: any = {};
this.table.forEach((item, key) => {
const cell = item.toMinJS();
if (Object.keys(cell).length) {
json[key] = cell;
}
});
return json;
}
private tableToJS() {
let json: any = {};
Range(1, this.columnHeader.columnCount + 1).forEach((columnNo) => {
Range(1, this.rowHeader.rowCount + 1).forEach((rowNo) => {
const cellPoint = new CellPoint(columnNo, rowNo);
const key = cellPoint.toId();
json[key] = this.getCell(cellPoint);
});
});
return json;
}
private bordersToJS(isMin: boolean) {
let json: any = {};
this.borders.forEach((border, key) => {
const bJson = border.toMinJS();
if ((!isMin) || (Object.keys(bJson).length)) {
json[key] = bJson;
}
})
return json;
}
toMinJS() {
let json: any = {};
const addJson = (j, v, name) => {
if (!v) {
return j;
}
if (Object.keys(v).length) {
j[name] = v;
}
return j;
}
json = addJson(json, this.columnHeader.toMinJS(), "columnHeader");
json = addJson(json, this.rowHeader.toMinJS(), "rowHeader");
json = addJson(json, this.bordersToJS(true), "borders");
json = addJson(json, this.tableToMinJS(), "cells");
json = addJson(json, this.freezePane && this.freezePane.toMinJS(), "freezePane");
if (this.zoom !== 100) {
json["zoom"] = this.zoom;
}
return json;
}
// 本クラスをJSONへ変換
toJS() {
return {
columnHeader: this.columnHeader.toJS(),
rowHeader: this.rowHeader.toJS(),
borders: this.bordersToJS(false),
cells: this.tableToJS(),
zoom: this.zoom
};
}
setTable(table: Map<string, Cell>) {
return <Sheet>this.set("table", table);
}
setColumnHeader(columnHeader: ColumnHeader) {
return <Sheet>this.set("columnHeader", columnHeader);
}
setRowHeader(rowHeader: RowHeader) {
return <Sheet>this.set("rowHeader", rowHeader);
}
setZoom(zoom: number) {
return <Sheet>this.set("zoom", zoom);
}
editRowHeader(mutator: (rowHeader: RowHeader) => RowHeader) {
return <Sheet>this.set("rowHeader", mutator(this.rowHeader));
}
editColumnHeader(mutator: (columnHeader: ColumnHeader) => ColumnHeader) {
return <Sheet>this.set("columnHeader", mutator(this.columnHeader));
}
getCell(arg): Cell {
let id;
let cellPoint;
if (arguments.length === 1) {
id = (typeof arguments[0] === "string") ? arguments[0] : arguments[0].toId();
cellPoint = (typeof arguments[0] === "string") ? CellPoint.fromId(id) : arguments[0];
}
else {
cellPoint = new CellPoint(arguments[0], arguments[1]);
id = cellPoint.toId();
}
if (this.table.has(id) === false) {
return Cell.create();
}
return this.table.get(id);
}
setOnChangeCell(onChangeCell: (prev: Cell, nextCell: Cell) => Cell) {
return <Sheet>this.set("onChangeCell", onChangeCell);
}
getValueForId(id: string) {
if (this.table.has(id) === false) {
return "";
}
return this.table.get(id).value;
}
// 値のセット
setValue(cellPoint: CellPoint, value) {
const nextCell = this.getCell(cellPoint).setValue(value);
return <Sheet>this.setCell(cellPoint, nextCell);
}
setCell(arg, arg2, arg3?) {
const cellPoint = (arguments.length === 2) ? arguments[0] : new CellPoint(arguments[0], arguments[1]);
let nextCell = arguments[arguments.length - 1];
const prevCell = this.getCell(cellPoint);
nextCell = nextCell.solveCalc(this);
let cell = this.onChangeCell(prevCell, nextCell);
if (cell === prevCell) {
return this;
}
let table = emptyCell.equals(cell) ?
this.table.delete(cellPoint.toId()) :
this.table.set(cellPoint.toId(), cell);
const prevKV = {
key: cellPoint.toId(),
value: prevCell
};
const nextKV = {
key: cellPoint.toId(),
value: nextCell
};
// 参照セルの値を更新
table = refsApply(table, prevKV, nextKV);
let sheet = this.setTable(table);
if (cell.text !== prevCell.text) {
cell.childIds.forEach(id => {
const childCell = sheet.table.get(id);
sheet = sheet.setTable(sheet.table.set(id, childCell.solveCalc(sheet)));
});
}
return sheet;
}
get defaultBorder() {
return emptyBorder;
}
get scale() {
// デバイスのピクセル比を取得する
// var dpr = (window && window.devicePixelRatio) || 1;
// return this.zoom / 100 * dpr || 1;
return this.zoom / 100 || 1;
}
// 枠線取得
getBorder(cellPoint: CellPoint, borderPosition: BORDER_POSITION) {
const id = cellPoint.toId() + "-" + borderPosition;
if (this.borders.has(id) === false) {
return this.defaultBorder;
}
return this.borders.get(id);
}
setBorders(borders: Map<string, Border>);
setBorders(cellRange: CellRange, borderPosition: BORDER_POSITION, border: Border);
setBorders(a, b?: BORDER_POSITION, c?: Border) {
if (a instanceof CellRange) {
let model = <Sheet>this;
const cellRange = <CellRange>a;
cellRange.cellPoints().forEach((cellPoint) => {
model = model.setBorder(cellPoint, b, c);
})
return model;
}
return <Sheet>this.set("borders", a);
}
// 枠線設定
setBorder(cellPoint: CellPoint, borderPosition: BORDER_POSITION, border: Border) {
if (!cellPoint) {
return this;
}
if (borderPosition === BORDER_POSITION.RIGHT) {
cellPoint = cellPoint.setColumnNo(cellPoint.columnNo + 1);
borderPosition = BORDER_POSITION.LEFT;
}
if (borderPosition === BORDER_POSITION.BOTTOM) {
cellPoint = cellPoint.setRowNo(cellPoint.rowNo + 1);
borderPosition = BORDER_POSITION.TOP;
}
const id = cellPoint.toId() + "-" + borderPosition;
if (!border) {
if (this.borders.has(id)) {
return <Sheet>this.set("borders", this.borders.delete(id));
}
else {
return this;
}
}
const prevBorder = this.getBorder(cellPoint, borderPosition);
if (prevBorder.equals(border)) {
return this;
}
return <Sheet>this.set("borders", this.borders.set(id, border));
}
editBorders(cellRange: CellRange, borderPosition: BORDER_POSITION, mutator: (border: Border, cellPoint?: CellPoint) => Border) {
if (!cellRange) {
return this;
}
const left = Math.min(cellRange.cellPoint1.columnNo, cellRange.cellPoint2.columnNo);
const right = Math.max(cellRange.cellPoint1.columnNo, cellRange.cellPoint2.columnNo);
const top = Math.min(cellRange.cellPoint1.rowNo, cellRange.cellPoint2.rowNo);
const bottom = Math.max(cellRange.cellPoint1.rowNo, cellRange.cellPoint2.rowNo);
let model = <Sheet>this;
Range(left, right + 1).forEach((columnNo) => {
Range(top, bottom + 1).forEach((rowNo) => {
const cellPoint = new CellPoint(columnNo, rowNo);
const prevBorder = this.getBorder(cellPoint, borderPosition);
const nextBorder = mutator(prevBorder, cellPoint);
model = model.setBorder(cellPoint, borderPosition, nextBorder);
});
});
return model;
}
editCell(cellPoint: CellPoint, mutator: (cell: Cell) => Cell) {
const prevCell = this.getCell(cellPoint);
const nextCell = mutator(prevCell);
return this.setCell(cellPoint, nextCell);
}
// 範囲内のセルを変更する
editCells(range: CellRange, mutator: (cell: Cell, cellPoint?: CellPoint) => Cell) {
if (!range) {
return this;
}
const left = Math.min(range.cellPoint1.columnNo, range.cellPoint2.columnNo);
const right = Math.max(range.cellPoint1.columnNo, range.cellPoint2.columnNo);
const top = Math.min(range.cellPoint1.rowNo, range.cellPoint2.rowNo);
const bottom = Math.max(range.cellPoint1.rowNo, range.cellPoint2.rowNo);
let model = <Sheet>this;
Range(left, right + 1).forEach((columnNo) => {
Range(top, bottom + 1).forEach((rowNo) => {
const cellPoint = new CellPoint(columnNo, rowNo);
const prevCell = this.getCell(cellPoint);
const nextCell = mutator(prevCell, cellPoint);
model = model.setCell(cellPoint, nextCell);
});
});
return model;
}
setFreezePane(freezePane: FreezePane) {
return <Sheet>this.set("freezePane", freezePane);
}
editFreezePane(mutator: (freezePane: FreezePane) => FreezePane) {
return <Sheet>this.set("freezePane", mutator(this.freezePane));
}
mergeRange(rangeItem: CellRange) {
return this.editCells(
rangeItem, (cell) => {
return cell.setMergeRange(rangeItem);
});
}
unMergeRange(rangeItem: CellRange) {
return this.editCells(
rangeItem, (cell) => {
return cell.setMergeRange(null);
});
}
getCells(range: CellRange): Map<string, Cell> {
if (!range) {
return <Map<string, Cell>>Map();
}
const left = Math.min(range.cellPoint1.columnNo, range.cellPoint2.columnNo);
const right = Math.max(range.cellPoint1.columnNo, range.cellPoint2.columnNo);
const top = Math.min(range.cellPoint1.rowNo, range.cellPoint2.rowNo);
const bottom = Math.max(range.cellPoint1.rowNo, range.cellPoint2.rowNo);
let cells = <Map<string, Cell>>Map();
Range(left, right + 1).forEach((columnNo) => {
Range(top, bottom + 1).forEach((rowNo) => {
const cellPoint = new CellPoint(columnNo, rowNo);
cells = cells.set(
cellPoint.toId(),
this.getCell(cellPoint)
);
});
});
return cells;
}
addSticky(sticky: Sticky) {
return this.set("stickies", this.stickies.push(sticky));
}
deleteSticky(index: number) {
return this.set("stickies", this.stickies.delete(index));
}
// 範囲内のセルを設定する
setValueRange(range: CellRange, value) {
if (!range) {
return this;
}
const left = Math.min(range.cellPoint1.columnNo, range.cellPoint2.columnNo);
const right = Math.max(range.cellPoint1.columnNo, range.cellPoint2.columnNo);
const top = Math.min(range.cellPoint1.rowNo, range.cellPoint2.rowNo);
const bottom = Math.max(range.cellPoint1.rowNo, range.cellPoint2.rowNo);
let model = <Sheet>this;
Range(left, right + 1).forEach((columnNo) => {
Range(top, bottom + 1).forEach((rowNo) => {
model = model.setValue(new CellPoint(columnNo, rowNo), value);
});
});
return model;
}
/**
* 複数範囲の値を変更する
* @param {List} ranges 範囲リスト
* @param {string} value 変更値
*/
setValueRanges(ranges: List<CellRange>, value) {
if (!ranges) {
return this;
}
let model = <Sheet>this;
ranges.forEach(range => {
model = model.setValueRange(range, value);
});
return model;
}
// 絶対座標の列情報を探す(二分探索)
pointToColumnNo(pointX: number, firstIndex?: number, lastIndex?: number) {
if ((!firstIndex) && (lastIndex !== 0)) {
firstIndex = 1;
}
if ((!lastIndex) && (lastIndex !== 0)) {
lastIndex = this.columnHeader.columnCount;
}
// 上限下限が逆転してしまったら、範囲外にはもう無い
if (firstIndex > lastIndex) {
return 0;
}
// 一区画あたりのセル数(切り上げ)
const targetIndex = Math.ceil((firstIndex + lastIndex) / 2);
const cellPoint = this.columnHeader.items.get(targetIndex);
// ターゲットがもっと左側にある
if (pointX < cellPoint.left) {
return this.pointToColumnNo(pointX, firstIndex, targetIndex - 1);
}
// ターゲットがもっと右側にある
if (pointX >= cellPoint.right) {
return this.pointToColumnNo(pointX, targetIndex + 1, lastIndex);
}
// 発見
return targetIndex;
}
// Y座標から、行番号を算出する
pointToRowNo(pointY: number, firstIndex?: number, lastIndex?: number) {
if ((!firstIndex) && (lastIndex !== 0)) {
firstIndex = 1;
}
if ((!lastIndex) && (lastIndex !== 0)) {
lastIndex = this.rowHeader.rowCount;
}
// 左右が逆転してしまったら、範囲外にはもう無い
if (firstIndex > lastIndex) {
return 0;
}
// 一区画あたりのセル数(切り上げ)
const targetIndex = Math.ceil((firstIndex + lastIndex) / 2);
const cellPoint = this.rowHeader.items.get(targetIndex);
// ターゲットがもっと上側にある
if (pointY < cellPoint.top) {
return this.pointToRowNo(pointY, firstIndex, targetIndex - 1);
}
// ターゲットがもっと下側にある
if (pointY >= cellPoint.bottom) {
return this.pointToRowNo(pointY, targetIndex + 1, lastIndex);
}
// 発見
return targetIndex;
}
// 座標からセル位置を取得する
pointToTarget(pointX: number, pointY: number) {
const columnNo = this.pointToColumnNo(pointX);
const rowNo = this.pointToRowNo(pointY);
return new CellPoint(columnNo, rowNo);
}
/**
* 固定枠(上側)の高さを取得
*/
getFreezePaneTopHeight() {
const freezePane = this.freezePane;
if ((!freezePane) || (!freezePane.firstPoint)) {
return 0;
}
const max = this.rowHeader.items.get(freezePane.firstPoint.rowNo).top;
if ((!freezePane.topLeft) || (freezePane.topLeft.rowNo === 0)) {
return max - this.columnHeader.height;
}
const min = this.rowHeader.items.get(freezePane.topLeft.rowNo).top;
return max - min;
}
/**
* 固定枠(下側)の高さを取得
*/
getFreezePaneBottomHeight() {
const freezePane = this.freezePane;
if ((!freezePane) || (!freezePane.lastPoint) || (!freezePane.bottomRight)) {
return 0;
}
const min = this.rowHeader.items.get(freezePane.lastPoint.rowNo).bottom;
const max = this.rowHeader.items.get(freezePane.bottomRight.rowNo).bottom;
return max - min;
}
/**
* 固定枠(左側)の幅を取得
*/
getFreezePaneLeftWidth() {
const freezePane = this.freezePane;
if ((!freezePane) || (!freezePane.firstPoint)) {
return 0;
}
const max = this.columnHeader.items.get(freezePane.firstPoint.columnNo).left;
if ((!freezePane.topLeft) || (freezePane.topLeft.columnNo === 0)) {
return max - this.rowHeader.width;
}
const min = this.columnHeader.items.get(freezePane.topLeft.columnNo).left;
return max - min;
}
/**
* 固定枠(右側)の幅を取得
*/
getFreezePaneRightWidth() {
const freezePane = this.freezePane;
if ((!freezePane) || (!freezePane.lastPoint) || (!freezePane.bottomRight)) {
return 0;
}
const min = this.columnHeader.items.get(freezePane.lastPoint.columnNo).right;
const max = this.columnHeader.items.get(freezePane.bottomRight.columnNo).right;
return max - min;
}
}
export {
Sheet as default
} | the_stack |
import ScrollMagic from '../scrollmagic-with-ssr'
var NAMESPACE = 'debug.addIndicators'
var console = window.console || {},
//@ts-ignore
err = Function.prototype.bind.call(console.error || console.log || function() {}, console)
if (!ScrollMagic) {
err(
'(' +
NAMESPACE +
") -> ERROR: The ScrollMagic main module could not be found. Please make sure it's loaded before this plugin or use an asynchronous loader like requirejs.",
)
}
// plugin settings
var FONT_SIZE = '0.85em',
ZINDEX = '9999',
EDGE_OFFSET = 15 // minimum edge distance, added to indentation
// overall vars
var _util = ScrollMagic._util,
_autoindex = 0
ScrollMagic.Scene.extend(function() {
var Scene = this,
_indicator
//@ts-ignore
var log = function() {
if (Scene._log) {
// not available, when main source minified
Array.prototype.splice.call(arguments, 1, 0, '(' + NAMESPACE + ')', '->')
Scene._log.apply(this, arguments)
}
}
/**
* Add visual indicators for a ScrollMagic.Scene.
* @memberof! debug.addIndicators#
*
* @example
* // add basic indicators
* scene.addIndicators()
*
* // passing options
* scene.addIndicators({name: "pin scene", colorEnd: "#FFFFFF"});
*
* @param {object} [options] - An object containing one or more options for the indicators.
* @param {(string|object)} [options.parent] - A selector, DOM Object or a jQuery object that the indicators should be added to.
If undefined, the controller's container will be used.
* @param {number} [options.name=""] - This string will be displayed at the start and end indicators of the scene for identification purposes. If no name is supplied an automatic index will be used.
* @param {number} [options.indent=0] - Additional position offset for the indicators (useful, when having multiple scenes starting at the same position).
* @param {string} [options.colorStart=green] - CSS color definition for the start indicator.
* @param {string} [options.colorEnd=red] - CSS color definition for the end indicator.
* @param {string} [options.colorTrigger=blue] - CSS color definition for the trigger indicator.
*/
Scene.addIndicators = function(options) {
if (!_indicator) {
var DEFAULT_OPTIONS = {
name: '',
indent: 0,
parent: undefined,
colorStart: 'green',
colorEnd: 'red',
colorTrigger: 'blue',
}
options = _util.extend({}, DEFAULT_OPTIONS, options)
_autoindex++
_indicator = new Indicator(Scene, options)
Scene.on('add.plugin_addIndicators', _indicator.add)
Scene.on('remove.plugin_addIndicators', _indicator.remove)
Scene.on('destroy.plugin_addIndicators', Scene.removeIndicators)
// it the scene already has a controller we can start right away.
if (Scene.controller()) {
_indicator.add()
}
}
return Scene
}
/**
* Removes visual indicators from a ScrollMagic.Scene.
* @memberof! debug.addIndicators#
*
* @example
* // remove previously added indicators
* scene.removeIndicators()
*
*/
Scene.removeIndicators = function() {
if (_indicator) {
_indicator.remove()
this.off('*.plugin_addIndicators')
_indicator = undefined
}
return Scene
}
})
/*
* ----------------------------------------------------------------
* Extension for controller to store and update related indicators
* ----------------------------------------------------------------
*/
// add option to globally auto-add indicators to scenes
/**
* Every ScrollMagic.Controller instance now accepts an additional option.
* See {@link ScrollMagic.Controller} for a complete list of the standard options.
* @memberof! debug.addIndicators#
* @method new ScrollMagic.Controller(options)
* @example
* // make a controller and add indicators to all scenes attached
* var controller = new ScrollMagic.Controller({addIndicators: true});
* // this scene will automatically have indicators added to it
* new ScrollMagic.Scene()
* .addTo(controller);
*
* @param {object} [options] - Options for the Controller.
* @param {boolean} [options.addIndicators=false] - If set to `true` every scene that is added to the controller will automatically get indicators added to it.
*/
ScrollMagic.Controller.addOption('addIndicators', false)
// extend Controller
ScrollMagic.Controller.extend(function() {
var Controller = this,
_info = Controller.info(),
_container = _info.container,
_isDocument = _info.isDocument,
_vertical = _info.vertical,
_indicators = {
// container for all indicators and methods
groups: [],
}
var log = function() {
if (Controller._log) {
// not available, when main source minified
Array.prototype.splice.call(arguments, 1, 0, '(' + NAMESPACE + ')', '->')
Controller._log.apply(this, arguments)
}
}
if (Controller._indicators) {
//@ts-ignore
log(2, "WARNING: Scene already has a property '_indicators', which will be overwritten by plugin.")
}
// add indicators container
this._indicators = _indicators
/*
needed updates:
+++++++++++++++
start/end position on scene shift (handled in Indicator class)
trigger parameters on triggerHook value change (handled in Indicator class)
bounds position on container scroll or resize (to keep alignment to bottom/right)
trigger position on container resize, window resize (if container isn't document) and window scroll (if container isn't document)
*/
// event handler for when associated bounds markers need to be repositioned
var handleBoundsPositionChange = function() {
//@ts-ignore
_indicators.updateBoundsPositions()
}
// event handler for when associated trigger groups need to be repositioned
var handleTriggerPositionChange = function() {
//@ts-ignore
_indicators.updateTriggerGroupPositions()
}
_container.addEventListener('resize', handleTriggerPositionChange)
if (!_isDocument) {
window.addEventListener('resize', handleTriggerPositionChange)
window.addEventListener('scroll', handleTriggerPositionChange)
}
// update all related bounds containers
_container.addEventListener('resize', handleBoundsPositionChange)
_container.addEventListener('scroll', handleBoundsPositionChange)
// updates the position of the bounds container to aligned to the right for vertical containers and to the bottom for horizontal
this._indicators.updateBoundsPositions = function(specificIndicator) {
var // constant for all bounds
groups = specificIndicator
? [
_util.extend({}, specificIndicator.triggerGroup, {
members: [specificIndicator],
}),
] // create a group with only one element
: _indicators.groups, // use all
g = groups.length,
css = {},
paramPos = _vertical ? 'left' : 'top',
paramDimension = _vertical ? 'width' : 'height',
edge = _vertical
? _util.get.scrollLeft(_container) + _util.get.width(_container) - EDGE_OFFSET
: _util.get.scrollTop(_container) + _util.get.height(_container) - EDGE_OFFSET,
b,
triggerSize,
group
while (g--) {
// group loop
group = groups[g]
b = group.members.length
triggerSize = _util.get[paramDimension](group.element.firstChild)
while (b--) {
// indicators loop
css[paramPos] = edge - triggerSize
_util.css(group.members[b].bounds, css)
}
}
}
// updates the positions of all trigger groups attached to a controller or a specific one, if provided
this._indicators.updateTriggerGroupPositions = function(specificGroup) {
var // constant vars
groups = specificGroup ? [specificGroup] : _indicators.groups,
i = groups.length,
container = _isDocument ? document.body : _container,
containerOffset = _isDocument
? {
top: 0,
left: 0,
}
: _util.get.offset(container, true),
edge = _vertical ? _util.get.width(_container) - EDGE_OFFSET : _util.get.height(_container) - EDGE_OFFSET,
paramDimension = _vertical ? 'width' : 'height',
paramTransform = _vertical ? 'Y' : 'X'
var // changing vars
group,
elem,
pos,
elemSize,
transform
while (i--) {
group = groups[i]
elem = group.element
pos = group.triggerHook * Controller.info('size')
elemSize = _util.get[paramDimension](elem.firstChild.firstChild)
transform = pos > elemSize ? 'translate' + paramTransform + '(-100%)' : ''
_util.css(elem, {
top: containerOffset.top + (_vertical ? pos : edge - group.members[0].options.indent),
left: containerOffset.left + (_vertical ? edge - group.members[0].options.indent : pos),
})
_util.css(elem.firstChild.firstChild, {
'-ms-transform': transform,
'-webkit-transform': transform,
transform: transform,
})
}
}
// updates the label for the group to contain the name, if it only has one member
this._indicators.updateTriggerGroupLabel = function(group) {
var text = 'trigger' + (group.members.length > 1 ? '' : ' ' + group.members[0].options.name),
elem = group.element.firstChild.firstChild,
doUpdate = elem.textContent !== text
if (doUpdate) {
elem.textContent = text
if (_vertical) {
// bounds position is dependent on text length, so update
//@ts-ignore
_indicators.updateBoundsPositions()
}
}
}
// add indicators if global option is set
this.addScene = function(newScene) {
if (this._options.addIndicators && newScene instanceof ScrollMagic.Scene && newScene.controller() === Controller) {
newScene.addIndicators()
}
// call original destroy method
this.$super.addScene.apply(this, arguments)
}
// remove all previously set listeners on destroy
this.destroy = function() {
_container.removeEventListener('resize', handleTriggerPositionChange)
if (!_isDocument) {
window.removeEventListener('resize', handleTriggerPositionChange)
window.removeEventListener('scroll', handleTriggerPositionChange)
}
_container.removeEventListener('resize', handleBoundsPositionChange)
_container.removeEventListener('scroll', handleBoundsPositionChange)
// call original destroy method
this.$super.destroy.apply(this, arguments)
}
return Controller
})
/*
* ----------------------------------------------------------------
* Internal class for the construction of Indicators
* ----------------------------------------------------------------
*/
var Indicator = function(Scene, options) {
var Indicator = this,
_elemBounds = TPL.bounds(),
_elemStart = TPL.start(options.colorStart),
_elemEnd = TPL.end(options.colorEnd),
_boundsContainer = options.parent && _util.get.elements(options.parent)[0],
_vertical,
_ctrl
var log = function() {
if (Scene._log) {
// not available, when main source minified
Array.prototype.splice.call(arguments, 1, 0, '(' + NAMESPACE + ')', '->')
Scene._log.apply(this, arguments)
}
}
options.name = options.name || _autoindex
// prepare bounds elements
_elemStart.firstChild.textContent += ' ' + options.name
_elemEnd.textContent += ' ' + options.name
_elemBounds.appendChild(_elemStart)
_elemBounds.appendChild(_elemEnd)
// set public variables
Indicator.options = options
Indicator.bounds = _elemBounds
// will be set later
Indicator.triggerGroup = undefined
// add indicators to DOM
this.add = function() {
_ctrl = Scene.controller()
_vertical = _ctrl.info('vertical')
var isDocument = _ctrl.info('isDocument')
if (!_boundsContainer) {
// no parent supplied or doesnt exist
_boundsContainer = isDocument ? document.body : _ctrl.info('container') // check if window/document (then use body)
}
if (!isDocument && _util.css(_boundsContainer, 'position') === 'static') {
// position mode needed for correct positioning of indicators
_util.css(_boundsContainer, {
position: 'relative',
})
}
// add listeners for updates
Scene.on('change.plugin_addIndicators', handleTriggerParamsChange)
Scene.on('shift.plugin_addIndicators', handleBoundsParamsChange)
// updates trigger & bounds (will add elements if needed)
updateTriggerGroup()
updateBounds()
setTimeout(function() {
// do after all execution is finished otherwise sometimes size calculations are off
_ctrl._indicators.updateBoundsPositions(Indicator)
}, 0)
//@ts-ignore
log(3, 'added indicators')
}
// remove indicators from DOM
this.remove = function() {
if (Indicator.triggerGroup) {
// if not set there's nothing to remove
Scene.off('change.plugin_addIndicators', handleTriggerParamsChange)
Scene.off('shift.plugin_addIndicators', handleBoundsParamsChange)
if (Indicator.triggerGroup.members.length > 1) {
// just remove from memberlist of old group
var group = Indicator.triggerGroup
group.members.splice(group.members.indexOf(Indicator), 1)
_ctrl._indicators.updateTriggerGroupLabel(group)
_ctrl._indicators.updateTriggerGroupPositions(group)
Indicator.triggerGroup = undefined
} else {
// remove complete group
removeTriggerGroup()
}
removeBounds()
//@ts-ignore
log(3, 'removed indicators')
}
}
/*
* ----------------------------------------------------------------
* internal Event Handlers
* ----------------------------------------------------------------
*/
// event handler for when bounds params change
var handleBoundsParamsChange = function() {
updateBounds()
}
// event handler for when trigger params change
var handleTriggerParamsChange = function(e) {
if (e.what === 'triggerHook') {
updateTriggerGroup()
}
}
/*
* ----------------------------------------------------------------
* Bounds (start / stop) management
* ----------------------------------------------------------------
*/
// adds an new bounds elements to the array and to the DOM
var addBounds = function() {
var v = _ctrl.info('vertical')
// apply stuff we didn't know before...
_util.css(_elemStart.firstChild, {
'border-bottom-width': v ? 1 : 0,
'border-right-width': v ? 0 : 1,
bottom: v ? -1 : options.indent,
right: v ? options.indent : -1,
padding: v ? '0 8px' : '2px 4px',
})
_util.css(_elemEnd, {
'border-top-width': v ? 1 : 0,
'border-left-width': v ? 0 : 1,
top: v ? '100%' : '',
right: v ? options.indent : '',
bottom: v ? '' : options.indent,
left: v ? '' : '100%',
padding: v ? '0 8px' : '2px 4px',
})
// append
_boundsContainer.appendChild(_elemBounds)
}
// remove bounds from list and DOM
var removeBounds = function() {
_elemBounds.parentNode.removeChild(_elemBounds)
}
// update the start and end positions of the scene
var updateBounds = function() {
if (_elemBounds.parentNode !== _boundsContainer) {
addBounds() // Add Bounds elements (start/end)
}
var css = {}
css[_vertical ? 'top' : 'left'] = Scene.triggerPosition()
css[_vertical ? 'height' : 'width'] = Scene.duration()
_util.css(_elemBounds, css)
_util.css(_elemEnd, {
display: Scene.duration() > 0 ? '' : 'none',
})
}
/*
* ----------------------------------------------------------------
* trigger and trigger group management
* ----------------------------------------------------------------
*/
// adds an new trigger group to the array and to the DOM
var addTriggerGroup = function() {
var triggerElem = TPL.trigger(options.colorTrigger) // new trigger element
var css = {}
css[_vertical ? 'right' : 'bottom'] = 0
css[_vertical ? 'border-top-width' : 'border-left-width'] = 1
_util.css(triggerElem.firstChild, css)
_util.css(triggerElem.firstChild.firstChild, {
padding: _vertical ? '0 8px 3px 8px' : '3px 4px',
})
document.body.appendChild(triggerElem) // directly add to body
var newGroup = {
triggerHook: Scene.triggerHook(),
element: triggerElem,
members: [Indicator],
}
_ctrl._indicators.groups.push(newGroup)
Indicator.triggerGroup = newGroup
// update right away
_ctrl._indicators.updateTriggerGroupLabel(newGroup)
_ctrl._indicators.updateTriggerGroupPositions(newGroup)
}
var removeTriggerGroup = function() {
_ctrl._indicators.groups.splice(_ctrl._indicators.groups.indexOf(Indicator.triggerGroup), 1)
Indicator.triggerGroup.element.parentNode.removeChild(Indicator.triggerGroup.element)
Indicator.triggerGroup = undefined
}
// updates the trigger group -> either join existing or add new one
/*
* Logic:
* 1 if a trigger group exist, check if it's in sync with Scene settings – if so, nothing else needs to happen
* 2 try to find an existing one that matches Scene parameters
* 2.1 If a match is found check if already assigned to an existing group
* If so:
* A: it was the last member of existing group -> kill whole group
* B: the existing group has other members -> just remove from member list
* 2.2 Assign to matching group
* 3 if no new match could be found, check if assigned to existing group
* A: yes, and it's the only member -> just update parameters and positions and keep using this group
* B: yes but there are other members -> remove from member list and create a new one
* C: no, so create a new one
*/
var updateTriggerGroup = function() {
var triggerHook = Scene.triggerHook(),
closeEnough = 0.0001
// Have a group, check if it still matches
if (Indicator.triggerGroup) {
if (Math.abs(Indicator.triggerGroup.triggerHook - triggerHook) < closeEnough) {
// _util.log(0, "trigger", options.name, "->", "no need to change, still in sync");
return // all good
}
}
// Don't have a group, check if a matching one exists
// _util.log(0, "trigger", options.name, "->", "out of sync!");
var groups = _ctrl._indicators.groups,
group,
i = groups.length
while (i--) {
group = groups[i]
if (Math.abs(group.triggerHook - triggerHook) < closeEnough) {
// found a match!
// _util.log(0, "trigger", options.name, "->", "found match");
if (Indicator.triggerGroup) {
// do I have an old group that is out of sync?
if (Indicator.triggerGroup.members.length === 1) {
// is it the only remaining group?
// _util.log(0, "trigger", options.name, "->", "kill");
// was the last member, remove the whole group
removeTriggerGroup()
} else {
Indicator.triggerGroup.members.splice(Indicator.triggerGroup.members.indexOf(Indicator), 1) // just remove from memberlist of old group
_ctrl._indicators.updateTriggerGroupLabel(Indicator.triggerGroup)
_ctrl._indicators.updateTriggerGroupPositions(Indicator.triggerGroup)
// _util.log(0, "trigger", options.name, "->", "removing from previous member list");
}
}
// join new group
group.members.push(Indicator)
Indicator.triggerGroup = group
_ctrl._indicators.updateTriggerGroupLabel(group)
return
}
}
// at this point I am obviously out of sync and don't match any other group
if (Indicator.triggerGroup) {
if (Indicator.triggerGroup.members.length === 1) {
// _util.log(0, "trigger", options.name, "->", "updating existing");
// out of sync but i'm the only member => just change and update
Indicator.triggerGroup.triggerHook = triggerHook
_ctrl._indicators.updateTriggerGroupPositions(Indicator.triggerGroup)
return
} else {
// _util.log(0, "trigger", options.name, "->", "removing from previous member list");
Indicator.triggerGroup.members.splice(Indicator.triggerGroup.members.indexOf(Indicator), 1) // just remove from memberlist of old group
_ctrl._indicators.updateTriggerGroupLabel(Indicator.triggerGroup)
_ctrl._indicators.updateTriggerGroupPositions(Indicator.triggerGroup)
Indicator.triggerGroup = undefined // need a brand new group...
}
}
// _util.log(0, "trigger", options.name, "->", "add a new one");
// did not find any match, make new trigger group
addTriggerGroup()
}
}
/*
* ----------------------------------------------------------------
* Templates for the indicators
* ----------------------------------------------------------------
*/
var TPL = {
start: function(color) {
// inner element (for bottom offset -1, while keeping top position 0)
var inner = document.createElement('div')
inner.textContent = 'start'
_util.css(inner, {
position: 'absolute',
overflow: 'visible',
'border-width': 0,
'border-style': 'solid',
color: color,
'border-color': color,
})
var e = document.createElement('div')
// wrapper
_util.css(e, {
position: 'absolute',
overflow: 'visible',
width: 0,
height: 0,
})
e.appendChild(inner)
return e
},
end: function(color) {
var e = document.createElement('div')
e.textContent = 'end'
_util.css(e, {
position: 'absolute',
overflow: 'visible',
'border-width': 0,
'border-style': 'solid',
color: color,
'border-color': color,
})
return e
},
bounds: function() {
var e = document.createElement('div')
_util.css(e, {
position: 'absolute',
overflow: 'visible',
'white-space': 'nowrap',
'pointer-events': 'none',
'font-size': FONT_SIZE,
})
e.style.zIndex = ZINDEX
return e
},
trigger: function(color) {
// inner to be above or below line but keep position
var inner = document.createElement('div')
inner.textContent = 'trigger'
_util.css(inner, {
position: 'relative',
})
// inner wrapper for right: 0 and main element has no size
var w = document.createElement('div')
_util.css(w, {
position: 'absolute',
overflow: 'visible',
'border-width': 0,
'border-style': 'solid',
color: color,
'border-color': color,
})
w.appendChild(inner)
// wrapper
var e = document.createElement('div')
_util.css(e, {
position: 'fixed',
overflow: 'visible',
'white-space': 'nowrap',
'pointer-events': 'none',
'font-size': FONT_SIZE,
})
e.style.zIndex = ZINDEX
e.appendChild(w)
return e
},
} | the_stack |
import { Pos, Position, SrcFile } from './pos'
import * as utf8 from './utf8'
import * as unicode from './unicode'
import { ErrorCode, ErrorReporter, ErrorHandler } from './error'
import { token, lookupKeyword, prec } from './token'
import * as path from './path'
import { Int64 } from './int64'
import { IntParser } from './intparse'
import {
AppendBuffer,
bufcmp,
asciibuf,
asciistr,
asciistrn,
// debuglog as dlog,
} from './util'
export enum Mode {
None = 0,
ScanComments = 1, // do not skip comments; produce token.COMMENT
CopySource = 2,
// copy slices of source data for tokens with literal values instead of
// referencing the source buffer. This means slightly lower speed but
// less memory usage since when scanning is done, the source code memory
// can be reclaimed. If you plan to keep the source code around after
// scanning (common case) you should leave this disabled.
}
const linePrefix = asciibuf('//!line ')
enum istrOne { OFF, WAIT, CONT }
const decodeRes :utf8.DecodeResult = {c:0,w:0}
// Snapshot represents a point between tokens and is
// just enough data to "time travel" a scanner within the same
// source file and scan session.
//
export interface Snapshot {
tok :token
ch :int
offset :int
rdOffset :int
lineOffset :int
insertSemi :bool
parenL :int
interpStrL :int
byteval :Uint8Array|null
errorCount :int
}
// A Scanner holds the scanner's internal state while processing a given text.
// It must be initialized via init before use or resue.
//
export class Scanner extends ErrorReporter {
// immutable state (only changed by init())
// Note: `undefined as any as X` is a workaround for a TypeScript issue
// where members are otherwise not initialized at construction which causes
// duplicate struct definitions in v8.
public sfile :SrcFile = undefined as any as SrcFile // source file handle
public sdata :Uint8Array = undefined as any as Uint8Array // source data
public dir :string = '' // directory portion of file.name
public mode :Mode = 0 // scanning mode
// scanning state
public ch :int = -1 // current character (unicode; -1=EOF)
public offset :int = 0 // character offset
public rdOffset :int = 0 // reading offset (position after current char)
private lineOffset :int = 0 // current line offset
private insertSemi :bool = false // insert a semicolon before next newline
private parenL :int = 0 // parenthesis level, for string interpolation
private interpStrL :int = 0 // string interpolation level
private istrOne :istrOne = istrOne.OFF // string interpolation
private byteval :Uint8Array|null = null // value for some string tokens
private intParser = new IntParser()
// public scanning state (read-only)
public pos :Pos = 0 // token start position
public startoffs :int = 0 // token start offset
public endoffs :int = 0 // token end offset
public tok :token = token.EOF
public prec :prec = prec.LOWEST
public hash :int = 0 // hash value for current token (if NAME*)
public int32val :int = 0 // value for some tokens (char and int lits)
public int64val :Int64|null = null // value for large int tokens
public floatval :number = +0.0 // IEEE 754-2008 float
// sparse buffer state (not reset by s.init)
private appendbuf :AppendBuffer|null = null // for string literals
private snapshotFreeList :Snapshot[] = []
// public state - ok to modify
public errorCount :int = 0 // number of errors encountered
constructor(traceInDebugMode? :bool) {
super('E_SYNTAX', null, traceInDebugMode)
}
// Init prepares the scanner s to tokenize the text sdata by setting the
// scanner at the beginning of sdata. The scanner uses the file set file
// for position information and it adds line information for each line.
// It is ok to re-use the same file when re-scanning the same file as
// line information which is already present is ignored. Init causes a
// panic if the file size does not match the sdata size.
//
// Calls to Scan will invoke the error handler errh if they encounter a
// syntax error and errh is not nil. Also, for each error encountered,
// the Scanner field ErrorCount is incremented by one. The mode parameter
// determines how comments are handled.
//
// Note that Init may call errh if there is an error in the first character
// of the file.
//
init(
sfile :SrcFile,
sdata :Uint8Array,
errh? :ErrorHandler|null,
mode :Mode = Mode.None,
) {
const s = this
// Explicitly initialize all fields since a scanner may be reused
if (sfile.size != sdata.length) {
panic(
`file size (${sfile.size}) `+
`does not match source size (${sdata.length})`
)
}
s.sfile = sfile
s.dir = path.dir(sfile.name)
s.sdata = sdata
s.errh = errh || null
s.mode = mode
// reset scanner state
s.tok = token.EOF
s.ch = 0x20 /*' '*/
s.offset = 0
s.rdOffset = 0
s.lineOffset = 0
s.insertSemi = false
s.parenL = 0
s.interpStrL = 0
s.byteval = null
s.errorCount = 0
s.readchar()
}
recordSnapshot(s :Snapshot) {
s.tok = this.tok
s.ch = this.ch
s.offset = this.offset
s.rdOffset = this.rdOffset
s.lineOffset = this.lineOffset
s.insertSemi = this.insertSemi
s.parenL = this.parenL
s.interpStrL = this.interpStrL
s.byteval = this.byteval
s.errorCount = this.errorCount
}
restoreSnapshot(s :Snapshot) {
this.tok = s.tok
this.ch = s.ch
this.offset = s.offset
this.rdOffset = s.rdOffset
this.lineOffset = s.lineOffset
this.insertSemi = s.insertSemi
this.parenL = s.parenL
this.interpStrL = s.interpStrL
this.byteval = s.byteval
this.errorCount = s.errorCount
}
allocSnapshot() :Snapshot {
let s = this.snapshotFreeList.pop()
if (!s) { s = {} as Snapshot }
return s
}
freeSnapshot(s :Snapshot) {
this.snapshotFreeList.push(s)
}
// setOffset sets the read offset.
// it's only safe to call this outside of next() and readchar()
//
setOffset(offs :int) {
const s = this
s.offset = s.rdOffset = offs
}
// setEOF sets the state to EOF, as if we had scanned until the end
setEOF() {
const s = this
s.setOffset(s.sdata.length)
s.ch = -1 // eof
s.tok = token.EOF
}
// Read the next Unicode char into s.ch.
// s.ch < 0 means end-of-file.
readchar() {
const s = this
if (s.rdOffset < s.sdata.length) {
s.offset = s.rdOffset
if (s.ch == 0xA /*\n*/ ) {
s.lineOffset = s.offset
s.sfile.addLine(s.offset)
}
decodeRes.w = 1
decodeRes.c = s.sdata[s.rdOffset]
if (decodeRes.c >= 0x80) {
// uncommon case: non-ASCII character
if (!utf8.decode(s.sdata, s.rdOffset, decodeRes)) {
s.errorAtOffs('invalid UTF-8 encoding', s.offset)
} else if (decodeRes.c == 0) {
s.errorAtOffs('illegal NUL byte in input', s.offset)
}
}
s.rdOffset += decodeRes.w
s.ch = decodeRes.c
} else {
s.offset = s.sdata.length
if (s.ch == 0xA /*\n*/) {
s.lineOffset = s.offset
s.sfile.addLine(s.offset)
}
s.ch = -1 // eof
}
}
// undobyte "puts back" the last-read byte.
// note that this does NOT fully update scanner state -- after calling this
// function, you should either call readchar() to update s.ch and s.offset
// or call next().
//
undobyte() {
const s = this
assert(s.ch < 0x80)
s.rdOffset -= 1
s.offset -= 1
s.endoffs = s.offset
}
// gotchar reads the next character and returns true if s.ch == ch
private gotchar(ch :int) :bool {
const s = this
if (s.ch == ch) {
s.readchar()
return true
}
return false
}
currentPosition() :Position {
const s = this
return s.sfile.position(s.pos)
}
// byteValue returns a byte buffer representing the literal value of the
// current token.
// Note that this method returns a byte buffer that is potentially referenced
// internally and which value might change next time s.scan is called. If you
// plan to keep referencing the byte buffer, use s.takeByteValue instead.
//
byteValue() :Uint8Array {
const s = this
const end = s.endoffs == -1 ? s.offset : s.endoffs
return s.byteval || s.sdata.subarray(s.startoffs, end)
}
// takeByteValue returns a new byte buffer that is not referenced by
// the scanner.
// If Mode.CopySource is set, a mutable copy is returned, otherwise an immutable
// view on the underlying source code is returned.
//
takeByteValue() :Uint8Array {
const s = this
const b = s.byteValue()
s.byteval = null
return (this.mode & Mode.CopySource) ? b.slice() : b
}
// stringValue returns a string of the literal value of the
// current token. This is mainly a convenience method; it
// decodes the underlying buffer as UTF-8.
stringValue() :string {
return utf8.decodeToString(this.byteValue())
}
// Increment errorCount and call any error handler
//
error(msg :string, pos :Pos = this.pos, code? :ErrorCode) {
const s = this
s.errorAt(msg, s.sfile.position(pos), code)
}
errorAtOffs(msg :string, offs :int, code? :ErrorCode) {
const s = this
s.errorAt(msg, s.sfile.position(s.sfile.pos(offs)), code)
}
// Scan the next token
//
next() {
while (true) {
const s = this
if (s.istrOne == istrOne.OFF) {
// skip whitespace
while (
s.ch == 0x20 ||
s.ch == 0x9 ||
(s.ch == 0xA && !s.insertSemi) ||
s.ch == 0xD
) {
s.readchar()
}
}
// current token start
s.pos = s.sfile.pos(s.offset)
s.startoffs = s.offset
s.endoffs = -1
s.byteval = null
if (s.istrOne == istrOne.CONT) {
// continue interpolated string
s.istrOne = istrOne.OFF
s.startoffs-- // b/c scanString increments it, assuming it's skipping `"`
s.tok = s.scanString()
s.insertSemi = s.tok != token.STRING_PIECE
return
} else if (s.istrOne == istrOne.WAIT) {
// we are about to scan a single token following $ in a string template
s.istrOne = istrOne.CONT
}
// make progress
let ch = s.ch
s.readchar()
let insertSemi = false
switch (ch) {
case -1: {
s.tok = s.insertSemi ? token.SEMICOLON : token.EOF
break
}
case 0x30: case 0x31: case 0x32: case 0x33: case 0x34:
case 0x35: case 0x36: case 0x37: case 0x38: case 0x39:
// 0..9
s.scanNumber(ch, /*modch=*/0)
insertSemi = true
break
case 0xA: { // \n
// we only reach here if s.insertSemi was set in the first place
// and exited early from skipping whitespace.
// newline consumed
s.tok = token.SEMICOLON
break
}
case 0x22: // "
s.tok = s.scanString()
insertSemi = s.tok != token.STRING_PIECE
break
case 0x27: // '
s.scanChar()
insertSemi = true
break
case 0x3a: // :
if (s.gotchar(0x3D)) {
s.tok = token.SET_ASSIGN
s.prec = prec.LOWEST
} else {
s.tok = token.COLON
}
break
case 0x2e: { // .
if (
isDigit(s.ch) &&
s.tok != token.NAME &&
s.tok != token.RPAREN &&
s.tok != token.RBRACKET
) {
// Note: We check for NAME so that:
// x.1 => (selector (name x) (int 1))
// ).1 => (selector (name x) (int 1))
// ].1 => (selector (name x) (int 1))
// .1 => (float 0.1)
s.scanFloatNumber(/*seenDecimal*/true, /*modc*/0)
insertSemi = true
} else {
if (s.gotchar(0x2e)) { // ..
if (s.gotchar(0x2e)) { // ...
s.tok = token.ELLIPSIS
} else {
s.tok = token.PERIODS
}
} else {
s.tok = token.DOT
}
}
break
}
case 0x40: { // @
s.startoffs++ // skip @
let c = s.ch
if (c < utf8.UniSelf && (asciiFeats[c] & langIdentStart)) {
s.readchar()
s.scanIdentifier(c)
} else if (c >= utf8.UniSelf && isUniIdentStart(c)) {
s.readchar()
s.scanIdentifierU(c, this.startoffs)
}
s.tok = token.NAMEAT
insertSemi = true
break
}
case 0x2C: // ,
s.tok = token.COMMA
break
case 0x3B: // ;
s.tok = token.SEMICOLON
break
case 0x28: // (
if (s.interpStrL) {
s.parenL++
}
s.tok = token.LPAREN
break
case 0x29: // )
s.tok = token.RPAREN
insertSemi = true
if (s.interpStrL) {
if (s.parenL == 0) {
// continue interpolated string
s.interpStrL--
s.tok = s.scanString()
insertSemi = s.tok != token.STRING_PIECE
} else {
s.parenL--
}
}
break
case 0x5b: // [
s.tok = token.LBRACKET
break
case 0x5d: // ]
s.tok = token.RBRACKET
insertSemi = true
break
case 0x7b: // {
s.tok = token.LBRACE
break
case 0x7d: // }
s.tok = token.RBRACE
insertSemi = true
break
case 0x3f: // ?
s.tok = token.QUESTION
insertSemi = true
break
case 0x2B: { // +
s.prec = prec.LOWEST
if (s.gotchar(0x3D)) { // +=
s.tok = token.ADD_ASSIGN
} else if (s.gotchar(ch)) { // ++
s.tok = token.INC
insertSemi = true
} else if (s.ch >= 0x30 && s.ch <= 0x39) { // 0..9
ch = s.ch
s.readchar()
s.scanNumber(ch, /*modch=*/0x2B)
insertSemi = true
} else if (s.gotchar(0x2e)) { // .
s.scanFloatNumber(/*seenDecimal*/true, /*modc=*/0x2B)
insertSemi = true
} else {
s.tok = token.ADD
s.prec = prec.ADD
}
break
}
case 0x2D: { // -
s.prec = prec.LOWEST
if (s.gotchar(0x3e)) { // ->
s.tok = token.ARROWR
} else if (s.gotchar(0x3D)) { // -=
s.tok = token.SUB_ASSIGN
} else if (s.gotchar(ch)) { // --
s.tok = token.DEC
insertSemi = true
} else if (s.ch >= 0x30 && s.ch <= 0x39) { // 0..9
ch = s.ch
s.readchar()
s.scanNumber(ch, /*modc=*/0x2D)
insertSemi = true
} else if (s.gotchar(0x2e)) { // .
s.scanFloatNumber(/*seenDecimal*/true, /*modc=*/0x2D)
insertSemi = true
} else {
s.tok = token.SUB
s.prec = prec.ADD
}
break
}
case 0x2a: // *
if (s.gotchar(0x3D)) { // *=
s.tok = token.MUL_ASSIGN
s.prec = prec.LOWEST
} else {
s.tok = token.MUL
s.prec = prec.MUL
}
break
case 0x2f: { // /
if (s.ch == 0x2f) { // //
s.scanLineComment()
if (!(s.mode & Mode.ScanComments)) {
continue
}
insertSemi = s.insertSemi // persist s.insertSemi
} else if (s.ch == 0x2a) { // /*
const CRcount = s.scanGeneralComment()
if (!(s.mode & Mode.ScanComments)) {
continue
}
s.tok = token.COMMENT
if (CRcount) {
// strip CR characters from comment
const v = s.sdata.subarray(
s.startoffs,
s.endoffs == -1 ? s.offset : s.endoffs
)
s.byteval = stripByte(v, 0xD, CRcount) // copy; no mutation
}
insertSemi = s.insertSemi // persist s.insertSemi
} else {
if (s.gotchar(0x3D)) { // /=
s.tok = token.QUO_ASSIGN
s.prec = prec.LOWEST
} else {
s.tok = token.QUO
s.prec = prec.MUL
}
}
break
}
case 0x25: // %
if (s.gotchar(0x3D)) { // %=
s.tok = token.REM_ASSIGN
s.prec = prec.LOWEST
} else {
s.tok = token.REM
s.prec = prec.MUL
}
break
case 0x5e: // ^
if (s.gotchar(0x3D)) { // ^=
s.tok = token.XOR_ASSIGN
s.prec = prec.LOWEST
} else {
s.tok = token.XOR
s.prec = prec.ADD
}
break
case 0x3c: { // <
if (s.gotchar(0x2D)) { // <-
s.tok = token.ARROWL
s.prec = prec.LOWEST
} else if (s.gotchar(0x3D)) { // <=
s.tok = token.LEQ
s.prec = prec.CMP
} else if (s.gotchar(ch)) { // <<
if (s.gotchar(0x3D)) { // <<=
s.tok = token.SHL_ASSIGN
s.prec = prec.LOWEST
} else {
s.tok = token.SHL
s.prec = prec.MUL
}
} else {
s.tok = token.LSS
s.prec = prec.CMP
}
break
}
case 0x3E: // >
if (s.gotchar(0x3D)) { // >=
s.tok = token.GEQ
s.prec = prec.CMP
} else if (s.gotchar(ch)) { // >>
if (s.gotchar(0x3D)) { // >>=
s.tok = token.SHR_ASSIGN
s.prec = prec.LOWEST
} else {
s.tok = token.SHR
s.prec = prec.MUL
insertSemi = true
}
} else {
s.tok = token.GTR
s.prec = prec.CMP
insertSemi = true
}
break
case 0x3D: // =
if (s.gotchar(0x3D)) { // ==
s.tok = token.EQL
s.prec = prec.CMP
} else {
s.tok = token.ASSIGN
s.prec = prec.LOWEST
}
break
case 0x21: // !
if (s.gotchar(0x3D)) { // !=
s.tok = token.NEQ
s.prec = prec.CMP
} else {
s.tok = token.NOT
s.prec = prec.LOWEST
}
break
case 0x26: { // &
if (s.gotchar(0x5E)) { // &^
if (s.gotchar(0x3D)) { // &^=
s.tok = token.AND_NOT_ASSIGN
s.prec = prec.LOWEST
} else {
s.tok = token.AND_NOT
s.prec = prec.MUL
}
} else if (s.gotchar(0x3D)) { // &=
s.tok = token.AND_ASSIGN
s.prec = prec.LOWEST
} else if (s.gotchar(ch)) { // &&
s.tok = token.ANDAND
s.prec = prec.ANDAND
} else {
s.tok = token.AND
s.prec = prec.MUL
}
break
}
case 0x7c: // |
if (s.gotchar(0x3D)) { // |=
s.tok = token.OR_ASSIGN
s.prec = prec.LOWEST
} else if (s.gotchar(ch)) { // ||
s.tok = token.OROR
s.prec = prec.OROR
} else {
s.tok = token.OR
s.prec = prec.ADD
}
break
case 0x23: { // #
s.startoffs++ // skip #
let c = s.ch
if (c < utf8.UniSelf && (asciiFeats[c] & langIdent)) {
s.readchar()
s.scanIdentifier(c)
}
s.tok = token.DIRECTIVE
insertSemi = true
break
}
default: {
if (
(ch < utf8.UniSelf && (asciiFeats[ch] & langIdentStart)) ||
(ch >= utf8.UniSelf && isUniIdentStart(ch))
) {
if (ch < utf8.UniSelf) {
s.scanIdentifier(ch)
} else {
s.scanIdentifierU(ch, this.startoffs)
}
if (s.offset - s.startoffs > 1) {
// shortest keyword is 2
switch (s.tok = lookupKeyword(s.byteValue())) {
case token.NAME:
case token.BREAK:
case token.CONTINUE:
case token.FALLTHROUGH:
case token.RETURN:
insertSemi = true
break
}
} else {
s.tok = token.NAME
insertSemi = true
}
} else {
s.error(`unexpected character ${unicode.repr(ch)} in input`)
s.tok = token.ILLEGAL
}
break
}
} // switch (ch)
if (s.endoffs == -1) {
s.endoffs = s.offset
}
s.insertSemi = insertSemi
// dlog(
// `-> ${tokstr(s.tok)} "${utf8.decodeToString(s.byteValue())}"`)
return
} // while(true)
}
scanIdentifierU(c :int, hashOffs :int, hash :int = 0x811c9dc5) {
// Scan identifier with non-ASCII characters.
// c is already verified to be a valid indentifier character.
// Hash is calculated as a second pass at the end.
const s = this
const ZeroWidthJoiner = 0x200D
let lastCp = c
c = s.ch
while (
isUniIdentCont(c) ||
unicode.isEmojiModifier(c) ||
unicode.isEmojiModifierBase(c) ||
c == ZeroWidthJoiner
) {
if (lastCp == 0x2D && c == 0x2D) { // --
s.undobyte() // "put back" the "-" byte
break
}
lastCp = c
s.readchar()
c = s.ch
}
if (lastCp == ZeroWidthJoiner) {
s.error(`illegal zero width-joiner character at end of identifer`)
s.tok = token.ILLEGAL
return
}
// computing rest of hash
for (let i = hashOffs; i < s.offset; ++i) {
hash = (hash ^ s.sdata[i]) * 0x1000193 // fnv1a
}
s.hash = hash >>> 0
}
scanIdentifier(c :int) {
// enters past first char; c = 1st char, s.ch = 2nd char
// c is already verified to be a valid indentifier character.
// The hash function used here must exactly match what's in bytestr.
const s = this
let hash = (0x811c9dc5 ^ c) * 0x1000193 // fnv1a
c = s.ch
while (
isLetter(c) ||
isDigit(c) ||
c == 0x2D || // -
c == 0x5F || // _
c == 0x24 // $
) {
s.readchar()
if (c == 0x2D && s.ch == 0x2D) { // --
s.undobyte() // "put back" the "-" byte
break
}
hash = (hash ^ c) * 0x1000193 // fnv1a
c = s.ch
}
if (c >= utf8.UniSelf && isUniIdentCont(c)) {
return s.scanIdentifierU(c, s.offset, hash)
}
s.hash = hash >>> 0
}
scanChar() {
const s = this
let cp = -1
s.tok = token.CHAR
s.int32val = NaN
switch (s.ch) {
case -1: // EOF
s.error("unterminated character literal")
s.tok = token.ILLEGAL
return
case 0x27: // '
s.error("empty character literal or unescaped ' in character literal")
s.readchar()
s.tok = token.ILLEGAL
return
case 0x5c: // \
s.readchar()
cp = s.scanEscape(0x27) // '
// note: cp is -1 for illegal escape sequences
break
default:
cp = s.ch
if (cp < 0x20) {
s.error("invalid character literal")
s.tok = token.ILLEGAL
cp = -1
}
s.readchar()
break
}
if (s.ch == 0x27) { // '
s.readchar()
if (cp == -1) {
s.tok = token.ILLEGAL
} else {
s.int32val = cp
}
} else {
// failed -- read until EOF or '
s.tok = token.ILLEGAL
while (true) {
if (s.ch == -1) {
break
}
if (s.ch == 0x27) { // '
s.readchar() // consume '
break
}
s.readchar()
}
s.error("invalid character literal")
}
}
resetAppendBuf() :AppendBuffer {
const s = this
if (s.appendbuf) {
s.appendbuf.reset()
} else {
// we need to buffer the value since it's not a 1:1 literal
s.appendbuf = new AppendBuffer(64)
}
return s.appendbuf
}
scanString() :token {
// opening char already consumed
const s = this
let buf :AppendBuffer|null = null
s.startoffs++ // skip initial "
let chunkStart = s.startoffs
let tok = token.STRING
loop1:
while (true) {
switch (s.ch) {
case -1:
s.error("string literal not terminated")
if (buf) {
buf = null
}
break loop1
case 0x22: // "
if (buf) {
buf.write(s.sdata, chunkStart, s.offset)
}
s.readchar()
break loop1
case 0x5c: { // \
// we need to buffer the value since it's not a 1:1 literal
if (!buf) {
buf = s.resetAppendBuf()
}
if (chunkStart != s.offset) {
buf.write(s.sdata, chunkStart, s.offset)
}
s.readchar()
const ch = s.ch as int // e.g. "u", "x", etc
const n = s.scanEscape(0x22) // "
// we continue even if there was an error
if (n >= 0) {
if (n >= utf8.UniSelf && (ch == 0x75 || ch == 0x55)) { // u | U
// Write unicode code point as UTF8 to value buffer
if (0xD800 <= n && n <= 0xE000) {
s.error("illegal: surrogate half in string literal")
} else if (n > unicode.MaxRune) {
s.error("escape sequence is invalid Unicode code point")
}
buf.reserve(utf8.UTFMax)
buf.length += utf8.encode(buf.buffer, buf.length, n)
} else {
buf.writeByte(n)
}
}
chunkStart = s.offset
break
}
case 0x24: { // $
s.readchar()
// start interpolated string
if (buf) {
s.byteval = buf.bytes()
}
if (s.gotchar(0x28)) { // (
// don't close until we see a balanced closing ')'
s.interpStrL++
s.endoffs = s.offset - 2 // exclude `$(`
} else if (s.ch as int == 0x22) { // "
// "foo $"bar"" is invalid -- hard to read, hard to parse.
// ("foo $("bar")" _is_ valid however.)
s.error(
"invalid \" in string template — string literals inside string " +
"templates need to be enclosed in parenthesis"
)
break // consume
} else {
// expect a single token to follow
s.endoffs = s.offset - 1 // exclude `$`
s.istrOne = istrOne.WAIT
}
return token.STRING_PIECE
}
case 0xA: // \n
tok = token.STRING_MULTI
s.readchar()
break
default:
s.readchar()
}
}
if (buf) {
s.byteval = buf.bytes()
} else {
s.endoffs = s.offset - 1
}
return tok
}
// scanEscape parses an escape sequence where `quote` is the accepted
// escaped character. In case of a syntax error, it stops at the offending
// character (without consuming it) and returns -1.
// Otherwise it returns the unicode codepoint for \u and \U, and returns a
// byte value for all other escape sequences.
//
scanEscape(quote :int) :int {
const s = this
let n :int = 0
let base :int = 0
let isuc = false
switch (s.ch) {
case quote: s.readchar(); return quote
case 0x30: s.readchar(); return 0 // 0 - null
case 0x61: s.readchar(); return 0x7 // a - alert or bell
case 0x62: s.readchar(); return 0x8 // b - backspace
case 0x66: s.readchar(); return 0xC // f - form feed
case 0x6e: s.readchar(); return 0xA // n - line feed or newline
case 0x72: s.readchar(); return 0xD // r - carriage return
case 0x74: s.readchar(); return 0x9 // t - horizontal tab
case 0x76: s.readchar(); return 0xb // v - vertical tab
case 0x5c: s.readchar(); return 0x5c // \
case 0x24: s.readchar(); return 0x24 // $
case 0x78: s.readchar(); n = 2; base = 16; break // x
case 0x75: s.readchar(); n = 4; base = 16; isuc = true; break // u
case 0x55: s.readchar(); n = 8; base = 16; isuc = true; break // U
default: {
let msg = "unknown escape sequence"
if (s.ch < 0) {
msg = "escape sequence not terminated"
}
s.error(msg)
return -1
}
}
let cp :int = 0
while (n > 0) {
let d = digitVal(s.ch) // returns a large value for non-digit chars
if (d >= base) {
let msg = (
(s.ch == quote) ? "escape sequence incomplete" :
(s.ch < 0) ? "escape sequence not terminated" :
`illegal character ${unicode.repr(s.ch)} in escape sequence`
)
s.errorAtOffs(msg, s.offset)
return -1
}
cp = cp * base + d
s.readchar()
n--
}
// validate unicode codepoints
if (isuc && !unicode.isValid(cp)) {
s.errorAtOffs(
"escape sequence is invalid Unicode code point",
s.offset
)
return -1
}
return cp
}
scanNumber(c :int, modc :int) {
let s = this
if (c == 0x30) { // 0
switch (s.ch) {
case 0x78: case 0x58: // x, X
return s.scanHexInt(modc)
case 0x6F: case 0x4F: // o, O
s.tok = token.INT_OCT
return s.scanRadixInt8(8, modc)
case 0x62: case 0x42: // b, B
s.tok = token.INT_BIN
return s.scanRadixInt8(2, modc)
case 0x2e: case 0x65: case 0x45: // . e E
return s.scanFloatNumber(/*seenDecimal*/false, modc)
// case 0x2f: // /
// // this is invalid, but we will still parse any number after "/"
// // scanRatioNumber returns true if it actually parsed a number.
// if (s.scanRatioNumber()) {
// // i.e. 0/N
// s.error("invalid zero ratio")
// return
// }
// break
}
}
// if we get here, the number is in base 10 and is either an int, float
// or ratio.
s.intParser.init(10, /*signed*/modc > 0, /*negative*/modc == 0x2D)
s.intParser.parseval(c - 0x30) // entry char
while (s.ch >= 0x30 && s.ch <= 0x39) { // 0..9
s.intParser.parseval(s.ch - 0x30)
s.readchar()
}
s.tok = token.INT
switch (s.ch) {
case 0x2e: case 0x65: case 0x45: // . e E
// scanning a floating-point number
return s.scanFloatNumber(/*seenDecimal*/false, modc)
}
// scanned an integer
let valid = s.intParser.finalize()
s.int32val = s.intParser.int32val
s.int64val = s.intParser.int64val
if (!valid) {
s.error("integer constant too large")
}
// if (s.ch == 0x2f) {
// return s.scanRatioNumber()
// }
}
scanHexInt(modc :int) {
const s = this
s.tok = token.INT_HEX
s.readchar()
s.intParser.init(16, /*signed*/modc > 0, /*negative*/modc == 0x2D)
let n = 0
while ((n = hexDigit(s.ch)) != -1) {
s.intParser.parseval(n)
s.readchar()
}
if (s.offset - s.startoffs <= 2 || unicode.isLetter(s.ch)) {
// only scanned "0x" or "0X" OR e.g. 0xfg
while (unicode.isLetter(s.ch) || unicode.isDigit(s.ch)) {
s.readchar() // consume invalid letters & digits
}
s.error("invalid hex number")
}
let valid = s.intParser.finalize()
s.int32val = s.intParser.int32val
s.int64val = s.intParser.int64val
if (!valid) {
s.error("integer constant too large")
}
}
scanRadixInt8(radix :int, modc :int) {
const s = this
s.readchar()
let isInvalid = false
s.intParser.init(radix, /*signed*/modc > 0, /*negative*/modc == 0x2D)
while (unicode.isDigit(s.ch)) {
if (s.ch - 0x30 >= radix) {
// e.g. 0o678
isInvalid = true
} else {
s.intParser.parseval(s.ch - 0x30)
}
s.readchar()
}
if (isInvalid || s.offset - s.startoffs <= 2 || !s.intParser.finalize()) {
// isInvalid OR only scanned "0x"
s.error(`invalid ${radix == 8 ? "octal" : "binary"} number`)
s.int32val = NaN
s.int64val = null
} else {
s.int32val = s.intParser.int32val
s.int64val = s.intParser.int64val
}
}
// scanRatioNumber() :bool {
// // ratio_lit = decimals "/" decimals
// const s = this
// const startoffs = s.offset
// s.readchar() // consume /
// while (unicode.isDigit(s.ch)) {
// s.readchar()
// }
// if (startoffs+1 == s.offset) {
// // e.g. 43/* 43/= etc -- restore state
// s.ch = 0x2f // /
// s.offset = startoffs
// s.rdOffset = s.offset + 1
// return false
// }
// if (s.ch == 0x2e) { // .
// s.error("invalid ratio")
// }
// s.tok = token.RATIO
// return true
// }
scanFloatNumber(seenDecimal :bool, _modc :int) {
// float_lit = decimals "." [ decimals ] [ exponent ] |
// decimals exponent |
// "." decimals [ exponent ] .
// decimals = decimal_digit { decimal_digit } .
// exponent = ( "e" | "E" ) [ "+" | "-" ] decimals .
const s = this
s.tok = token.FLOAT
// Note: We are ignoring modc since we use parseFloat to parse the entire
// range of source text.
if (seenDecimal || s.ch == 0x2e) { // .
s.readchar()
while (unicode.isDigit(s.ch)) {
s.readchar()
}
}
if (s.ch == 0x65 || s.ch == 0x45) { // e E
s.readchar()
if ((s.ch as int) == 0x2D || (s.ch as int) == 0x2B) { // - +
s.readchar()
}
let valid = false
if (unicode.isDigit(s.ch)) {
valid = true
s.readchar()
while (unicode.isDigit(s.ch)) {
s.readchar()
}
}
if (!valid) {
s.error("invalid floating-point exponent")
s.floatval = NaN
return
}
}
let str :string
if (s.byteval) {
str = asciistr(s.byteval)
} else {
str = asciistrn(s.sdata, s.startoffs, s.offset)
}
s.floatval = parseFloat(str)
assert(!isNaN(s.floatval), 'we failed to catch invalid float lit')
}
scanLineComment() {
const s = this
// initial '/' already consumed; s.ch == '/'
do { s.readchar() } while (s.ch != 0xA && s.ch >= 0)
if (s.sdata[s.offset-1] == 0xD) { // \r
// don't include \r in comment
s.endoffs = s.offset - 1
}
if (s.startoffs == s.lineOffset && s.sdata[s.startoffs + 2] == 0x21) { // !
// comment pragma, e.g. //!foo
s.interpretCommentPragma()
}
s.startoffs += 2 // skip //
s.tok = token.COMMENT
}
scanGeneralComment() :int /* CR count */ {
// initial '/' already consumed; s.ch == '*'
const s = this
let CR_count = 0
while (true) {
s.readchar()
switch (s.ch) {
case -1: // EOF
s.error("comment not terminated")
return CR_count
case 0x2f: // /
if (s.sdata[s.offset-1] == 0x2a) { // *
s.readchar()
s.startoffs += 2
s.endoffs = s.offset - 2
return CR_count
}
break
case 0xD: // \r
++CR_count
break
default:
break
}
}
}
findCommentLineEnd() :bool {
// initial '/' already consumed; s.ch == '*'
const s = this
// save state
const enterOffset = s.offset
while (true) {
const ch = s.ch
s.readchar()
switch (ch) {
case -1: // EOF
case 0xA: // \n
return true
case 0x2a: // *
if (s.ch == 0x2f) { // /
// restore state
s.ch = 0x2a
s.offset = enterOffset
s.rdOffset = s.offset + 1
return false
}
break
default:
break
}
}
}
interpretCommentPragma() {
const s = this
const offs = s.startoffs
if ( s.offset - offs > linePrefix.length &&
bufcmp(s.sdata, linePrefix, offs, offs + linePrefix.length) == 0
) {
// get filename and line number, if any
// e.g. "//!line file name:line"
let text = utf8.decodeToString(
s.sdata.subarray(offs + linePrefix.length, s.offset)
)
/// --- here--- the above doesnt work on uintarray.
// we need to decode sdata to a js string
let i = text.lastIndexOf(':')
if (i > 0) {
let line = parseInt(text.substr(i+1))
if (!isNaN(line) && line > 0) {
// valid //!line filename:line comment
let filename = text.substr(0, i).trim()
if (filename) {
filename = path.clean(filename)
if (!path.isAbs(filename)) {
// make filename relative to current directory
filename = path.join(s.dir, filename)
}
}
// update scanner position
s.sfile.addLineInfo(s.offset + 1, filename, line)
// +1 since comment applies to next line
}
}
}
}
findLineEnd() :bool {
// initial '/' already consumed; enters with s.ch == '*'
const s = this
// read ahead until a newline, EOF, or non-comment token is found
while (s.ch == 0x2f || s.ch == 0x2a) { // / *
if (s.ch == 0x2f) { // /
//-style comment always contains a newline
return true
}
/*-style comment: look for newline */
s.readchar()
while (s.ch >= 0) {
const ch = s.ch as int
if (ch == 0xA) { // \n
return true
}
s.readchar()
if (ch == 0x2a && s.ch as int == 0x2f) { // */
s.readchar()
break
}
}
// skip whitespace
while (
s.ch as int == 0x20 || // ' '
s.ch as int == 0x9 || // \t
(s.ch as int == 0xA && !s.insertSemi) || // \n
s.ch as int == 0xD) // \r
{
s.readchar()
}
if (s.ch < 0 || s.ch as int == 0xA) { // \n
return true
}
if (s.ch as int != 0x2f) { // /
// non-comment token
return false
}
s.readchar() // consume '/'
}
return false
}
}
function digitVal(ch :int) :int {
return (
0x30 <= ch && ch <= 0x39 ? ch - 0x30 : // 0..9
0x61 <= ch && ch <= 0x66 ? ch - 0x61 + 10 : // a..f
0x41 <= ch && ch <= 0x46 ? ch - 0x41 + 10 : // A..F
16 // larger than any legal digit val
)
}
function stripByte(v :Uint8Array, b :byte, countHint :int = 0) :Uint8Array {
const c = new Uint8Array(v.length - countHint)
let i = 0
for (let x = 0, L = v.length; x < L; ++x) {
const _b = v[x]
if (_b != b) { // \r
c[i++] = _b
}
}
return i < c.length ? c.subarray(0, i) : c
}
function isLetter(c :int) :bool {
return (
(0x41 <= c && c <= 0x5A) || // A..Z
(0x61 <= c && c <= 0x7A) // a..z
)
}
function isDigit(c :int) :bool {
return 0x30 <= c && c <= 0x39 // 0..9
}
function hexDigit(c :int) :int {
if (c >= 0x30 && c <= 0x39) { // 0..9
return c - 0x30
} else if (c >= 0x41 && c <= 0x46) { // A..F
return c - (0x41 - 10)
} else if (c >= 0x61 && c <= 0x66) { // a..f
return c - (0x61 - 10)
}
return -1
}
function isUniIdentStart(c :int) :bool {
return (
unicode.isLetter(c) ||
c == 0x5F || // _
c == 0x24 || // $
unicode.isEmojiPresentation(c) ||
unicode.isEmojiModifierBase(c)
)
}
function isUniIdentCont(c :int) :bool {
return (
c == 0x2D || // -
c == 0x5F || // _
c == 0x24 || // $
c > 0xFF || // shortcut to include most codepoints. not ideal but fast.
isLetter(c) ||
isDigit(c)
// unicode.isLetter(c) ||
// unicode.isDigit(c) ||
// unicode.isEmojiPresentation(c) ||
// unicode.isEmojiModifierBase(c) ||
)
}
const
langIdent = 1<< 1 -1,
langIdentStart = 1<< 2 -1
// values must be smaller than utf8.UniSelf
const asciiFeats = new Uint8Array([
/* 0 0 NUL */ 0,
/* 1 1 SOH */ 0,
/* 2 2 STX */ 0,
/* 3 3 ETX */ 0,
/* 4 4 EOT */ 0,
/* 5 5 ENQ */ 0,
/* 6 6 ACK */ 0,
/* 7 7 BEL */ 0,
/* 8 8 BS */ 0,
/* 9 9 TAB */ 0,
/* 10 A LF */ 0,
/* 11 B VT */ 0,
/* 12 C FF */ 0,
/* 13 D CR */ 0,
/* 14 E SO */ 0,
/* 15 F SI */ 0,
/* 16 10 DLE */ 0,
/* 17 11 DC1 */ 0,
/* 18 12 DC2 */ 0,
/* 19 13 DC3 */ 0,
/* 20 14 DC4 */ 0,
/* 21 15 NAK */ 0,
/* 22 16 SYN */ 0,
/* 23 17 ETB */ 0,
/* 24 18 CAN */ 0,
/* 25 19 EM */ 0,
/* 26 1A SUB */ 0,
/* 27 1B ESC */ 0,
/* 28 1C FS */ 0,
/* 29 1D GS */ 0,
/* 30 1E RS */ 0,
/* 31 1F US */ 0,
/* 32 20 SP */ 0,
/* 33 21 ! */ 0,
/* 34 22 " */ 0,
/* 35 23 # */ 0,
/* 36 24 $ */ langIdent | langIdentStart,
/* 37 25 % */ 0,
/* 38 26 & */ 0,
/* 39 27 ' */ 0,
/* 40 28 ( */ 0,
/* 41 29 ) */ 0,
/* 42 2A * */ 0,
/* 43 2B + */ 0,
/* 44 2C , */ 0,
/* 45 2D - */ 0,
/* 46 2E . */ 0,
/* 47 2F / */ 0,
/* 48 30 0 */ langIdent,
/* 49 31 1 */ langIdent,
/* 50 32 2 */ langIdent,
/* 51 33 3 */ langIdent,
/* 52 34 4 */ langIdent,
/* 53 35 5 */ langIdent,
/* 54 36 6 */ langIdent,
/* 55 37 7 */ langIdent,
/* 56 38 8 */ langIdent,
/* 57 39 9 */ langIdent,
/* 58 3A : */ 0,
/* 59 3B ; */ 0,
/* 60 3C < */ 0,
/* 61 3D = */ 0,
/* 62 3E > */ 0,
/* 63 3F ? */ 0,
/* 64 40 @ */ 0,
/* 65 41 A */ langIdent | langIdentStart,
/* 66 42 B */ langIdent | langIdentStart,
/* 67 43 C */ langIdent | langIdentStart,
/* 68 44 D */ langIdent | langIdentStart,
/* 69 45 E */ langIdent | langIdentStart,
/* 70 46 F */ langIdent | langIdentStart,
/* 71 47 G */ langIdent | langIdentStart,
/* 72 48 H */ langIdent | langIdentStart,
/* 73 49 I */ langIdent | langIdentStart,
/* 74 4A J */ langIdent | langIdentStart,
/* 75 4B K */ langIdent | langIdentStart,
/* 76 4C L */ langIdent | langIdentStart,
/* 77 4D M */ langIdent | langIdentStart,
/* 78 4E N */ langIdent | langIdentStart,
/* 79 4F O */ langIdent | langIdentStart,
/* 80 50 P */ langIdent | langIdentStart,
/* 81 51 Q */ langIdent | langIdentStart,
/* 82 52 R */ langIdent | langIdentStart,
/* 83 53 S */ langIdent | langIdentStart,
/* 84 54 T */ langIdent | langIdentStart,
/* 85 55 U */ langIdent | langIdentStart,
/* 86 56 V */ langIdent | langIdentStart,
/* 87 57 W */ langIdent | langIdentStart,
/* 88 58 X */ langIdent | langIdentStart,
/* 89 59 Y */ langIdent | langIdentStart,
/* 90 5A Z */ langIdent | langIdentStart,
/* 91 5B [ */ 0,
/* 92 5C \ */ 0,
/* 93 5D ] */ 0,
/* 94 5E ^ */ 0,
/* 95 5F _ */ langIdent | langIdentStart,
/* 96 60 ` */ 0,
/* 97 61 a */ langIdent | langIdentStart,
/* 98 62 b */ langIdent | langIdentStart,
/* 99 63 c */ langIdent | langIdentStart,
/* 100 64 d */ langIdent | langIdentStart,
/* 101 65 e */ langIdent | langIdentStart,
/* 102 66 f */ langIdent | langIdentStart,
/* 103 67 g */ langIdent | langIdentStart,
/* 104 68 h */ langIdent | langIdentStart,
/* 105 69 i */ langIdent | langIdentStart,
/* 106 6A j */ langIdent | langIdentStart,
/* 107 6B k */ langIdent | langIdentStart,
/* 108 6C l */ langIdent | langIdentStart,
/* 109 6D m */ langIdent | langIdentStart,
/* 110 6E n */ langIdent | langIdentStart,
/* 111 6F o */ langIdent | langIdentStart,
/* 112 70 p */ langIdent | langIdentStart,
/* 113 71 q */ langIdent | langIdentStart,
/* 114 72 r */ langIdent | langIdentStart,
/* 115 73 s */ langIdent | langIdentStart,
/* 116 74 t */ langIdent | langIdentStart,
/* 117 75 u */ langIdent | langIdentStart,
/* 118 76 v */ langIdent | langIdentStart,
/* 119 77 w */ langIdent | langIdentStart,
/* 120 78 x */ langIdent | langIdentStart,
/* 121 79 y */ langIdent | langIdentStart,
/* 122 7A z */ langIdent | langIdentStart,
/* 123 7B { */ 0,
/* 124 7C | */ 0,
/* 125 7D } */ 0,
/* 126 7E ~ */ 0,
/* 127 7F DEL */ 0,
]) | the_stack |
import {
Component,
Directive,
EventEmitter,
Input,
NgModule,
OnInit,
Output,
TemplateRef,
ViewContainerRef,
InjectionToken,
Injectable,
} from '@angular/core';
import { InvalidBindOnEntryComponentError, InvalidInputBindError, Renderer } from './renderer';
import { TestSetup } from './test-setup';
import { InvalidStaticPropertyMockError } from '../tools/mock-statics';
class TestUtility {
// tslint:disable-line no-unnecessary-class
static readonly staticNumber = 123;
static staticMethod() {
return 'foo';
}
}
const staticObject = {
staticNumber: 123,
staticMethod: () => 'foo',
};
@Component({
selector: 'thing',
template: `
<div>{{ myInput }}</div>
<span>{{ promiseResult }}</span>
`,
})
class TestComponent implements OnInit {
// tslint:disable-next-line: no-input-rename
@Input('renamedInput') fooInput!: string;
@Input() myInput!: string;
myProperty!: string;
@Output() myOutput = new EventEmitter<any>();
emitterWithoutOutputDecorator = new EventEmitter<any>();
promiseResult!: string;
async ngOnInit() {
this.promiseResult = await Promise.resolve('Promise Result');
}
}
@NgModule({
declarations: [TestComponent],
})
class TestModule {}
describe('Renderer', () => {
let renderer: Renderer<TestComponent>;
let setup: TestSetup<TestComponent>;
beforeEach(() => {
setup = new TestSetup(TestComponent, TestModule);
setup.dontMock.push(TestComponent);
renderer = new Renderer(setup);
});
it('mocks static CLASS methods from the test setup', async () => {
setup.staticMocks.set(TestUtility, { staticMethod: () => 'mocked foo' });
await renderer.render();
expect(TestUtility.staticMethod()).toBe('mocked foo');
});
it('mocks static OBJECT methods from the test setup', async () => {
setup.staticMocks.set(staticObject, { staticMethod: () => 'mocked foo' });
await renderer.render();
expect(staticObject.staticMethod()).toBe('mocked foo');
});
it('mocks static CLASS properties throws an error', async () => {
setup.staticMocks.set(TestUtility, { staticNumber: 999 });
try {
await renderer.render();
fail('render should have thrown an error');
} catch (e) {
expect(e).toBeInstanceOf(InvalidStaticPropertyMockError);
}
});
it('mocks static OBJECT properties throws an error', async () => {
setup.staticMocks.set(staticObject, { staticNumber: 999 });
try {
await renderer.render();
fail('render should have thrown an error');
} catch (e) {
expect(e).toBeInstanceOf(InvalidStaticPropertyMockError);
}
});
it('spys on output event emitters', async () => {
const { instance } = await renderer.render();
instance.myOutput.emit('FOO');
// Spys have a `calls` property on them. This is the only way I know
// how to detect an existing spy.
expect((instance.myOutput.emit as jasmine.Spy).calls).toBeDefined();
expect(instance.myOutput.emit).toHaveBeenCalledWith('FOO');
});
it('does not spy on event emitters that are not marked as @Output', async () => {
const { instance } = await renderer.render();
instance.emitterWithoutOutputDecorator.emit('FOO');
// Spys have a `calls` property on them. This is the only way I know
// how to detect an existing spy.
expect((instance.emitterWithoutOutputDecorator.emit as jasmine.Spy).calls).not.toBeDefined();
});
describe('with only template', () => {
it('wraps the rendering in a container', async () => {
const { fixture } = await renderer.render('<thing></thing>');
expect(fixture.debugElement.children[0].componentInstance).toBeInstanceOf(TestComponent);
});
});
describe('with no arguments', () => {
it('wraps the rendering in a container', async () => {
const { fixture } = await renderer.render();
expect(fixture.debugElement.children[0].componentInstance).toBeInstanceOf(TestComponent);
});
});
describe('with only renderOptions', () => {
it('wraps the rendering in a container', async () => {
const { fixture } = await renderer.render({});
expect(fixture.debugElement.children[0].componentInstance).toBeInstanceOf(TestComponent);
});
it('binds through the wrapper to the component', async () => {
const { instance } = await renderer.render({
bind: { myInput: 'FOO' },
});
expect(instance.myInput).toBe('FOO');
});
it('works on renamed @Input properties', async () => {
await renderer.render({
bind: { fooInput: 'FOO' },
});
expect(true).toBe(true);
});
it('throws an error when binding to a property that is not marked as an @Input', async () => {
try {
await renderer.render({
bind: { myProperty: 'FOO' },
});
fail('Render should have thrown an error because the myProperty is not an @Input');
} catch (e) {
expect(e).toBeInstanceOf(InvalidInputBindError);
}
});
describe('without a selector defined on the component', () => {
@Component({ template: '<div>Without selector</div>' })
class TestComponentWithoutSelector {}
@NgModule({ declarations: [TestComponentWithoutSelector] })
class NoSelectorModule {}
it('should be able to render without a template specified', async () => {
const testSetup = new TestSetup(TestComponentWithoutSelector, NoSelectorModule);
testSetup.dontMock.push(TestComponentWithoutSelector);
const { element } = await new Renderer(testSetup).render();
expect(element).toBeTruthy();
});
});
});
describe('whenStable', () => {
it('is awaited by default', async () => {
const { find } = await renderer.render();
expect(find('span').nativeElement.textContent).toBe('Promise Result');
});
it('is not awaited when disabled in options', async () => {
const { find } = await renderer.render({ whenStable: false });
expect(find('span').nativeElement.textContent).toBe('');
});
});
describe('detectChanges', () => {
it('is detected by default', async () => {
const { find } = await renderer.render({
bind: { myInput: 'FOO' },
});
expect(find('div').nativeElement.textContent).toBe('FOO');
});
it('is not detected when disabled in options', async () => {
const { find } = await renderer.render({
detectChanges: false,
bind: { myInput: 'FOO' },
});
expect(find('div').nativeElement.textContent).toBe('');
});
});
describe('structural directives', () => {
@Directive({ selector: '[ifOdd]' })
class IfOddDirective {
private hasView = false;
constructor(private readonly _templateRef: TemplateRef<any>, private readonly _viewContainer: ViewContainerRef) {}
@Input() set ifOdd(possiblyOdd: number) {
const isOdd = possiblyOdd % 2 !== 0;
if (!isOdd && !this.hasView) {
this._viewContainer.createEmbeddedView(this._templateRef);
this.hasView = true;
} else if (isOdd && this.hasView) {
this._viewContainer.clear();
this.hasView = false;
}
}
}
@NgModule({ declarations: [IfOddDirective] })
class OddModule {}
it('element is the first child element when testing a structural directive', async () => {
const myRenderer = new Renderer(new TestSetup(IfOddDirective, OddModule));
const { element } = await myRenderer.render('<b *ifOdd="2"></b>');
expect(element.nativeElement.tagName).toBe('B');
});
it('element is undefined when the structural directive does not render an element', async () => {
const myRenderer = new Renderer(new TestSetup(IfOddDirective, OddModule));
const { element } = await myRenderer.render('<b *ifOdd="1"></b>');
expect(element).not.toBeDefined();
});
it('instance is the directive instance when testing a structural directive', async () => {
const myRenderer = new Renderer(new TestSetup(IfOddDirective, OddModule));
const { instance } = await myRenderer.render('<b *ifOdd="2"></b>');
expect(instance).toBeInstanceOf(IfOddDirective);
});
});
describe('entry components', () => {
it('allows rendering entryComponents with some module magic', async () => {
@Component({
template: '<i class="my-entry">My Entry</i>',
})
class EntryComponent {}
@Component({
selector: 'my-normal-component',
template: '<i *ngComponentOutlet="entryComponentClass"></i>',
})
class NormalComponent {
entryComponentClass = EntryComponent;
}
@NgModule({
declarations: [NormalComponent, EntryComponent],
entryComponents: [EntryComponent],
})
class EntryTestModule {}
const mySetup = new TestSetup(NormalComponent, EntryTestModule);
mySetup.dontMock.push(NormalComponent, EntryComponent);
const { find } = await new Renderer(mySetup).render({ whenStable: true });
expect(find('.my-entry')).toHaveFoundOne();
});
it('allows rendering entryComponents with dependencies', async () => {
@Component({
selector: 'child-component',
template: '<i class="my-child">My Dependency</i>',
})
class ChildComponent {}
@Component({
template: '<i class="my-entry"><child-component></child-component></i>',
})
class EntryComponent {}
@Component({
selector: 'normal-component',
template: '<i *ngComponentOutlet="entryComponentClass"></i>',
})
class NormalComponent {
entryComponentClass = EntryComponent;
}
@NgModule({
declarations: [NormalComponent, EntryComponent, ChildComponent],
entryComponents: [EntryComponent],
})
class EntryTestModule {}
const mySetup = new TestSetup(NormalComponent, EntryTestModule);
mySetup.dontMock.push(NormalComponent, EntryComponent);
const { find } = await new Renderer(mySetup).render({ whenStable: true });
expect(find('.my-entry')).toHaveFoundOne();
});
it('does not allow bindings to be set for entry components', async () => {
@Component({
template: '<i class="my-entry">My Entry</i>',
})
class EntryComponent {
@Input() devMadeAMistakeAndCreatedAnInputOnAnEntryComponent!: string;
}
@NgModule({
declarations: [EntryComponent],
entryComponents: [EntryComponent],
})
class EntryTestModule {}
const mySetup = new TestSetup(EntryComponent, EntryTestModule);
try {
await new Renderer(mySetup).render({
bind: { devMadeAMistakeAndCreatedAnInputOnAnEntryComponent: 'Whoops!' },
});
fail('Should not have rendered the entry component');
} catch (e) {
expect(e).toBeInstanceOf(InvalidBindOnEntryComponentError);
}
});
it('provides mocked things even if they are not in the module', async () => {
@Component({
template: '<i>Booya</i>',
})
class BasicComponent {}
@Injectable({ providedIn: 'root' })
class BasicService {
basicFunction() {
return 'Basic';
}
}
const MY_TOKEN = new InjectionToken('Foo', { providedIn: 'root', factory: () => 'FOO' });
@NgModule({
declarations: [BasicComponent],
})
class BasicModule {}
const mySetup = new TestSetup(BasicComponent, BasicModule);
mySetup.mocks.set(MY_TOKEN, 'MOCKED VALUE');
mySetup.mocks.set(BasicService, { basicFunction: () => 'MOCKED BASIC' });
const rendering = await new Renderer(mySetup).render();
const injectedService = rendering.inject(BasicService);
const injectedToken = rendering.inject(MY_TOKEN);
expect(injectedToken).toBe('MOCKED VALUE');
expect(injectedService.basicFunction()).toBe('MOCKED BASIC');
expect(injectedService.basicFunction).toHaveBeenCalled();
});
});
}); | the_stack |
import type {BrowserObject} from 'webdriverio'
import {createStore, createEvent, restore, combine} from 'effector'
import {h, using, list, remap, spec, variant, rec} from 'forest'
// let addGlobals: Function
declare const act: (cb?: () => any) => Promise<void>
declare const initBrowser: () => Promise<void>
declare const el: HTMLElement
// let execFun: <T>(cb: (() => Promise<T> | T) | string) => Promise<T>
// let readHTML: () => string
declare const browser: BrowserObject
declare const exec: (cb: () => any) => Promise<string[]>
declare const execFunc: <T>(cb: () => Promise<T>) => Promise<T>
beforeEach(async () => {
await initBrowser()
}, 10e3)
test('edge case with duplicated keys', async () => {
const [initial, s1, s2, s3] = await exec(async () => {
const $list = createStore<(string | number)[]>(['green', 'yellow', 'red'])
const add = createEvent<MouseEvent>()
$list.on(add, list => [1, ...list])
using(el, () => {
list({
source: $list,
//@ts-expect-error
key: item => item,
fn: ({store}) => {
store.watch(console.log)
h('div', {text: store})
},
})
h('button', {text: '+', handler: {click: add}, attr: {id: 'click'}})
})
await act()
await act(async () => {
document.getElementById('click')!.click()
})
await act(async () => {
document.getElementById('click')!.click()
})
await act(async () => {
document.getElementById('click')!.click()
})
})
expect(initial).toMatchInlineSnapshot(`
"
<div>green</div>
<div>yellow</div>
<div>red</div>
<button id='click'>+</button>
"
`)
/**
* TODO: Wrong behavior!
*
* 1 should be first item, not last
*/
expect(s1).toMatchInlineSnapshot(`
"
<div>green</div>
<div>yellow</div>
<div>red</div>
<div>1</div>
<button id='click'>+</button>
"
`)
expect(s2).toMatchInlineSnapshot(`
"
<div>green</div>
<div>yellow</div>
<div>red</div>
<div>1</div>
<div>1</div>
<button id='click'>+</button>
"
`)
/**
* TODO: Wrong behavior!
*
* click should add one item, not two
*/
expect(s3).toMatchInlineSnapshot(`
"
<div>green</div>
<div>yellow</div>
<div>red</div>
<div>1</div>
<div>1</div>
<div>1</div>
<div>1</div>
<button id='click'>+</button>
"
`)
})
it('support list sequences without keys', async () => {
const [s1, s2, s3, s4] = await exec(async () => {
const addTeamAMember = createEvent<string>()
const removeTeamAMember = createEvent<string>()
const teamA = createStore([{name: 'alice'}, {name: 'bob'}])
const teamB = createStore([{name: 'carol'}])
teamA
.on(addTeamAMember, (list, name) => [...list, {name}])
.on(removeTeamAMember, (list, name) => list.filter(e => e.name !== name))
using(el, () => {
list(teamA, ({store}) => {
h('div', {
text: remap(store, 'name'),
})
})
list(teamB, ({store}) => {
h('div', {
text: remap(store, 'name'),
})
})
})
await act()
await act(() => {
addTeamAMember('carol')
})
await act(() => {
addTeamAMember('charlie')
})
await act(() => {
removeTeamAMember('carol')
})
})
expect(s1).toMatchInlineSnapshot(`
"
<div>alice</div>
<div>bob</div>
<div>carol</div>
"
`)
expect(s2).toMatchInlineSnapshot(`
"
<div>alice</div>
<div>bob</div>
<div>carol</div>
<div>carol</div>
"
`)
expect(s3).toMatchInlineSnapshot(`
"
<div>alice</div>
<div>bob</div>
<div>carol</div>
<div>charlie</div>
<div>carol</div>
"
`)
expect(s4).toMatchInlineSnapshot(`
"
<div>alice</div>
<div>bob</div>
<div>charlie</div>
<div>carol</div>
"
`)
})
it('support list sequences with keys', async () => {
const [s1, s2, s3, s4] = await exec(async () => {
const addTeamAMember = createEvent<string>()
const removeTeamAMember = createEvent<string>()
const teamA = createStore([{name: 'alice'}, {name: 'bob'}])
const teamB = createStore([{name: 'carol'}])
teamA
.on(addTeamAMember, (list, name) => [...list, {name}])
.on(removeTeamAMember, (list, name) => list.filter(e => e.name !== name))
using(el, () => {
list(
{source: teamA, key: 'name', fields: ['name']},
({fields: [name]}) => {
h('div', {text: name})
},
)
list(
{source: teamB, key: 'name', fields: ['name']},
({fields: [name]}) => {
h('div', {text: name})
},
)
})
await act()
await act(() => {
addTeamAMember('carol')
})
await act(() => {
addTeamAMember('charlie')
})
await act(() => {
removeTeamAMember('carol')
})
})
expect(s1).toMatchInlineSnapshot(`
"
<div>alice</div>
<div>bob</div>
<div>carol</div>
"
`)
expect(s2).toMatchInlineSnapshot(`
"
<div>alice</div>
<div>bob</div>
<div>carol</div>
<div>carol</div>
"
`)
expect(s3).toMatchInlineSnapshot(`
"
<div>alice</div>
<div>bob</div>
<div>carol</div>
<div>charlie</div>
<div>carol</div>
"
`)
expect(s4).toMatchInlineSnapshot(`
"
<div>alice</div>
<div>bob</div>
<div>charlie</div>
<div>carol</div>
"
`)
})
it('support text nodes', async () => {
const [s1] = await exec(async () => {
const text = createStore(['foo', 'bar'])
using(el, () => {
list(text, ({store}) => {
spec({text: store})
})
})
await act()
})
expect(s1).toMatchInlineSnapshot(`
"
"
`)
})
describe('support visible changes', () => {
it('works with non-keyed list', async () => {
const [s1, s2] = await exec(async () => {
const setTeam = createEvent<'a' | 'b'>()
const currentTeam = restore(setTeam, 'a')
const users = createStore([
{name: 'alice', team: 'a'},
{name: 'bob', team: 'b'},
{name: 'carol', team: 'b'},
{name: 'dave', team: 'a'},
{name: 'eve', team: 'a'},
])
using(el, () => {
list(users, ({store}) => {
h('p', () => {
spec({
visible: combine(
currentTeam,
store,
(current, {team}) => team === current,
),
})
h('div', {
text: remap(store, 'name'),
})
h('div', {
text: remap(store, 'team'),
})
})
})
})
await act()
await act(() => {
setTeam('b')
})
})
expect(s1).toMatchInlineSnapshot(
`"<p><div>alice</div><div>a</div></p><p><div>dave</div><div>a</div></p><p><div>eve</div><div>a</div></p>"`,
)
expect(s2).toMatchInlineSnapshot(
`"<p><div>bob</div><div>b</div></p><p><div>carol</div><div>b</div></p>"`,
)
})
it('works with keyed list', async () => {
const [s1, s2] = await exec(async () => {
type User = {
team: 'a' | 'b'
name: string
}
const setTeam = createEvent<'a' | 'b'>()
const currentTeam = restore(setTeam, 'a')
const users = createStore<User[]>([
{name: 'alice', team: 'a'},
{name: 'bob', team: 'b'},
{name: 'carol', team: 'b'},
{name: 'dave', team: 'a'},
{name: 'eve', team: 'a'},
])
using(el, () => {
list(
{source: users, key: 'name', fields: ['name', 'team']},
({fields: [name, team]}) => {
h('p', () => {
spec({
visible: combine(
currentTeam,
team,
(current, team) => team === current,
),
})
h('div', {text: name})
h('div', {text: team})
})
},
)
})
await act()
await act(() => {
setTeam('b')
})
})
expect(s1).toMatchInlineSnapshot(
`"<p><div>alice</div><div>a</div></p><p><div>dave</div><div>a</div></p><p><div>eve</div><div>a</div></p>"`,
)
expect(s2).toMatchInlineSnapshot(
`"<p><div>bob</div><div>b</div></p><p><div>carol</div><div>b</div></p>"`,
)
})
})
it('create list from [fn] option', async () => {
const [s1] = await exec(async () => {
const users = createStore([
{name: 'alice', id: 1},
{name: 'bob', id: 2},
])
using(el, () => {
list({
source: users,
key: 'id',
fn: ({store}) => {
h('li', {text: store.map(v => v.name)})
},
})
})
await act()
})
expect(s1).toMatchInlineSnapshot(`
"
<li>alice</li>
<li>bob</li>
"
`)
})
it('insert its items before sibling nodes', async () => {
const [s1, s2] = await exec(async () => {
const addUser = createEvent<string>()
const users = createStore(['alice', 'bob']).on(addUser, (list, user) => [
...list,
user,
])
using(el, () => {
list(users, ({store}) => {
h('p', {text: store})
})
h('footer', {text: 'Users'})
})
await act()
await act(() => {
addUser('carol')
})
})
expect(s1).toMatchInlineSnapshot(`
"
<p>alice</p>
<p>bob</p>
<footer>Users</footer>
"
`)
expect(s2).toMatchInlineSnapshot(`
"
<p>alice</p>
<p>bob</p>
<p>carol</p>
<footer>Users</footer>
"
`)
})
it('support node unmounting', async () => {
//prettier-ignore
type User =
| {
id: number
name: string
status: 'user'
}
| {
id: number
name: string
status: 'admin'
roles: string[]
};
await execFunc(async () => {
const removeUser = createEvent<number>()
const removeUserRole = createEvent<{userId: number; role: string}>()
const users = createStore<User[]>([
{
id: 1,
name: 'alice',
status: 'user',
},
{
id: 2,
name: 'bob',
status: 'admin',
roles: ['moderator', 'qa'],
},
{
id: 3,
name: 'carol',
status: 'admin',
roles: ['qa'],
},
{
id: 4,
name: 'charlie',
status: 'user',
},
])
.on(removeUser, (list, id) => list.filter(user => user.id !== id))
.on(removeUserRole, (list, {userId, role}) =>
list.map(user => {
if (user.status !== 'admin') return user
if (user.id !== userId) return user
return {
id: user.id,
name: user.name,
status: user.status,
roles: user.roles.filter(r => r !== role),
}
}),
)
const UserRec = rec<User>(({store}) => {
h('article', () => {
h('h2', {
text: remap(store, 'name'),
})
variant({
source: store,
key: 'status',
cases: {
user() {
h('div', {text: 'user'})
},
admin({store}) {
const roles = remap(store, 'roles')
h('div', {text: 'roles'})
h('ul', () => {
list(roles, ({store}) => {
h('li', {text: store})
})
})
},
},
})
})
})
using(el, {
fn() {
list({
source: users,
key: 'id',
fn({store}) {
UserRec({store})
},
})
},
})
await act()
await act(async () => {
removeUserRole({
userId: 2,
role: 'qa',
})
})
await act(async () => {
removeUser(4)
})
await act(async () => {
removeUser(1)
})
})
}) | the_stack |
import * as React from "react";
import { Project, File, Directory, FileType, ModelRef, isBinaryFileType, IStatusProvider } from "../models";
import { Service } from "../service";
import { ITree, ContextMenuEvent } from "../monaco-extra";
import { MonacoUtils } from "../monaco-utils";
import { ViewType } from "./editor/View";
import { openFile, pushStatus, popStatus, logLn } from "../actions/AppActions";
import { FileTemplate } from "../utils/Template";
import { createController } from "../monaco-controller";
import { DragAndDrop } from "../monaco-dnd";
export interface DirectoryTreeProps {
directory: ModelRef<Directory>;
value?: ModelRef<File>;
onEditFile?: (file: File) => void;
onDeleteFile?: (file: File) => void;
onMoveFile?: (file: File, directory: Directory) => void;
onNewFile?: (directory: Directory) => void;
onNewDirectory?: (directory: Directory) => void;
onClickFile?: (file: File) => void;
onDoubleClickFile?: (file: File) => void;
onUploadFile?: (directory: Directory) => void;
onCreateGist?: (fileOrDirectory: File) => void;
onlyUploadActions?: boolean;
}
export class DirectoryTree extends React.Component<DirectoryTreeProps, {
directory: ModelRef<Directory>;
}> {
status: IStatusProvider;
tree: ITree;
contextViewService: any;
contextMenuService: any;
container: HTMLDivElement;
lastClickedTime = Date.now();
lastClickedFile: File | null = null;
constructor(props: DirectoryTreeProps) {
super(props);
// tslint:disable-next-line
this.contextViewService = new MonacoUtils.ContextViewService(document.documentElement, null, {trace: () => {}});
this.contextMenuService = new MonacoUtils.ContextMenuService(document.documentElement, null, null, this.contextViewService);
this.state = { directory: this.props.directory };
this.status = {
push: pushStatus,
pop: popStatus,
logLn: logLn
};
}
componentDidMount() {
this.ensureTree();
(this.tree as any).model.setInput(this.props.directory.getModel());
(this.tree as any).model.onDidSelect((e: any) => {
if (e.selection.length) {
this.onClickFile(e.selection[0]);
}
});
document.addEventListener("layout", this.onLayout);
}
componentWillUnmount() {
document.removeEventListener("layout", this.onLayout);
}
componentWillReceiveProps(props: DirectoryTreeProps) {
if (this.state.directory !== props.directory) {
(this.tree as any).model.setInput(props.directory.getModel());
this.setState({ directory: props.directory });
} else {
this.tree.refresh();
MonacoUtils.expandTree(this.tree);
}
}
private setContainer(container: HTMLDivElement) {
if (container == null) { return; }
this.container = container;
}
private ensureTree() {
if (this.container.lastChild) {
this.container.removeChild(this.container.lastChild);
}
this.tree = new MonacoUtils.Tree(this.container, {
dataSource: {
/**
* Returns the unique identifier of the given element.
* No more than one element may use a given identifier.
*/
getId: function(tree: ITree, element: File): string {
return element.key;
},
/**
* Returns a boolean value indicating whether the element has children.
*/
hasChildren: function(tree: ITree, element: File): boolean {
return element instanceof Directory;
},
/**
* Returns the element's children as an array in a promise.
*/
getChildren: function(tree: ITree, element: Directory): monaco.Promise<any> {
return monaco.Promise.as(element.children);
},
/**
* Returns the element's parent in a promise.
*/
getParent: function(tree: ITree, element: File): monaco.Promise<any> {
return monaco.Promise.as(element.parent);
}
},
renderer: {
getHeight: function(tree: ITree, element: File): number {
return 24;
},
renderTemplate: function(tree: ITree, templateId: string, container: any): any {
return new FileTemplate(container);
},
renderElement: function(tree: ITree, element: File, templateId: string, templateData: any): void {
(templateData as FileTemplate).set(element);
},
disposeTemplate: function(tree: ITree, templateId: string, templateData: any): void {
(templateData as FileTemplate).dispose();
}
},
controller: createController(this, (file: File, event: ContextMenuEvent) => this.getActions(file, event), true),
dnd: new DragAndDrop(this)
});
}
getActions(file: File, event: ContextMenuEvent) {
const actions: any[] = [];
// Upload options (Limited to delete & edit)
if (this.props.onlyUploadActions) {
if (!file.parent) {
return actions;
}
this.props.onDeleteFile && actions.push(new MonacoUtils.Action("x", "Delete", "octicon-x", true, () => {
return this.props.onDeleteFile(file as Directory);
}));
this.props.onEditFile && actions.push(new MonacoUtils.Action("x", "Edit", "octicon-pencil", true, () => {
return this.props.onEditFile(file as Directory);
}));
return actions;
}
// Directory options
if (file instanceof Directory) {
this.props.onNewFile && actions.push(new MonacoUtils.Action("x", "New File", "octicon-file-add", true, () => {
return this.props.onNewFile(file as Directory);
}));
this.props.onNewDirectory && actions.push(new MonacoUtils.Action("x", "New Directory", "octicon-file-add", true, () => {
return this.props.onNewDirectory(file as Directory);
}));
this.props.onUploadFile && actions.push(new MonacoUtils.Action("x", "Upload Files", "octicon-cloud-upload", true, () => {
return this.props.onUploadFile(file as Directory);
}));
}
// Common file options
if (!(file instanceof Project)) {
this.props.onEditFile && actions.push(new MonacoUtils.Action("x", "Edit", "octicon-pencil", true, () => {
return this.props.onEditFile(file as Directory);
}));
this.props.onDeleteFile && actions.push(new MonacoUtils.Action("x", "Delete", "octicon-x", true, () => {
return this.props.onDeleteFile(file as Directory);
}));
actions.push(new MonacoUtils.Action("x", "Download", "octicon-cloud-download", true, () => {
Service.download(file);
}));
}
// Create a gist from everything but binary
if (!isBinaryFileType(file.type)) {
this.props.onCreateGist && actions.push(new MonacoUtils.Action("x", "Create Gist", "octicon-gist", true, () => {
return this.props.onCreateGist(file as Directory);
}));
}
// File-type specific separated with a ruler
if (file.type === FileType.Wasm) {
actions.push(new MonacoUtils.Action("x", "Validate", "octicon-check ruler", true, async () => {
const result = await Service.validateWasmWithBinaryen(file, this.status);
window.alert(result ? "Module is valid" : "Module is not valid");
}));
actions.push(new MonacoUtils.Action("x", "Optimize", "octicon-gear", true, () => {
Service.optimizeWasmWithBinaryen(file, this.status);
}));
actions.push(new MonacoUtils.Action("x", "Disassemble", "octicon-file-code", true, () => {
Service.disassembleWasmWithWabt(file, this.status);
}));
actions.push(new MonacoUtils.Action("x", "Disassemble w/ Binaryen", "octicon-file-code", true, () => {
Service.disassembleWasmWithBinaryen(file, this.status);
}));
actions.push(new MonacoUtils.Action("x", "To asm.js", "octicon-file-code", true, () => {
Service.convertWasmToAsmWithBinaryen(file, this.status);
}));
actions.push(new MonacoUtils.Action("x", "Generate Call Graph", "octicon-gear", true, () => {
Service.getWasmCallGraphWithBinaryen(file, this.status);
}));
actions.push(new MonacoUtils.Action("x", "To Firefox x86", "octicon-file-binary", true, () => {
Service.disassembleX86(file, this.status);
}));
actions.push(new MonacoUtils.Action("x", "To Firefox x86 Baseline", "octicon-file-binary", true, () => {
Service.disassembleX86(file, this.status, "--wasm-always-baseline");
}));
actions.push(new MonacoUtils.Action("x", "Binary Explorer", "octicon-file-binary", true, () => {
Service.openBinaryExplorer(file);
}));
actions.push(new MonacoUtils.Action("x", "View as Binary", "octicon-file-binary", true, () => {
openFile(file, ViewType.Binary, false);
}));
actions.push(new MonacoUtils.Action("x", "Twiggy", "octicon-file-binary", true, () => {
Service.twiggyWasm(file, this.status);
}));
} else if (file.type === FileType.C || file.type === FileType.Cpp) {
actions.push(new MonacoUtils.Action("x", "Clang-Format", "octicon-quote ruler", true, () => {
Service.clangFormat(file, this.status);
}));
} else if (file.type === FileType.Wat) {
actions.push(new MonacoUtils.Action("x", "Assemble", "octicon-file-binary ruler", true, () => {
Service.assembleWatWithWabt(file, this.status);
}));
actions.push(new MonacoUtils.Action("x", "Assemble w/ Binaryen", "octicon-file-binary", true, () => {
Service.assembleWatWithBinaryen(file, this.status);
}));
}
return actions;
}
onClickFile(file: File) {
if (file instanceof Directory) {
return;
}
if (Date.now() - this.lastClickedTime < 500 && this.lastClickedFile === file && this.props.onDoubleClickFile) {
this.props.onDoubleClickFile(file);
} else if (this.props.onClickFile) {
this.props.onClickFile(file);
}
this.lastClickedTime = Date.now();
this.lastClickedFile = file;
}
onLayout = () => {
this.tree.layout();
}
render() {
return <div className="fill" ref={(ref) => this.setContainer(ref)}/>;
}
} | the_stack |
import * as pidusage from '@gristlabs/pidusage';
import * as bluebird from 'bluebird';
import {EventEmitter} from 'events';
import * as path from 'path';
import {ApiError} from 'app/common/ApiError';
import {mapSetOrClear} from 'app/common/AsyncCreate';
import {BrowserSettings} from 'app/common/BrowserSettings';
import {DocCreationInfo, DocEntry, DocListAPI, OpenDocMode, OpenLocalDocResult} from 'app/common/DocListAPI';
import {Invite} from 'app/common/sharing';
import {tbind} from 'app/common/tbind';
import {NEW_DOCUMENT_CODE} from 'app/common/UserAPI';
import {HomeDBManager} from 'app/gen-server/lib/HomeDBManager';
import {assertAccess, Authorizer, DocAuthorizer, DummyAuthorizer, isSingleUserMode} from 'app/server/lib/Authorizer';
import {Client} from 'app/server/lib/Client';
import {
getDocSessionCachedDoc,
makeExceptionalDocSession,
makeOptDocSession,
OptDocSession
} from 'app/server/lib/DocSession';
import * as docUtils from 'app/server/lib/docUtils';
import {GristServer} from 'app/server/lib/GristServer';
import {IDocStorageManager} from 'app/server/lib/IDocStorageManager';
import {makeForkIds, makeId} from 'app/server/lib/idUtils';
import {checkAllegedGristDoc} from 'app/server/lib/serverUtils';
import * as log from 'app/server/lib/log';
import {ActiveDoc} from './ActiveDoc';
import {PluginManager} from './PluginManager';
import {getFileUploadInfo, globalUploadSet, makeAccessId, UploadInfo} from './uploads';
import noop = require('lodash/noop');
// A TTL in milliseconds to use for material that can easily be recomputed / refetched
// but is a bit of a burden under heavy traffic.
export const DEFAULT_CACHE_TTL = 10000;
/**
* DocManager keeps track of "active" Grist documents, i.e. those loaded
* in-memory, with clients connected to them.
*/
export class DocManager extends EventEmitter {
// Maps docName to promise for ActiveDoc object. Most of the time the promise
// will be long since resolved, with the resulting document cached.
private _activeDocs: Map<string, Promise<ActiveDoc>> = new Map();
constructor(
public readonly storageManager: IDocStorageManager,
public readonly pluginManager: PluginManager,
private _homeDbManager: HomeDBManager|null,
public gristServer: GristServer
) {
super();
}
// attach a home database to the DocManager. During some tests, it
// is awkward to have this set up at the point of construction.
public testSetHomeDbManager(dbManager: HomeDBManager) {
this._homeDbManager = dbManager;
}
public getHomeDbManager() {
return this._homeDbManager;
}
/**
* Returns an implementation of the DocListAPI for the given Client object.
*/
public getDocListAPIImpl(client: Client): DocListAPI {
return {
getDocList: tbind(this.listDocs, this, client),
createNewDoc: tbind(this.createNewDoc, this, client),
importSampleDoc: tbind(this.importSampleDoc, this, client),
importDoc: tbind(this.importDoc, this, client),
deleteDoc: tbind(this.deleteDoc, this, client),
renameDoc: tbind(this.renameDoc, this, client),
openDoc: tbind(this.openDoc, this, client),
};
}
/**
* Returns the number of currently open docs.
*/
public numOpenDocs(): number {
return this._activeDocs.size;
}
/**
* Returns a Map from docId to number of connected clients for each doc.
*/
public async getDocClientCounts(): Promise<Map<string, number>> {
const values = await Promise.all(Array.from(this._activeDocs.values(), async (adocPromise) => {
const adoc = await adocPromise;
return [adoc.docName, adoc.docClients.clientCount()] as [string, number];
}));
return new Map(values);
}
/**
* Returns a promise for all known Grist documents and document invites to show in the doc list.
*/
public async listDocs(client: Client): Promise<{docs: DocEntry[], docInvites: DocEntry[]}> {
const docs = await this.storageManager.listDocs();
return {docs, docInvites: []};
}
/**
* Returns a promise for invites to docs which have not been downloaded.
*/
public async getLocalInvites(client: Client): Promise<Invite[]> {
return [];
}
/**
* Creates a new document, fetches it, and adds a table to it.
* @returns {Promise:String} The name of the new document.
*/
public async createNewDoc(client: Client): Promise<string> {
log.debug('DocManager.createNewDoc');
const docSession = makeExceptionalDocSession('nascent', {client});
return this.createNamedDoc(docSession, 'Untitled');
}
public async createNamedDoc(docSession: OptDocSession, docId: string): Promise<string> {
const activeDoc: ActiveDoc = await this.createNewEmptyDoc(docSession, docId);
await activeDoc.addInitialTable(docSession);
return activeDoc.docName;
}
/**
* Creates a new document, fetches it, and adds a table to it.
* @param {String} sampleDocName: Doc name of a sample document.
* @returns {Promise:String} The name of the new document.
*/
public async importSampleDoc(client: Client, sampleDocName: string): Promise<string> {
const sourcePath = this.storageManager.getSampleDocPath(sampleDocName);
if (!sourcePath) {
throw new Error(`no path available to sample ${sampleDocName}`);
}
log.info('DocManager.importSampleDoc importing', sourcePath);
const basenameHint = path.basename(sampleDocName);
const targetName = await docUtils.createNumbered(basenameHint, '-',
(name: string) => docUtils.createExclusive(this.storageManager.getPath(name)));
const targetPath = this.storageManager.getPath(targetName);
log.info('DocManager.importSampleDoc saving as', targetPath);
await docUtils.copyFile(sourcePath, targetPath);
return targetName;
}
/**
* Processes an upload, containing possibly multiple files, to create a single new document, and
* returns the new document's name/id.
*/
public async importDoc(client: Client, uploadId: number): Promise<string> {
const userId = this._homeDbManager ? await client.requireUserId(this._homeDbManager) : null;
const result = await this._doImportDoc(makeOptDocSession(client),
globalUploadSet.getUploadInfo(uploadId, this.makeAccessId(userId)), {naming: 'classic'});
return result.id;
}
// Import a document, assigning it a unique id distinct from its title. Cleans up uploadId.
public importDocWithFreshId(docSession: OptDocSession, userId: number, uploadId: number): Promise<DocCreationInfo> {
const accessId = this.makeAccessId(userId);
return this._doImportDoc(docSession, globalUploadSet.getUploadInfo(uploadId, accessId),
{naming: 'saved'});
}
// Do an import targeted at a specific workspace. Cleans up uploadId.
// UserId should correspond to the user making the request.
// A workspaceId of null results in an import to an unsaved doc, not
// associated with a specific workspace.
public async importDocToWorkspace(
userId: number, uploadId: number, workspaceId: number|null, browserSettings?: BrowserSettings,
): Promise<DocCreationInfo> {
if (!this._homeDbManager) { throw new Error("HomeDbManager not available"); }
const accessId = this.makeAccessId(userId);
const docSession = makeExceptionalDocSession('nascent', {browserSettings});
const register = async (docId: string, docTitle: string) => {
if (!workspaceId || !this._homeDbManager) { return; }
const queryResult = await this._homeDbManager.addDocument({userId}, workspaceId,
{name: docTitle}, docId);
if (queryResult.status !== 200) {
// TODO The ready-to-add document is not yet in storageManager, but is in the filesystem. It
// should get cleaned up in case of error here.
throw new ApiError(queryResult.errMessage || 'unable to add imported document', queryResult.status);
}
};
return this._doImportDoc(docSession,
globalUploadSet.getUploadInfo(uploadId, accessId), {
naming: workspaceId ? 'saved' : 'unsaved',
register,
userId,
});
// The imported document is associated with the worker that did the import.
// We could break that association (see /api/docs/:docId/assign for how) if
// we start using dedicated import workers.
}
/**
* Imports file at filepath into the app by creating a new document and adding the file to
* the documents directory.
* @param {String} filepath - Path to the current location of the file on the server.
* @returns {Promise:String} The name of the new document.
*/
public async importNewDoc(filepath: string): Promise<DocCreationInfo> {
const uploadId = globalUploadSet.registerUpload([await getFileUploadInfo(filepath)], null, noop, null);
return await this._doImportDoc(makeOptDocSession(null), globalUploadSet.getUploadInfo(uploadId, null),
{naming: 'classic'});
}
/**
* Deletes the Grist files and directories for a given document name.
* @param {String} docName - The name of the Grist document to be deleted.
* @returns {Promise:String} The name of the deleted Grist document.
*
*/
public async deleteDoc(client: Client|null, docName: string, deletePermanently: boolean): Promise<string> {
log.debug('DocManager.deleteDoc starting for %s', docName);
const docPromise = this._activeDocs.get(docName);
if (docPromise) {
// Call activeDoc's shutdown method first, to remove the doc from internal structures.
const doc: ActiveDoc = await docPromise;
await doc.shutdown();
}
await this.storageManager.deleteDoc(docName, deletePermanently);
return docName;
}
/**
* Interrupt all clients, forcing them to reconnect. Handy when a document has changed
* status in some major way that affects access rights, such as being deleted.
*/
public async interruptDocClients(docName: string) {
const docPromise = this._activeDocs.get(docName);
if (docPromise) {
const doc: ActiveDoc = await docPromise;
doc.docClients.interruptAllClients();
}
}
/**
* Opens a document. Adds the client as a subscriber to the document, and fetches and returns the
* document's metadata.
* @returns {Promise:Object} An object with properties:
* `docFD` - the descriptor to use in further methods and messages about this document,
* `doc` - the object with metadata tables.
*/
public async openDoc(client: Client, docId: string,
mode: OpenDocMode = 'default',
linkParameters: Record<string, string> = {}): Promise<OpenLocalDocResult> {
let auth: Authorizer;
const dbManager = this._homeDbManager;
if (!isSingleUserMode()) {
if (!dbManager) { throw new Error("HomeDbManager not available"); }
// Sets up authorization of the document.
const org = client.getOrg();
if (!org) { throw new Error('Documents can only be opened in the context of a specific organization'); }
const userId = await client.getUserId(dbManager) || dbManager.getAnonymousUserId();
// We use docId in the key, and disallow urlId, so we can be sure that we are looking at the
// right doc when we re-query the DB over the life of the websocket.
const key = {urlId: docId, userId, org};
log.debug("DocManager.openDoc Authorizer key", key);
const docAuth = await dbManager.getDocAuthCached(key);
assertAccess('viewers', docAuth);
if (docAuth.docId !== docId) {
// The only plausible way to end up here is if we called openDoc with a urlId rather
// than a docId.
throw new Error(`openDoc expected docId ${docAuth.docId} not urlId ${docId}`);
}
auth = new DocAuthorizer(dbManager, key, mode, linkParameters, docAuth, client.getProfile() || undefined);
} else {
log.debug(`DocManager.openDoc not using authorization for ${docId} because GRIST_SINGLE_USER`);
auth = new DummyAuthorizer('owners', docId);
}
// Fetch the document, and continue when we have the ActiveDoc (which may be immediately).
const docSessionPrecursor = makeOptDocSession(client);
docSessionPrecursor.authorizer = auth;
const activeDoc: ActiveDoc = await this.fetchDoc(docSessionPrecursor, docId);
if (activeDoc.muted) {
log.debug('DocManager.openDoc interrupting, called for a muted doc', docId);
client.interruptConnection();
throw new Error(`document ${docId} cannot be opened right now`);
}
// Get a fresh DocSession object.
const docSession = activeDoc.addClient(client, auth);
// If opening in (pre-)fork mode, check if it is appropriate to treat the user as
// an owner for granular access purposes.
if (mode === 'fork') {
if (await activeDoc.canForkAsOwner(docSession)) {
// Mark the session specially and flush any cached access
// information. It is easier to make this a property of the
// session than to try computing it later in the heat of
// battle, since it introduces a loop where a user property
// (user.Access) depends on evaluating rules, but rules need
// the user properties in order to be evaluated. It is also
// somewhat justifiable even if permissions change later on
// the theory that the fork is theoretically happening at this
// instance).
docSession.forkingAsOwner = true;
activeDoc.flushAccess(docSession);
} else {
// TODO: it would be kind to pass on a message to the client
// to let them know they won't be able to fork. They'll get
// an error when they make their first change. But currently
// we only have the blunt instrument of throwing an error,
// which would prevent access to the document entirely.
}
}
const [metaTables, recentActions] = await Promise.all([
activeDoc.fetchMetaTables(docSession),
activeDoc.getRecentMinimalActions(docSession)
]);
this.emit('open-doc', this.storageManager.getPath(activeDoc.docName));
return {
docFD: docSession.fd,
clientId: docSession.client.clientId,
doc: metaTables,
log: recentActions,
recoveryMode: activeDoc.recoveryMode,
userOverride: await activeDoc.getUserOverride(docSession),
};
}
/**
* Shut down all open docs. This is called, in particular, on server shutdown.
*/
public async shutdownAll() {
await Promise.all(Array.from(this._activeDocs.values(),
adocPromise => adocPromise.then(adoc => adoc.shutdown())));
try {
await this.storageManager.closeStorage();
} catch (err) {
log.error('DocManager had problem shutting down storage: %s', err.message);
}
// Clear the setInterval that the pidusage module sets up internally.
pidusage.clear();
}
// Access a document by name.
public getActiveDoc(docName: string): Promise<ActiveDoc>|undefined {
return this._activeDocs.get(docName);
}
public async removeActiveDoc(activeDoc: ActiveDoc): Promise<void> {
this._activeDocs.delete(activeDoc.docName);
}
public async renameDoc(client: Client, oldName: string, newName: string): Promise<void> {
log.debug('DocManager.renameDoc %s -> %s', oldName, newName);
const docPromise = this._activeDocs.get(oldName);
if (docPromise) {
const adoc: ActiveDoc = await docPromise;
await adoc.renameDocTo({client}, newName);
this._activeDocs.set(newName, docPromise);
this._activeDocs.delete(oldName);
} else {
await this.storageManager.renameDoc(oldName, newName);
}
}
public markAsChanged(activeDoc: ActiveDoc, reason?: 'edit') {
// Ignore changes if document is muted or in the middle of a migration.
if (!activeDoc.muted && !activeDoc.isMigrating()) {
this.storageManager.markAsChanged(activeDoc.docName, reason);
}
}
public async makeBackup(activeDoc: ActiveDoc, name: string): Promise<string> {
if (activeDoc.muted) { throw new Error('Document is disabled'); }
return this.storageManager.makeBackup(activeDoc.docName, name);
}
/**
* Helper function for creating a new empty document that also emits an event.
* @param docSession The client session.
* @param basenameHint Suggested base name to use (no directory, no extension).
*/
public async createNewEmptyDoc(docSession: OptDocSession, basenameHint: string): Promise<ActiveDoc> {
const docName = await this._createNewDoc(basenameHint);
return mapSetOrClear(this._activeDocs, docName,
this._createActiveDoc(docSession, docName)
.then(newDoc => newDoc.createEmptyDoc(docSession)));
}
/**
* Fetches an ActiveDoc object. Used by openDoc.
*/
public async fetchDoc(docSession: OptDocSession, docName: string,
wantRecoveryMode?: boolean): Promise<ActiveDoc> {
log.debug('DocManager.fetchDoc', docName);
// Repeat until we acquire an ActiveDoc that is not muted (shutting down).
for (;;) {
if (this._activeDocs.has(docName) && wantRecoveryMode !== undefined) {
const activeDoc = await this._activeDocs.get(docName);
if (activeDoc && activeDoc.recoveryMode !== wantRecoveryMode && await activeDoc.isOwner(docSession)) {
// shutting doc down to have a chance to re-open in the correct mode.
// TODO: there could be a battle with other users opening it in a different mode.
await activeDoc.shutdown();
}
}
if (!this._activeDocs.has(docName)) {
return mapSetOrClear(this._activeDocs, docName,
this._createActiveDoc(docSession, docName, wantRecoveryMode)
.then(newDoc => {
// Propagate backupMade events from newly opened activeDocs (consolidate all to DocMan)
newDoc.on('backupMade', (bakPath: string) => {
this.emit('backupMade', bakPath);
});
return newDoc.loadDoc(docSession);
}));
}
const activeDoc = await this._activeDocs.get(docName)!;
if (!activeDoc.muted) { return activeDoc; }
log.debug('DocManager.fetchDoc waiting because doc is muted', docName);
await bluebird.delay(1000);
}
}
public makeAccessId(userId: number|null): string|null {
return makeAccessId(this.gristServer, userId);
}
public isAnonymous(userId: number): boolean {
if (!this._homeDbManager) { throw new Error("HomeDbManager not available"); }
return userId === this._homeDbManager.getAnonymousUserId();
}
private async _createActiveDoc(docSession: OptDocSession, docName: string, safeMode?: boolean) {
// Get URL for document for use with SELF_HYPERLINK().
const cachedDoc = getDocSessionCachedDoc(docSession);
let docUrl: string|undefined;
try {
if (cachedDoc) {
docUrl = await this.gristServer.getResourceUrl(cachedDoc);
} else {
docUrl = await this.gristServer.getDocUrl(docName);
}
} catch (e) {
// If there is no home url, we cannot construct links. Accept this, for the benefit
// of legacy tests.
if (!String(e).match(/need APP_HOME_URL/)) {
throw e;
}
}
return this.gristServer.create.ActiveDoc(this, docName, {docUrl, safeMode});
}
/**
* Helper that implements doing the actual import of an uploaded set of files to create a new
* document.
*/
private async _doImportDoc(docSession: OptDocSession, uploadInfo: UploadInfo,
options: {
naming: 'classic'|'saved'|'unsaved',
register?: (docId: string, docTitle: string) => Promise<void>,
userId?: number,
}): Promise<DocCreationInfo> {
try {
const fileCount = uploadInfo.files.length;
const hasGristDoc = Boolean(uploadInfo.files.find(f => extname(f.origName) === '.grist'));
if (hasGristDoc && fileCount > 1) {
throw new Error('Grist docs must be uploaded individually');
}
const first = uploadInfo.files[0].origName;
const ext = extname(first);
const basename = path.basename(first, ext).trim() || "Untitled upload";
let id: string;
switch (options.naming) {
case 'saved':
id = makeId();
break;
case 'unsaved': {
const {userId} = options;
if (!userId) { throw new Error('unsaved import requires userId'); }
if (!this._homeDbManager) { throw new Error("HomeDbManager not available"); }
const isAnonymous = userId === this._homeDbManager.getAnonymousUserId();
id = makeForkIds({userId, isAnonymous, trunkDocId: NEW_DOCUMENT_CODE,
trunkUrlId: NEW_DOCUMENT_CODE}).docId;
break;
}
case 'classic':
id = basename;
break;
default:
throw new Error('naming mode not recognized');
}
await options.register?.(id, basename);
if (ext === '.grist') {
// If the import is a grist file, copy it to the docs directory.
// TODO: We should be skeptical of the upload file to close a possible
// security vulnerability. See https://phab.getgrist.com/T457.
const docName = await this._createNewDoc(id);
const docPath: string = this.storageManager.getPath(docName);
const srcDocPath = uploadInfo.files[0].absPath;
await checkAllegedGristDoc(docSession, srcDocPath);
await docUtils.copyFile(srcDocPath, docPath);
await this.storageManager.addToStorage(docName);
return {title: basename, id: docName};
} else {
const doc = await this.createNewEmptyDoc(docSession, id);
await doc.oneStepImport(docSession, uploadInfo);
return {title: basename, id: doc.docName};
}
} catch (err) {
throw new ApiError(err.message, err.status || 400, {
tips: [{action: 'ask-for-help', message: 'Ask for help'}]
});
} finally {
await globalUploadSet.cleanup(uploadInfo.uploadId);
}
}
// Returns the name for a new doc, based on basenameHint.
private async _createNewDoc(basenameHint: string): Promise<string> {
const docName: string = await docUtils.createNumbered(basenameHint, '-', async (name: string) => {
if (this._activeDocs.has(name)) {
throw new Error("Existing entry in active docs for: " + name);
}
return docUtils.createExclusive(this.storageManager.getPath(name));
});
log.debug('DocManager._createNewDoc picked name', docName);
await this.pluginManager.pluginsLoaded;
return docName;
}
}
// Returns the extension of fpath (from last occurrence of "." to the end of the string), even
// when the basename is empty or starts with a period.
function extname(fpath: string): string {
return path.extname("X" + fpath);
} | the_stack |
import { BlockExtended } from '../mempool.interfaces';
import DB from '../database';
import logger from '../logger';
import { Common } from '../api/common';
import { prepareBlock } from '../utils/blocks-utils';
import PoolsRepository from './PoolsRepository';
import HashratesRepository from './HashratesRepository';
import { escape } from 'mysql2';
class BlocksRepository {
/**
* Save indexed block data in the database
*/
public async $saveBlockInDatabase(block: BlockExtended) {
try {
const query = `INSERT INTO blocks(
height, hash, blockTimestamp, size,
weight, tx_count, coinbase_raw, difficulty,
pool_id, fees, fee_span, median_fee,
reward, version, bits, nonce,
merkle_root, previous_block_hash, avg_fee, avg_fee_rate
) VALUE (
?, ?, FROM_UNIXTIME(?), ?,
?, ?, ?, ?,
?, ?, ?, ?,
?, ?, ?, ?,
?, ?, ?, ?
)`;
const params: any[] = [
block.height,
block.id,
block.timestamp,
block.size,
block.weight,
block.tx_count,
block.extras.coinbaseRaw,
block.difficulty,
block.extras.pool?.id, // Should always be set to something
block.extras.totalFees,
JSON.stringify(block.extras.feeRange),
block.extras.medianFee,
block.extras.reward,
block.version,
block.bits,
block.nonce,
block.merkle_root,
block.previousblockhash,
block.extras.avgFee,
block.extras.avgFeeRate,
];
await DB.query(query, params);
} catch (e: any) {
if (e.errno === 1062) { // ER_DUP_ENTRY - This scenario is possible upon node backend restart
logger.debug(`$saveBlockInDatabase() - Block ${block.height} has already been indexed, ignoring`);
} else {
logger.err('Cannot save indexed block into db. Reason: ' + (e instanceof Error ? e.message : e));
throw e;
}
}
}
/**
* Get all block height that have not been indexed between [startHeight, endHeight]
*/
public async $getMissingBlocksBetweenHeights(startHeight: number, endHeight: number): Promise<number[]> {
if (startHeight < endHeight) {
return [];
}
try {
const [rows]: any[] = await DB.query(`
SELECT height
FROM blocks
WHERE height <= ? AND height >= ?
ORDER BY height DESC;
`, [startHeight, endHeight]);
const indexedBlockHeights: number[] = [];
rows.forEach((row: any) => { indexedBlockHeights.push(row.height); });
const seekedBlocks: number[] = Array.from(Array(startHeight - endHeight + 1).keys(), n => n + endHeight).reverse();
const missingBlocksHeights = seekedBlocks.filter(x => indexedBlockHeights.indexOf(x) === -1);
return missingBlocksHeights;
} catch (e) {
logger.err('Cannot retrieve blocks list to index. Reason: ' + (e instanceof Error ? e.message : e));
throw e;
}
}
/**
* Get empty blocks for one or all pools
*/
public async $countEmptyBlocks(poolId: number | null, interval: string | null = null): Promise<any> {
interval = Common.getSqlInterval(interval);
const params: any[] = [];
let query = `SELECT count(height) as count, pools.id as poolId
FROM blocks
JOIN pools on pools.id = blocks.pool_id
WHERE tx_count = 1`;
if (poolId) {
query += ` AND pool_id = ?`;
params.push(poolId);
}
if (interval) {
query += ` AND blockTimestamp BETWEEN DATE_SUB(NOW(), INTERVAL ${interval}) AND NOW()`;
}
query += ` GROUP by pools.id`;
try {
const [rows] = await DB.query(query, params);
return rows;
} catch (e) {
logger.err('Cannot count empty blocks. Reason: ' + (e instanceof Error ? e.message : e));
throw e;
}
}
/**
* Return most recent block height
*/
public async $mostRecentBlockHeight(): Promise<number> {
try {
const [row] = await DB.query('SELECT MAX(height) as maxHeight from blocks');
return row[0]['maxHeight'];
} catch (e) {
logger.err(`Cannot count blocks for this pool (using offset). Reason: ` + (e instanceof Error ? e.message : e));
throw e;
}
}
/**
* Get blocks count for a period
*/
public async $blockCount(poolId: number | null, interval: string | null = null): Promise<number> {
interval = Common.getSqlInterval(interval);
const params: any[] = [];
let query = `SELECT count(height) as blockCount
FROM blocks`;
if (poolId) {
query += ` WHERE pool_id = ?`;
params.push(poolId);
}
if (interval) {
if (poolId) {
query += ` AND`;
} else {
query += ` WHERE`;
}
query += ` blockTimestamp BETWEEN DATE_SUB(NOW(), INTERVAL ${interval}) AND NOW()`;
}
try {
const [rows] = await DB.query(query, params);
return <number>rows[0].blockCount;
} catch (e) {
logger.err(`Cannot count blocks for this pool (using offset). Reason: ` + (e instanceof Error ? e.message : e));
throw e;
}
}
/**
* Get blocks count between two dates
* @param poolId
* @param from - The oldest timestamp
* @param to - The newest timestamp
* @returns
*/
public async $blockCountBetweenTimestamp(poolId: number | null, from: number, to: number): Promise<number> {
const params: any[] = [];
let query = `SELECT
count(height) as blockCount,
max(height) as lastBlockHeight
FROM blocks`;
if (poolId) {
query += ` WHERE pool_id = ?`;
params.push(poolId);
}
if (poolId) {
query += ` AND`;
} else {
query += ` WHERE`;
}
query += ` blockTimestamp BETWEEN FROM_UNIXTIME('${from}') AND FROM_UNIXTIME('${to}')`;
try {
const [rows] = await DB.query(query, params);
return <number>rows[0];
} catch (e) {
logger.err(`Cannot count blocks for this pool (using timestamps). Reason: ` + (e instanceof Error ? e.message : e));
throw e;
}
}
/**
* Get blocks count for a period
*/
public async $blockCountBetweenHeight(startHeight: number, endHeight: number): Promise<number> {
const params: any[] = [];
let query = `SELECT count(height) as blockCount
FROM blocks
WHERE height <= ${startHeight} AND height >= ${endHeight}`;
try {
const [rows] = await DB.query(query, params);
return <number>rows[0].blockCount;
} catch (e) {
logger.err(`Cannot count blocks for this pool (using offset). Reason: ` + (e instanceof Error ? e.message : e));
throw e;
}
}
/**
* Get the oldest indexed block
*/
public async $oldestBlockTimestamp(): Promise<number> {
const query = `SELECT UNIX_TIMESTAMP(blockTimestamp) as blockTimestamp
FROM blocks
ORDER BY height
LIMIT 1;`;
try {
const [rows]: any[] = await DB.query(query);
if (rows.length <= 0) {
return -1;
}
return <number>rows[0].blockTimestamp;
} catch (e) {
logger.err('Cannot get oldest indexed block timestamp. Reason: ' + (e instanceof Error ? e.message : e));
throw e;
}
}
/**
* Get blocks mined by a specific mining pool
*/
public async $getBlocksByPool(slug: string, startHeight?: number): Promise<object[]> {
const pool = await PoolsRepository.$getPool(slug);
if (!pool) {
throw new Error('This mining pool does not exist ' + escape(slug));
}
const params: any[] = [];
let query = ` SELECT
height,
hash as id,
UNIX_TIMESTAMP(blocks.blockTimestamp) as blockTimestamp,
size,
weight,
tx_count,
coinbase_raw,
difficulty,
fees,
fee_span,
median_fee,
reward,
version,
bits,
nonce,
merkle_root,
previous_block_hash as previousblockhash,
avg_fee,
avg_fee_rate
FROM blocks
WHERE pool_id = ?`;
params.push(pool.id);
if (startHeight !== undefined) {
query += ` AND height < ?`;
params.push(startHeight);
}
query += ` ORDER BY height DESC
LIMIT 10`;
try {
const [rows] = await DB.query(query, params);
const blocks: BlockExtended[] = [];
for (const block of <object[]>rows) {
blocks.push(prepareBlock(block));
}
return blocks;
} catch (e) {
logger.err('Cannot get blocks for this pool. Reason: ' + (e instanceof Error ? e.message : e));
throw e;
}
}
/**
* Get one block by height
*/
public async $getBlockByHeight(height: number): Promise<object | null> {
try {
const [rows]: any[] = await DB.query(`SELECT
height,
hash,
hash as id,
UNIX_TIMESTAMP(blocks.blockTimestamp) as blockTimestamp,
size,
weight,
tx_count,
coinbase_raw,
difficulty,
pools.id as pool_id,
pools.name as pool_name,
pools.link as pool_link,
pools.slug as pool_slug,
pools.addresses as pool_addresses,
pools.regexes as pool_regexes,
fees,
fee_span,
median_fee,
reward,
version,
bits,
nonce,
merkle_root,
previous_block_hash as previousblockhash,
avg_fee,
avg_fee_rate
FROM blocks
JOIN pools ON blocks.pool_id = pools.id
WHERE height = ${height};
`);
if (rows.length <= 0) {
return null;
}
rows[0].fee_span = JSON.parse(rows[0].fee_span);
return rows[0];
} catch (e) {
logger.err(`Cannot get indexed block ${height}. Reason: ` + (e instanceof Error ? e.message : e));
throw e;
}
}
/**
* Get one block by hash
*/
public async $getBlockByHash(hash: string): Promise<object | null> {
try {
const query = `
SELECT *, UNIX_TIMESTAMP(blocks.blockTimestamp) as blockTimestamp, hash as id,
pools.id as pool_id, pools.name as pool_name, pools.link as pool_link, pools.slug as pool_slug,
pools.addresses as pool_addresses, pools.regexes as pool_regexes,
previous_block_hash as previousblockhash
FROM blocks
JOIN pools ON blocks.pool_id = pools.id
WHERE hash = '${hash}';
`;
const [rows]: any[] = await DB.query(query);
if (rows.length <= 0) {
return null;
}
rows[0].fee_span = JSON.parse(rows[0].fee_span);
return rows[0];
} catch (e) {
logger.err(`Cannot get indexed block ${hash}. Reason: ` + (e instanceof Error ? e.message : e));
throw e;
}
}
/**
* Return blocks difficulty
*/
public async $getBlocksDifficulty(interval: string | null): Promise<object[]> {
interval = Common.getSqlInterval(interval);
// :D ... Yeah don't ask me about this one https://stackoverflow.com/a/40303162
// Basically, using temporary user defined fields, we are able to extract all
// difficulty adjustments from the blocks tables.
// This allow use to avoid indexing it in another table.
let query = `
SELECT
*
FROM
(
SELECT
UNIX_TIMESTAMP(blockTimestamp) as timestamp, difficulty, height,
IF(@prevStatus = YT.difficulty, @rn := @rn + 1,
IF(@prevStatus := YT.difficulty, @rn := 1, @rn := 1)
) AS rn
FROM blocks YT
CROSS JOIN
(
SELECT @prevStatus := -1, @rn := 1
) AS var
`;
if (interval) {
query += ` WHERE blockTimestamp BETWEEN DATE_SUB(NOW(), INTERVAL ${interval}) AND NOW()`;
}
query += `
ORDER BY YT.height
) AS t
WHERE t.rn = 1
ORDER BY t.height
`;
try {
const [rows]: any[] = await DB.query(query);
for (const row of rows) {
delete row['rn'];
}
return rows;
} catch (e) {
logger.err('Cannot generate difficulty history. Reason: ' + (e instanceof Error ? e.message : e));
throw e;
}
}
/**
* Get general block stats
*/
public async $getBlockStats(blockCount: number): Promise<any> {
try {
// We need to use a subquery
const query = `
SELECT MIN(height) as startBlock, MAX(height) as endBlock, SUM(reward) as totalReward, SUM(fees) as totalFee, SUM(tx_count) as totalTx
FROM
(SELECT height, reward, fees, tx_count FROM blocks
ORDER by height DESC
LIMIT ?) as sub`;
const [rows]: any = await DB.query(query, [blockCount]);
return rows[0];
} catch (e) {
logger.err('Cannot generate reward stats. Reason: ' + (e instanceof Error ? e.message : e));
throw e;
}
}
/*
* Check if the last 10 blocks chain is valid
*/
public async $validateRecentBlocks(): Promise<boolean> {
try {
const [lastBlocks]: any[] = await DB.query(`SELECT height, hash, previous_block_hash FROM blocks ORDER BY height DESC LIMIT 10`);
for (let i = 0; i < lastBlocks.length - 1; ++i) {
if (lastBlocks[i].previous_block_hash !== lastBlocks[i + 1].hash) {
logger.warn(`Chain divergence detected at block ${lastBlocks[i].height}, re-indexing most recent data`);
return false;
}
}
return true;
} catch (e) {
return true; // Don't do anything if there is a db error
}
}
/**
* Check if the chain of block hash is valid and delete data from the stale branch if needed
*/
public async $validateChain(): Promise<boolean> {
try {
const start = new Date().getTime();
const [blocks]: any[] = await DB.query(`SELECT height, hash, previous_block_hash,
UNIX_TIMESTAMP(blockTimestamp) as timestamp FROM blocks ORDER BY height`);
let partialMsg = false;
let idx = 1;
while (idx < blocks.length) {
if (blocks[idx].height - 1 !== blocks[idx - 1].height) {
if (partialMsg === false) {
logger.info('Some blocks are not indexed, skipping missing blocks during chain validation');
partialMsg = true;
}
++idx;
continue;
}
if (blocks[idx].previous_block_hash !== blocks[idx - 1].hash) {
logger.warn(`Chain divergence detected at block ${blocks[idx - 1].height}, re-indexing newer blocks and hashrates`);
await this.$deleteBlocksFrom(blocks[idx - 1].height);
await HashratesRepository.$deleteHashratesFromTimestamp(blocks[idx - 1].timestamp - 604800);
return false;
}
++idx;
}
logger.info(`${idx} blocks hash validated in ${new Date().getTime() - start} ms`);
return true;
} catch (e) {
logger.err('Cannot validate chain of block hash. Reason: ' + (e instanceof Error ? e.message : e));
return true; // Don't do anything if there is a db error
}
}
/**
* Delete blocks from the database from blockHeight
*/
public async $deleteBlocksFrom(blockHeight: number) {
logger.info(`Delete newer blocks from height ${blockHeight} from the database`);
try {
await DB.query(`DELETE FROM blocks where height >= ${blockHeight}`);
} catch (e) {
logger.err('Cannot delete indexed blocks. Reason: ' + (e instanceof Error ? e.message : e));
}
}
/**
* Get the historical averaged block fees
*/
public async $getHistoricalBlockFees(div: number, interval: string | null): Promise<any> {
try {
let query = `SELECT
CAST(AVG(height) as INT) as avgHeight,
CAST(AVG(UNIX_TIMESTAMP(blockTimestamp)) as INT) as timestamp,
CAST(AVG(fees) as INT) as avgFees
FROM blocks`;
if (interval !== null) {
query += ` WHERE blockTimestamp BETWEEN DATE_SUB(NOW(), INTERVAL ${interval}) AND NOW()`;
}
query += ` GROUP BY UNIX_TIMESTAMP(blockTimestamp) DIV ${div}`;
const [rows]: any = await DB.query(query);
return rows;
} catch (e) {
logger.err('Cannot generate block fees history. Reason: ' + (e instanceof Error ? e.message : e));
throw e;
}
}
/**
* Get the historical averaged block rewards
*/
public async $getHistoricalBlockRewards(div: number, interval: string | null): Promise<any> {
try {
let query = `SELECT
CAST(AVG(height) as INT) as avgHeight,
CAST(AVG(UNIX_TIMESTAMP(blockTimestamp)) as INT) as timestamp,
CAST(AVG(reward) as INT) as avgRewards
FROM blocks`;
if (interval !== null) {
query += ` WHERE blockTimestamp BETWEEN DATE_SUB(NOW(), INTERVAL ${interval}) AND NOW()`;
}
query += ` GROUP BY UNIX_TIMESTAMP(blockTimestamp) DIV ${div}`;
const [rows]: any = await DB.query(query);
return rows;
} catch (e) {
logger.err('Cannot generate block rewards history. Reason: ' + (e instanceof Error ? e.message : e));
throw e;
}
}
/**
* Get the historical averaged block fee rate percentiles
*/
public async $getHistoricalBlockFeeRates(div: number, interval: string | null): Promise<any> {
try {
let query = `SELECT
CAST(AVG(height) as INT) as avgHeight,
CAST(AVG(UNIX_TIMESTAMP(blockTimestamp)) as INT) as timestamp,
CAST(AVG(JSON_EXTRACT(fee_span, '$[0]')) as INT) as avgFee_0,
CAST(AVG(JSON_EXTRACT(fee_span, '$[1]')) as INT) as avgFee_10,
CAST(AVG(JSON_EXTRACT(fee_span, '$[2]')) as INT) as avgFee_25,
CAST(AVG(JSON_EXTRACT(fee_span, '$[3]')) as INT) as avgFee_50,
CAST(AVG(JSON_EXTRACT(fee_span, '$[4]')) as INT) as avgFee_75,
CAST(AVG(JSON_EXTRACT(fee_span, '$[5]')) as INT) as avgFee_90,
CAST(AVG(JSON_EXTRACT(fee_span, '$[6]')) as INT) as avgFee_100
FROM blocks`;
if (interval !== null) {
query += ` WHERE blockTimestamp BETWEEN DATE_SUB(NOW(), INTERVAL ${interval}) AND NOW()`;
}
query += ` GROUP BY UNIX_TIMESTAMP(blockTimestamp) DIV ${div}`;
const [rows]: any = await DB.query(query);
return rows;
} catch (e) {
logger.err('Cannot generate block fee rates history. Reason: ' + (e instanceof Error ? e.message : e));
throw e;
}
}
/**
* Get the historical averaged block sizes
*/
public async $getHistoricalBlockSizes(div: number, interval: string | null): Promise<any> {
try {
let query = `SELECT
CAST(AVG(height) as INT) as avgHeight,
CAST(AVG(UNIX_TIMESTAMP(blockTimestamp)) as INT) as timestamp,
CAST(AVG(size) as INT) as avgSize
FROM blocks`;
if (interval !== null) {
query += ` WHERE blockTimestamp BETWEEN DATE_SUB(NOW(), INTERVAL ${interval}) AND NOW()`;
}
query += ` GROUP BY UNIX_TIMESTAMP(blockTimestamp) DIV ${div}`;
const [rows]: any = await DB.query(query);
return rows;
} catch (e) {
logger.err('Cannot generate block size and weight history. Reason: ' + (e instanceof Error ? e.message : e));
throw e;
}
}
/**
* Get the historical averaged block weights
*/
public async $getHistoricalBlockWeights(div: number, interval: string | null): Promise<any> {
try {
let query = `SELECT
CAST(AVG(height) as INT) as avgHeight,
CAST(AVG(UNIX_TIMESTAMP(blockTimestamp)) as INT) as timestamp,
CAST(AVG(weight) as INT) as avgWeight
FROM blocks`;
if (interval !== null) {
query += ` WHERE blockTimestamp BETWEEN DATE_SUB(NOW(), INTERVAL ${interval}) AND NOW()`;
}
query += ` GROUP BY UNIX_TIMESTAMP(blockTimestamp) DIV ${div}`;
const [rows]: any = await DB.query(query);
return rows;
} catch (e) {
logger.err('Cannot generate block size and weight history. Reason: ' + (e instanceof Error ? e.message : e));
throw e;
}
}
}
export default new BlocksRepository(); | the_stack |
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import createSagaMiddleware, { SagaMiddleware, effects } from 'redux-saga'
import {
applyMiddleware,
createStore,
compose,
combineReducers,
Middleware,
Action,
Reducer,
Store,
AnyAction
} from 'redux'
import {
isString,
isFunction,
isPlainObject,
isArray,
isElement,
reduce,
set,
mapValues,
noop,
forEach,
pickBy,
isEmpty,
extend,
get,
cloneDeepWith
} from 'lodash'
import invariant from 'invariant'
import { DOMAIN_MODULE, ENTITY_MODULE, KOP_GLOBAL_STORE_REF } from './const'
import defaultMiddleWares from './middlewares'
import { isModule, isPresenter, toStorePath, hasDuplicatedKeys } from './utils'
import initSelectorHelper from './module/options/selector'
import {
Presenter,
Module,
Modules,
App,
ReducerHandler,
CreateOpt,
PageOption,
ParentNode
} from './types/createApp'
import { DefaultReducer } from './types/common'
// global store ref
let _store: Store
export default function createApp(createOpt: CreateOpt = {}) {
let app: App
const { initialReducer, onError } = createOpt
// internal map for modules
const _modules: Modules = {}
let _router = <div />
const _middleWares: Middleware<{}>[] = [...defaultMiddleWares]
const sagaMiddleware: SagaMiddleware<{}> = createSagaMiddleware()
_middleWares.push(sagaMiddleware)
function hasSubModule(module: Module) {
let flag = false
forEach(module, value => {
if (isModule(value)) {
flag = true
}
})
return flag
}
function _addModule(m: Module) {
invariant(!_modules[m.namespace], `kop nodule ${m.namespace} exists`)
if (!isEmpty(m.entities)) {
forEach(m.entities, e => {
_addModule(e)
})
}
_modules[m.namespace] = m
}
// create reducer
// http://redux.js.org/docs/recipes/reducers/RefactoringReducersExample.html
function createReducer(
initialState = {},
handlers: ReducerHandler,
defaultReducer?: DefaultReducer<any>
) {
return (state = initialState, action: Action) => {
if (
Object.prototype.hasOwnProperty.call(handlers, action.type) &&
isFunction(handlers[action.type])
) {
const handler = handlers[action.type]
return handler(state, action)
}
if (defaultReducer && isFunction(defaultReducer)) {
return defaultReducer(state, action)
}
return state
}
}
function loopCombineReducer(
tree: any,
combineRootreducer = true,
parentNode?: string | ParentNode
) {
const childReducer: any = mapValues(tree, node => {
if (!isModule(node)) {
return loopCombineReducer(node)
}
if (hasSubModule(node)) {
const subModuleMap = pickBy(node, value => isModule(value))
return loopCombineReducer(subModuleMap, true, node)
}
return createReducer(
node._initialState,
node._reducers,
node._defaultReducer
)
})
let result
if (isEmpty(parentNode)) {
result = {
...childReducer
}
} else if (parentNode === 'root') {
invariant(
!initialReducer || isPlainObject(initialReducer),
'initialReducer should be object'
)
const noDuplicatedKeys = !hasDuplicatedKeys(
initialReducer,
childReducer,
'router'
)
invariant(
noDuplicatedKeys,
'initialReducer has reduplicate keys with other reducers'
)
result = {
...initialReducer,
...childReducer
}
} else {
result = {
base: createReducer(
(parentNode as ParentNode)._initialState,
(parentNode as ParentNode)._reducers,
(parentNode as ParentNode)._defaultReducer
),
...childReducer
}
}
if (parentNode === 'root' && !combineRootreducer) return result
return combineReducers(result)
}
function addModule(module: Module | Module[]) {
if (isArray(module)) {
module.forEach(m => {
_addModule(m)
})
} else {
_addModule(module)
}
}
function initInjectModules(presenter: Presenter) {
forEach(presenter.injectModules, (name: string) => {
invariant(_modules[name], `please check the kop-module ${name} is added`)
extend(_modules[name].presenter, {
loaded: true, // 标记已被装载,在module中会注入 presentor 的 seletor
selectors: presenter.selectors,
actions: presenter.actions
})
})
}
function createRootReducer(combineRootreducer = true) {
const moduleData = cloneDeepWith(_modules)
const moduleTree = reduce(
moduleData,
(result, value, key) => {
const module = get(result, toStorePath(key))
if (isModule(value)) {
if (module) {
return set(result, `${toStorePath(key)}.base`, value)
}
return set(result, toStorePath(key), value)
}
return result
},
{}
)
return loopCombineReducer(moduleTree, combineRootreducer, 'root')
}
function addPage(pageModule: Module, opt: PageOption = {}) {
const { containers } = opt
if (containers && containers.length > 0) {
addModule(containers)
}
if (pageModule.injectModules && pageModule.injectModules.length > 0) {
initInjectModules(pageModule)
}
addModule(pageModule)
}
function addDomain(module: Module) {
addModule(module)
}
const addGlobal = _addModule
function removeModule(module: Module | Module[]) {
const _remove = (m: Module) => {
invariant(
_modules[m.namespace],
`error: the kop-module - ${m.namespace} is not existed`
)
// hack redux-devtools's bug
if (
m &&
m.actions &&
!isPresenter(m) &&
m.type !== DOMAIN_MODULE &&
(window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
) {
_store.dispatch(m.actions.__reset())
}
delete _modules[m.namespace]
_store.dispatch({ type: `${m.namespace}/@@KOP_CANCEL_EFFECTS` })
}
if (isArray(module)) {
module.forEach(m => {
_remove(m)
})
_store.replaceReducer(createRootReducer() as Reducer)
} else if (module) {
_remove(module)
_store.replaceReducer(createRootReducer() as Reducer)
}
}
function addRouter(r: JSX.Element) {
_router = r
}
function addMiddleWare(middleWare: Middleware) {
const add = (m: Middleware) => {
_middleWares.push(m)
}
add(middleWare)
}
function getStore() {
return _store
}
function createAppStore() {
// inject chrome redux devtools
let composeEnhancers
if (
process.env.NODE_ENV !== 'production' &&
(window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
) {
composeEnhancers = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
} else {
composeEnhancers = compose
}
const enhancer = composeEnhancers(applyMiddleware(..._middleWares))
const rootReducer = createRootReducer()
return createStore(rootReducer as Reducer, enhancer)
}
function getArguments(...args: any[]) {
let domSelector: string | null = null
let callback = noop
if (args.length === 1) {
// app.start(false) means jump render phase and return early
if (args[0] === false) {
return {
domSelector: '',
callback: noop,
shouldRender: false
}
}
if (isString(args[0])) {
domSelector = args[0]
}
if (isFunction(args[0])) {
callback = args[0]
}
}
if (args.length === 2) {
domSelector = args[0]
callback = args[1]
}
return {
domSelector,
callback,
shouldRender: true
}
}
function renderAppElement(
domSelector: string | null,
callback: Function,
shouldRender: boolean
) {
const $elem = <Provider store={_store}>{_router}</Provider>
// skip render when shouldRender is false
if (shouldRender) {
if (isString(domSelector)) {
render($elem, document.querySelector(domSelector), () => {
callback()
})
} else if (isElement(domSelector)) {
render($elem, domSelector, () => {
callback()
})
} else {
callback()
}
}
return $elem
}
function _onError(e: Error) {
if (!onError) {
console.error(e)
} else {
onError(e)
}
}
// create root saga
function createSaga(module: Module) {
return function*() {
if (isArray(module.effects)) {
for (let i = 0, k = module.effects.length; i < k; i++) {
const task = yield effects.fork(function*(): any {
try {
if (module.effects) {
yield module.effects[i]()
}
} catch (e) {
_onError(e)
}
})
yield effects.fork(function*() {
yield effects.take(`${module.namespace}/@@KOP_CANCEL_EFFECTS`)
yield effects.cancel(task)
})
}
}
if (isArray(module.watchers)) {
for (let i = 0, k = module.watchers.length; i < k; i++) {
const task = yield effects.fork(function*(): any {
try {
if (module.watchers) {
yield module.watchers[i]()
}
} catch (e) {
_onError(e)
}
})
yield effects.fork(function*() {
yield effects.take(`${module.namespace}/@@KOP_CANCEL_EFFECTS`)
yield effects.cancel(task)
})
}
}
}
}
function start(...args: any[]) {
const { domSelector, callback, shouldRender } = getArguments(...args)
_store = createAppStore()
initSelectorHelper(_store)
app._store = _store
window[KOP_GLOBAL_STORE_REF] = _store
app._modules = _modules
forEach(app._modules, (m: Module) => {
if (m.type === ENTITY_MODULE) {
m._store = _store // 提供domainModel的遍历action
}
})
app._middleWares = _middleWares
app._router = _router
forEach(_modules, module => {
sagaMiddleware.run(createSaga(module))
})
return renderAppElement(domSelector, callback, shouldRender)
}
// 集成模式初始化,返回 saga,reducer 等等
function _init() {
const rootReducer = createRootReducer(false)
return {
rootReducer,
sagaMiddleware
}
}
// 集成模式启动,由外部 Redux 控制 App 渲染流程
function _run(store: Store<any, AnyAction>) {
initSelectorHelper(store)
app._store = store
window[KOP_GLOBAL_STORE_REF] = store
app._modules = _modules
forEach(app._modules, (m: Module) => {
if (m.type === ENTITY_MODULE) {
m._store = store
}
})
app._router = _router
forEach(_modules, module => {
sagaMiddleware.run(createSaga(module))
})
}
app = {
addModule, // register container module
addPage, // register page module
addDomain, // register domain module
addGlobal, // register global module
addRouter,
addMiddleWare,
start,
getStore,
removeModule,
_init,
_run
}
return app
} | the_stack |
import { h,createProjector, VNode } from 'maquette'
import { Log } from "./common/log"
import * as Langs from './definitions/languages'
import * as Graph from './definitions/graph'
import * as Docs from './services/documentService'
import { editor } from 'monaco-editor';
// ------------------------------------------------------------------------------------------------
// Notebook user interface state and event type
// ------------------------------------------------------------------------------------------------
interface NotebookAddEvent { kind:'add', id: number, language:string }
interface NotebookMoveEvent { kind:'move', cell: Langs.BlockState, direction:"up"|"down"}
interface NotebookToggleAddEvent { kind:'toggleadd', id: number }
interface NotebookRemoveEvent { kind:'remove', id: number }
interface NotebookBlockEvent { kind:'block', id:number, event:any }
interface NotebookUpdateTriggerEvalEvent { kind:'evaluate', id:number }
interface NotebookUpdateEvalStateEvent { kind:'evalstate', hash:string, newState:"pending" | "done" }
interface NotebookSourceChange { kind:'rebind', block: Langs.BlockState, newSource: string}
type NotebookEvent =
NotebookAddEvent | NotebookToggleAddEvent | NotebookRemoveEvent | NotebookUpdateTriggerEvalEvent |
NotebookBlockEvent | NotebookUpdateEvalStateEvent | NotebookSourceChange | NotebookMoveEvent
type NotebookState = {
contentChanged: (newContent:string) => void,
languagePlugins: Langs.LanguagePlugins
cells: Langs.BlockState[]
counter: number
expandedMenu : number
cache: Graph.NodeCache
resourceServerUrl: string
resources:Array<Langs.Resource>
}
let paperElementID:string='paper'
// ------------------------------------------------------------------------------------------------
// Helper functions for binding nodes
// ------------------------------------------------------------------------------------------------
function bindCell (cache:Graph.NodeCache,
scope:Langs.ScopeDictionary,
editor:Langs.EditorState,
languagePlugins:Langs.LanguagePlugins,
resourceServerUrl:string,
resources:Array<Langs.Resource>): Promise<{code: Graph.Node, exports: Graph.ExportNode[], resources: Array<Langs.Resource>}>{
let languagePlugin = languagePlugins[editor.block.language]
return languagePlugin.bind({ resourceServerUrl:resourceServerUrl, cache:cache, scope:scope, resources:resources }, editor.block);
}
async function bindAllCells(state:NotebookState, editors:Langs.EditorState[]) {
var scope : Langs.ScopeDictionary = { };
var newCells : Langs.BlockState[] = []
let updatedResources: Array<Langs.Resource> = []
for (var c = 0; c < editors.length; c++) {
let editor = editors[c]
let {code, exports, resources} = await bindCell(state.cache, scope, editor, state.languagePlugins, state.resourceServerUrl, updatedResources);
updatedResources = updatedResources.concat(resources)
var newCell:Langs.BlockState = { editor:editor, code:code, exports:exports, evaluationState: "unevaluated"}
for (var e = 0; e < exports.length; e++ ) {
let exportNode = exports[e];
scope[exportNode.variableName] = exportNode;
}
newCells.push(newCell)
}
return {newCells: newCells, updatedResources: updatedResources};
}
async function updateAndBindAllCells (state:NotebookState, cell:Langs.BlockState, newSource: string): Promise<NotebookState> {
Log.trace("binding", "Begin rebinding subsequent cells. Cell: %O, New source: %O", cell, {"newSource": newSource})
let editors = state.cells.map(c => {
let lang = state.languagePlugins[c.editor.block.language]
if (c.editor.id == cell.editor.id) {
let block = lang.parse(newSource);
let editor:Langs.EditorState = lang.editor.initialize(c.editor.id, block);
return editor;
}
else return c.editor;
});
let {newCells, updatedResources} = await bindAllCells(state, editors);
return { ...state, cells:newCells, resources:updatedResources };
}
async function evaluate(node:Graph.Node, state:NotebookState,
triggerEvalStateEvent:(hash:string,state:"pending"|"done") => void) {
if (node.value && (Object.keys(node.value).length > 0)) return;
triggerEvalStateEvent(node.hash,"pending")
for(var ant of node.antecedents) await evaluate(ant, state, triggerEvalStateEvent);
let languagePlugin = state.languagePlugins[node.language]
// let source = (<any>node).source ? (<any>node).source.substr(0, 100) + "..." : "(no source)"
// Log.trace("editor","Evaluating %s node: %s", node.language, source)
let ctx = {resourceServerUrl:state.resourceServerUrl, resources:state.resources, cells:state.cells, languagePlugins:state.languagePlugins}
let evalResult = await languagePlugin.evaluate(ctx, node);
// Log.trace("evaluation","Evaluated %s node. Result: %O", node.language, node.value)
switch(evalResult.kind) {
case "success":
node.value = evalResult.value;
break;
case "error":
node.errors = evalResult.errors;
break;
}
triggerEvalStateEvent(node.hash, "done")
}
// ------------------------------------------------------------------------------------------------
// Render and update functions
// ------------------------------------------------------------------------------------------------
function render(trigger:(evt:NotebookEvent) => void, state:NotebookState) {
Log.trace("render", "Rendering %d cells", state.cells.length)
setTimeout(function(){ }, 3000);
function renderControlsBar() {
let langs = Object.keys(state.languagePlugins).map(lang =>
h('a', {
key:"add-" + lang,
onclick:()=>trigger({kind:'add', id:-1, language:lang})},
[ h('i', {'class':'fa fa-plus'}), lang ]))
let cmds = [
h('a', {key:"add", onclick:()=>trigger({kind:'toggleadd', id:-1})},[h('i', {'class':'fa fa-plus'}), "add below"]),
]
let tools = state.expandedMenu == -1 ? langs : cmds;
let controls = h('div', {class:'controls'}, tools)
return h('div', {id: "controls_default", class:'controls-bar', key:"controls_default"}, [controls])
}
let defaultControl:VNode = h('div', {id: 'add_default', class:'cell cell-c-default', key: 'add_default'}, [
renderControlsBar()
]);
let nodes:Array<VNode> = state.cells.map(cell => {
let context : Langs.EditorContext<any> = {
trigger: (event:any) =>
trigger({ kind:'block', id:cell.editor.id, event:event }),
evaluate: (blockId:number) =>
trigger({ kind:'evaluate', id:blockId }),
rebindSubsequent: (block:Langs.BlockState, newSource: string) => {
trigger({kind: 'rebind', block: block, newSource: newSource})
}
}
let plugin = state.languagePlugins[cell.editor.block.language]
let content = plugin.editor.render(cell, cell.editor, context)
let icon = plugin.iconClassName;
let icons = h('div', {class:'icons'}, [
h('i', {id:'cellIcon_'+cell.editor.id, class: icon }, []),
h('span', {}, [cell.editor.block.language] )
])
let move = h('div', {class:'move'}, [
h('a', { onclick:()=> trigger({ kind:'move', cell: cell, direction:"up" }) },
[ h('i', { class: 'fa fa-arrow-up' }) ]),
h('a', { onclick:()=> trigger({ kind:'move', cell: cell, direction:"down" }) },
[ h('i', { class: 'fa fa-arrow-down' }) ])
])
let langs = Object.keys(state.languagePlugins).map(lang =>
h('a', {
key:"add-" + lang,
onclick:()=>trigger({kind:'add', id:cell.editor.id, language:lang})},
[ h('i', {'class':'fa fa-plus'}), lang ]))
.concat(
h('a', {
key:"cancel",
onclick:()=>trigger({kind:'toggleadd', id:-1})},
[h('i', {'class':'fa fa-times'}), "cancel"]))
let cmds = [
h('a', {key:"add", onclick:()=>trigger({kind:'toggleadd', id:cell.editor.id})},[h('i', {'class':'fa fa-plus'}), "add below"]),
h('a', {key:"remove", onclick:()=>trigger({kind:'remove', id:cell.editor.id})},[h('i', {'class':'fa fa-times'}), "remove this"])
]
let tools = state.expandedMenu == cell.editor.id ? langs : cmds;
let controls = h('div', {class:'controls'}, tools)
let controlsBar = h('div', {class:'controls-bar', key:"controls_"+cell.editor.id}, [controls])
let iconsBar = h('div', {class:'icons-bar', key:"icons_"+cell.editor.id}, [icons, move])
let contentBar = h('div', {class:'content-bar', key:"content_"+cell.editor.id}, [content])
let langIndex = Object.keys(state.languagePlugins).indexOf(cell.editor.block.language)
return h('div', {class:'cell cell-c' + langIndex, key:cell.editor.id}, [
iconsBar, contentBar, controlsBar
]
);
});
return h('div', {class:'container-fluid', id:paperElementID}, [defaultControl, nodes])
}
async function update(trigger:(evt:NotebookEvent) => void,
state:NotebookState, evt:NotebookEvent) : Promise<NotebookState> {
Log.trace("main", "Updating with event: %s", evt.kind)
// Log.trace("spreadsheet", "Updating with event: %s", evt.kind)
function spliceEditor (editors:Langs.EditorState[], newEditor: Langs.EditorState, idOfAboveBlock: number) {
let newEditorState:Langs.EditorState[] = []
if (idOfAboveBlock > -1) {
newEditorState = editors.map (editor => {
if (editor.id === idOfAboveBlock) return [editor, newEditor];
else return [editor]
}).reduce ((a,b)=> a.concat(b));
return newEditorState
}
else {
newEditorState = editors.map (editor => {
if (editor.id === 0) return [newEditor,editor];
else return [editor]
}).reduce ((a,b)=> a.concat(b));
}
return newEditorState
}
function moveUpEditor (editors: Langs.EditorState[], selectedEditor: Langs.EditorState) {
let newEditors = editors.map(es => es);
for(let i = 0; i < editors.length; i++) {
if (editors[i].id == selectedEditor.id && i != 0) {
newEditors[i] = editors[i-1];
newEditors[i-1] = editors[i];
}
}
return newEditors;
}
function moveDownEditor (editors: Langs.EditorState[], selectedEditor: Langs.EditorState) {
let newEditors = editors.map(es => es);
for(let i = 0; i < editors.length; i++) {
if (editors[i].id == selectedEditor.id && i != editors.length-1) {
newEditors[i] = editors[i+1];
newEditors[i+1] = editors[i];
}
}
return newEditors;
}
function removeCell (cells:Langs.BlockState[], idOfSelectedBlock: number) {
return cells.map (cell => {
if (cell.editor.id === idOfSelectedBlock) return [];
else return [cell]
}).reduce ((a,b)=> a.concat(b));
}
switch(evt.kind) {
case 'block': {
let newCells:Langs.BlockState[] = state.cells.map(cellState => {
if (cellState.editor.id != evt.id)
return cellState
else {
var newCell:Langs.BlockState = { editor: state.languagePlugins[cellState.editor.block.language].editor.update(cellState.editor, evt.event),
code:cellState.code, exports:exports, evaluationState: "unevaluated"}
return newCell
}
})
return {...state, cells: newCells}
// return { cache:state.cache,
// counter: state.counter,
// cells: newCells,
// contentChanged:state.contentChanged,
// expandedMenu: state.expandedMenu,
// languagePlugins: state.languagePlugins,
// resources: state.resources };
}
case 'evalstate':
let newCells:Langs.BlockState[] = state.cells.map(cellState => {
if (cellState.code.hash != evt.hash)
return cellState
else {
var newCell:Langs.BlockState = {
editor: cellState.editor,
code:cellState.code,
exports:cellState.exports,
evaluationState: evt.newState}
return newCell
}
})
return {...state, cells: newCells}
case 'toggleadd':
return {...state, expandedMenu: evt.id};
case 'move': {
let newEditors: Langs.EditorState[] = []
if ((state.cells[0].editor.id == evt.cell.editor.id) && (evt.direction == 'up'))
return {...state};
if ((state.cells[state.cells.length-1].editor.id == evt.cell.editor.id) && (evt.direction == 'down'))
return {...state};
if (evt.direction == 'up')
newEditors = moveUpEditor(state.cells.map(c => c.editor), evt.cell.editor)
else
newEditors = moveDownEditor(state.cells.map(c => c.editor), evt.cell.editor)
let {newCells, updatedResources} = await bindAllCells(state, newEditors)
return {...state, cells: newCells, resources: updatedResources};
}
case 'add': {
Log.trace('main', "Adding cell")
let newId = state.counter + 1;
let lang = state.languagePlugins[evt.language];
let newDocument = { "language": evt.language, "source": lang.getDefaultCode(newId) };
let newBlock = lang.parse(newDocument.source);
let editor = lang.editor.initialize(newId, newBlock);
let newEditors = spliceEditor(state.cells.map(c => c.editor), editor, evt.id)
Log.trace('main', "Spliced editor: %O", newEditors)
let {newCells, updatedResources} = await bindAllCells(state, newEditors)
state.resources = state.resources.concat(updatedResources)
newCells.map(c => {
Log.trace('main', "New cell: %O", c.editor.block)
})
return {...state, counter: newId, expandedMenu:-1, cells: newCells, resources: state.resources}
}
case 'remove':
return {...state, cells: removeCell(state.cells, evt.id) };
case 'evaluate':
let triggerEvalStateEvent = (hash:string, newState:"pending"|"done") => {
Log.trace('main', "update evaluate triggerEvalStateEvent to '%s'", newState)
trigger({kind:'evalstate', hash:hash, newState})
}
let doEvaluate = async (block:Langs.BlockState) => {
await evaluate(block.code, state, triggerEvalStateEvent)
for(var exp of block.exports) await evaluate(exp, state, triggerEvalStateEvent)
}
let blocks = state.cells.filter(b => b.editor.id == evt.id)
if (blocks.length > 0) doEvaluate(blocks[0]);
else Log.error("main", "Tried to evaluate block that has been removed")
return state;
case 'rebind':
let newState = await updateAndBindAllCells(state, evt.block, evt.newSource);
state.contentChanged(saveDocument(newState))
Log.trace('jupyter',"This will trigger a render in Jupyter")
Log.trace('spreadsheet',"Returning new state")
return newState
}
}
// ------------------------------------------------------------------------------------------------
// Helper functions for creating notebooks
// ------------------------------------------------------------------------------------------------
async function initializeCells(elementID:string, counter: number, editors:Langs.EditorState[],
languagePlugins:Langs.LanguagePlugins, resourceServerUrl:string, contentChanged:(newContent:string) => void) {
let maquetteProjector = createProjector();
let paperElement = document.getElementById(elementID);
paperElementID = elementID;
Log.trace('main', "Looking for a element %s", paperElementID)
let elementNotFoundError:string = "Missing paper element: "+elementID
if (!paperElement) throw elementNotFoundError
var cache = createNodeCache()
var prestate : NotebookState = {cache:cache, counter:counter, cells:[], resourceServerUrl:resourceServerUrl,
contentChanged: contentChanged, expandedMenu:-1, languagePlugins:languagePlugins, resources: []}
var {newCells, updatedResources} = await bindAllCells(prestate, editors);
var state : NotebookState = {...prestate, cells:newCells, resources: updatedResources}
var events : NotebookEvent[] = []
var handling = false;
function trigger(event:NotebookEvent) {
Log.trace("main", "Triggering event: %s", event.kind )
events.push(event)
processEvents()
}
function processEvents() {
// Log.trace("main", "Processing events (%s). First of kind: %s",
// events.length, events.length>0?events[0].kind:"N/A")
if (events.length > 0 && !handling) {
handling = true;
let event = events[0]
events = events.slice(1)
update(trigger, state, event).then(newState => {
state = newState
handling = false;
// state.cells.map(c => Log.trace('main', "Cell: %O ", c.editor.block ))
if (events.length > 0) processEvents()
else maquetteProjector.scheduleRender()
});
}
}
maquetteProjector.replace(paperElement, () => render(trigger, state))
}
function loadNotebook(documents:Docs.DocumentElement[], languagePlugins:Langs.LanguagePlugins) {
let index = 0
let blockStates = documents
.filter(cell => {
// TODO: better error handling
const pluginFound: boolean = cell.language in languagePlugins
if (!pluginFound) {
Log.error("loadNotebook", `${cell.language} plugin not found.`)
}
return pluginFound
})
.map(cell => {
let languagePlugin = languagePlugins[cell.language];
let block = languagePlugin.parse(cell.source);
let editor:Langs.EditorState = languagePlugin.editor.initialize(index++, block);
return editor;
})
return { counter: index, editors: blockStates };
}
function saveDocument(state:NotebookState): string {
let content:string = ""
for (let cell of state.cells) {
let plugin = state.languagePlugins[cell.editor.block.language];
let cellContent = plugin.save(cell.editor.block);
content = content.concat(cellContent)
}
return content;
}
function createNodeCache() : Graph.NodeCache {
let nodeCache = { }
return {
tryFindNode : (node:Graph.Node) => {
let key = [ node.language, node.hash ].concat(node.antecedents.map(a => a.hash)).join(",")
if (typeof(nodeCache[key]) == "undefined")
nodeCache[key] = node;
return nodeCache[key];
}
}
}
export {
loadNotebook,
initializeCells
} | the_stack |
import { SerializerError, SerializerErrorType } from '../errors'
import { CosmosTransaction } from '../protocols/cosmos/CosmosTransaction'
import { MainProtocolSymbols, ProtocolSymbols, SubProtocolSymbols } from '../utils/ProtocolSymbols'
import { IACProtocol } from './inter-app-communication-protocol'
import { IACMessageType } from './interfaces'
import { IACMessageDefinitionObject } from './message'
import { FullPayload } from './payloads/full-payload'
import { Payload } from './payloads/payload'
import { SerializableUnsignedCosmosTransaction } from './schemas/definitions/unsigned-transaction-cosmos'
import { SchemaInfo, SchemaRoot } from './schemas/schema'
import { AeternityTransactionValidator } from './unsigned-transactions/aeternity-transactions.validator'
import { BitcoinTransactionValidator } from './unsigned-transactions/bitcoin-transactions.validator'
import { CosmosTransactionValidator } from './unsigned-transactions/cosmos-transactions.validator'
import { EthereumTransactionValidator } from './unsigned-transactions/ethereum-transactions.validator'
import { SubstrateTransactionValidator } from './unsigned-transactions/substrate-transactions.validator'
import { TezosTransactionValidator } from './unsigned-transactions/tezos-transactions.validator'
import { TezosBTCTransactionValidator } from './unsigned-transactions/xtz-btc-transactions.validator'
import { TransactionValidator } from './validators/transactions.validator'
const accountShareResponse: SchemaRoot = require('./schemas/generated/account-share-response.json')
const messageSignRequest: SchemaRoot = require('./schemas/generated/message-sign-request.json')
const messageSignResponse: SchemaRoot = require('./schemas/generated/message-sign-response.json')
const unsignedTransactionAeternity: SchemaRoot = require('./schemas/generated/transaction-sign-request-aeternity.json')
const unsignedTransactionBitcoin: SchemaRoot = require('./schemas/generated/transaction-sign-request-bitcoin.json')
const unsignedTransactionCosmos: SchemaRoot = require('./schemas/generated/transaction-sign-request-cosmos.json')
const unsignedTransactionEthereum: SchemaRoot = require('./schemas/generated/transaction-sign-request-ethereum.json')
const unsignedTransactionTezos: SchemaRoot = require('./schemas/generated/transaction-sign-request-tezos.json')
const unsignedTransactionTezosSapling: SchemaRoot = require('./schemas/generated/transaction-sign-request-tezos-sapling.json')
const unsignedTransactionSubstrate: SchemaRoot = require('./schemas/generated/transaction-sign-request-substrate.json')
const signedTransactionAeternity: SchemaRoot = require('./schemas/generated/transaction-sign-response-aeternity.json')
const signedTransactionBitcoin: SchemaRoot = require('./schemas/generated/transaction-sign-response-bitcoin.json')
const signedTransactionCosmos: SchemaRoot = require('./schemas/generated/transaction-sign-response-cosmos.json')
const signedTransactionEthereum: SchemaRoot = require('./schemas/generated/transaction-sign-response-ethereum.json')
const signedTransactionTezos: SchemaRoot = require('./schemas/generated/transaction-sign-response-tezos.json')
const signedTransactionTezosSapling: SchemaRoot = require('./schemas/generated/transaction-sign-response-tezos-sapling.json')
const signedTransactionSubstrate: SchemaRoot = require('./schemas/generated/transaction-sign-response-substrate.json')
function unsignedTransactionTransformerCosmos(value: SerializableUnsignedCosmosTransaction): SerializableUnsignedCosmosTransaction {
value.transaction = CosmosTransaction.fromJSON(value) as any
return value
}
export enum IACPayloadType {
FULL = 0,
CHUNKED = 1
}
export class Serializer {
private static readonly schemas: Map<string, SchemaInfo> = new Map()
public static addSchema(schemaId: number, schema: SchemaInfo, protocol?: ProtocolSymbols): void {
const protocolSpecificSchemaName: string = Serializer.getSchemaName(schemaId, protocol)
if (this.schemas.has(protocolSpecificSchemaName)) {
throw new SerializerError(SerializerErrorType.SCHEMA_ALREADY_EXISTS, `Schema ${protocolSpecificSchemaName} already exists`)
}
this.schemas.set(protocolSpecificSchemaName, schema)
}
public static getSchema(schemaId: number, protocol?: ProtocolSymbols): SchemaInfo {
const protocolSpecificSchemaName: string = Serializer.getSchemaName(schemaId, protocol)
// Try to get the protocol specific scheme, if it doesn't exist fall back to the generic one
const schema: SchemaInfo | undefined =
this.schemas.get(protocolSpecificSchemaName) ?? this.schemas.get(Serializer.getSchemaName(schemaId))
if (!schema) {
throw new SerializerError(SerializerErrorType.SCHEMA_DOES_NOT_EXISTS, `Schema ${protocolSpecificSchemaName} does not exist`)
}
return schema
}
private static getSchemaName(schemaId: number, protocol?: ProtocolSymbols): string {
const schemaName = `${schemaId}-${protocol}`
if (
(protocol !== undefined && schemaId === IACMessageType.TransactionSignRequest) ||
schemaId === IACMessageType.TransactionSignResponse
) {
const split = schemaName.split('-')
if (split.length >= 3 && `${split[1]}-${split[2]}` === SubProtocolSymbols.ETH_ERC20) {
return `${schemaId}-${SubProtocolSymbols.ETH_ERC20}`
}
}
return protocol ? `${schemaId}-${protocol}` : schemaId.toString()
}
public async serialize(
messages: IACMessageDefinitionObject[],
singleChunkSize: number = 0,
multiChunkSize: number = 0
): Promise<string[]> {
if (
messages.every((message: IACMessageDefinitionObject) => {
return Serializer.getSchema(message.type, message.protocol)
})
) {
const iacps: IACProtocol[] = IACProtocol.fromDecoded(JSON.parse(JSON.stringify(messages)), singleChunkSize, multiChunkSize)
return iacps.map((iac: IACProtocol) => iac.encoded())
} else {
throw new SerializerError(SerializerErrorType.SCHEMA_DOES_NOT_EXISTS, `Unknown schema`)
}
}
public async deserialize(data: string[]): Promise<IACMessageDefinitionObject[]> {
const result: IACProtocol[] = IACProtocol.fromEncoded(data)
const deserializedIACMessageDefinitionObjects: IACMessageDefinitionObject[] = result
.map((el: IACProtocol) => el.payload)
.map((el: Payload) => (el as FullPayload).asJson())
.reduce((pv: IACMessageDefinitionObject[], cv: IACMessageDefinitionObject[]) => pv.concat(...cv), [] as IACMessageDefinitionObject[])
return deserializedIACMessageDefinitionObjects
}
public serializationValidatorByProtocolIdentifier(protocolIdentifier: ProtocolSymbols): TransactionValidator {
const validators: { [key in ProtocolSymbols]?: any } = {
// TODO: Exhaustive list?
eth: EthereumTransactionValidator,
btc: BitcoinTransactionValidator,
grs: BitcoinTransactionValidator,
ae: AeternityTransactionValidator,
xtz: TezosTransactionValidator,
cosmos: CosmosTransactionValidator,
polkadot: SubstrateTransactionValidator,
kusama: SubstrateTransactionValidator,
'xtz-btc': TezosBTCTransactionValidator
}
const exactMatch = Object.keys(validators).find((protocol) => protocolIdentifier === protocol)
const startsWith = Object.keys(validators).find((protocol) => protocolIdentifier.startsWith(protocol))
const validator = exactMatch ? exactMatch : startsWith
// TODO: Only use validator if it's a transaction
// if (!validator) {
// throw Error(`Validator not implemented for ${protocolIdentifier}, ${exactMatch}, ${startsWith}, ${validator}`)
// }
return new validators[validator ?? 'eth']()
}
}
// Serializer.addSchema(IACMessageType.MetadataRequest, '')
// Serializer.addSchema(IACMessageType.MetadataResponse, '')
// Serializer.addSchema(IACMessageType.AccountShareRequest, accountShareRequest)
Serializer.addSchema(IACMessageType.AccountShareResponse, { schema: accountShareResponse })
Serializer.addSchema(IACMessageType.MessageSignRequest, { schema: messageSignRequest })
Serializer.addSchema(IACMessageType.MessageSignResponse, { schema: messageSignResponse })
// TODO: Make sure that we have a schema for every protocol we support
Serializer.addSchema(IACMessageType.TransactionSignRequest, { schema: unsignedTransactionAeternity }, MainProtocolSymbols.AE)
Serializer.addSchema(IACMessageType.TransactionSignRequest, { schema: unsignedTransactionBitcoin }, MainProtocolSymbols.BTC)
Serializer.addSchema(IACMessageType.TransactionSignRequest, { schema: unsignedTransactionBitcoin }, MainProtocolSymbols.GRS)
Serializer.addSchema(
IACMessageType.TransactionSignRequest,
{ schema: unsignedTransactionCosmos, transformer: unsignedTransactionTransformerCosmos },
MainProtocolSymbols.COSMOS
)
Serializer.addSchema(IACMessageType.TransactionSignRequest, { schema: unsignedTransactionEthereum }, MainProtocolSymbols.ETH)
Serializer.addSchema(IACMessageType.TransactionSignRequest, { schema: unsignedTransactionEthereum }, SubProtocolSymbols.ETH_ERC20)
Serializer.addSchema(IACMessageType.TransactionSignRequest, { schema: unsignedTransactionTezos }, MainProtocolSymbols.XTZ)
Serializer.addSchema(IACMessageType.TransactionSignRequest, { schema: unsignedTransactionTezosSapling }, MainProtocolSymbols.XTZ_SHIELDED)
Serializer.addSchema(IACMessageType.TransactionSignRequest, { schema: unsignedTransactionTezos }, SubProtocolSymbols.XTZ_BTC)
Serializer.addSchema(IACMessageType.TransactionSignRequest, { schema: unsignedTransactionTezos }, SubProtocolSymbols.XTZ_ETHTZ)
Serializer.addSchema(IACMessageType.TransactionSignRequest, { schema: unsignedTransactionTezos }, SubProtocolSymbols.XTZ_KUSD)
Serializer.addSchema(IACMessageType.TransactionSignRequest, { schema: unsignedTransactionTezos }, SubProtocolSymbols.XTZ_KT)
Serializer.addSchema(IACMessageType.TransactionSignRequest, { schema: unsignedTransactionTezos }, SubProtocolSymbols.XTZ_USD)
Serializer.addSchema(IACMessageType.TransactionSignRequest, { schema: unsignedTransactionSubstrate }, MainProtocolSymbols.POLKADOT)
Serializer.addSchema(IACMessageType.TransactionSignRequest, { schema: unsignedTransactionSubstrate }, MainProtocolSymbols.KUSAMA)
Serializer.addSchema(IACMessageType.TransactionSignRequest, { schema: unsignedTransactionSubstrate }, MainProtocolSymbols.MOONBASE)
Serializer.addSchema(IACMessageType.TransactionSignRequest, { schema: unsignedTransactionSubstrate }, MainProtocolSymbols.MOONRIVER)
Serializer.addSchema(IACMessageType.TransactionSignResponse, { schema: signedTransactionAeternity }, MainProtocolSymbols.AE)
Serializer.addSchema(IACMessageType.TransactionSignResponse, { schema: signedTransactionBitcoin }, MainProtocolSymbols.BTC)
Serializer.addSchema(IACMessageType.TransactionSignResponse, { schema: signedTransactionBitcoin }, MainProtocolSymbols.GRS)
Serializer.addSchema(IACMessageType.TransactionSignResponse, { schema: signedTransactionCosmos }, MainProtocolSymbols.COSMOS)
Serializer.addSchema(IACMessageType.TransactionSignResponse, { schema: signedTransactionEthereum }, MainProtocolSymbols.ETH)
Serializer.addSchema(IACMessageType.TransactionSignResponse, { schema: signedTransactionEthereum }, SubProtocolSymbols.ETH_ERC20)
Serializer.addSchema(IACMessageType.TransactionSignResponse, { schema: signedTransactionTezos }, MainProtocolSymbols.XTZ)
Serializer.addSchema(IACMessageType.TransactionSignResponse, { schema: signedTransactionTezosSapling }, MainProtocolSymbols.XTZ_SHIELDED)
Serializer.addSchema(IACMessageType.TransactionSignResponse, { schema: signedTransactionTezos }, SubProtocolSymbols.XTZ_BTC)
Serializer.addSchema(IACMessageType.TransactionSignResponse, { schema: signedTransactionTezos }, SubProtocolSymbols.XTZ_ETHTZ)
Serializer.addSchema(IACMessageType.TransactionSignResponse, { schema: signedTransactionTezos }, SubProtocolSymbols.XTZ_KUSD)
Serializer.addSchema(IACMessageType.TransactionSignResponse, { schema: signedTransactionTezos }, SubProtocolSymbols.XTZ_KT)
Serializer.addSchema(IACMessageType.TransactionSignResponse, { schema: signedTransactionTezos }, SubProtocolSymbols.XTZ_USD)
Serializer.addSchema(IACMessageType.TransactionSignResponse, { schema: signedTransactionSubstrate }, MainProtocolSymbols.POLKADOT)
Serializer.addSchema(IACMessageType.TransactionSignResponse, { schema: signedTransactionSubstrate }, MainProtocolSymbols.KUSAMA)
Serializer.addSchema(IACMessageType.TransactionSignResponse, { schema: signedTransactionSubstrate }, MainProtocolSymbols.MOONBASE)
Serializer.addSchema(IACMessageType.TransactionSignResponse, { schema: signedTransactionSubstrate }, MainProtocolSymbols.MOONRIVER) | the_stack |
import {AsyncValue} from './async-value';
import {ExternalsValidator} from './externals-validator';
import {
FeatureServiceConsumerDefinition,
FeatureServiceProviderDefinition,
FeatureServiceRegistry,
FeatureServices,
SharedFeatureService,
} from './feature-service-registry';
import * as Messages from './internal/feature-app-manager-messages';
import {isFeatureAppModule} from './internal/is-feature-app-module';
import {Logger} from './logger';
export interface FeatureAppEnvironment<
TFeatureServices extends FeatureServices,
TConfig
> {
/**
* An object of required Feature Services that are semver-compatible with the
* declared dependencies in the Feature App definition.
*/
readonly featureServices: TFeatureServices;
/**
* A config object that is provided by the integrator.
*/
readonly config: TConfig | undefined;
/**
* The ID that the integrator has assigned to the Feature App instance.
*/
readonly featureAppId: string;
/**
* The name that the integrator might have assigned to the Feature App.
*/
readonly featureAppName: string | undefined;
/**
* The absolute or relative base URL of the Feature App's assets and/or BFF.
*/
readonly baseUrl: string | undefined;
/**
* If this callback is defined, a short-lived Feature App can call this
* function when it has completed its task. The Integrator (or parent Feature
* App) can then decide to e.g. unmount the Feature App.
*/
readonly done?: () => void;
}
export interface FeatureAppDefinition<
TFeatureApp,
TFeatureServices extends FeatureServices = FeatureServices,
TConfig = unknown
> extends FeatureServiceConsumerDefinition {
readonly ownFeatureServiceDefinitions?: FeatureServiceProviderDefinition<
SharedFeatureService
>[];
create(env: FeatureAppEnvironment<TFeatureServices, TConfig>): TFeatureApp;
}
/**
* @param url A URL pointing to a [[FeatureAppDefinition]] bundle in a module
* format compatible with the module loader.
*
* @param moduleType The module type of the [[FeatureAppDefinition]] bundle.
* This can be used to choose different loading strategies based on the module
* type of the Feature App.
*/
export type ModuleLoader = (
url: string,
moduleType?: string
) => Promise<unknown>;
export interface FeatureAppScope<TFeatureApp> {
readonly featureApp: TFeatureApp;
/**
* When the `FeatureAppScope` is not needed anymore, e.g. the Feature App is
* unmounted, `release` must be called. When all scopes for a Feature App ID
* have been released, the Feature App instance is destroyed.
*/
release(): void;
}
export interface FeatureAppScopeOptions<
TFeatureServices extends FeatureServices,
TConfig
> {
/**
* The Feature App's name. In contrast to the `featureAppId`, the name must
* not be unique. It can be used by required Feature Services for display
* purposes, logging, looking up Feature App configuration meta data, etc.
*/
readonly featureAppName?: string;
/**
* The absolute or relative base URL of the Feature App's assets and/or BFF.
*/
readonly baseUrl?: string;
/**
* A config object that is intended for a specific Feature App instance.
*/
readonly config?: TConfig;
/**
* A callback that is called before the Feature App is created.
*/
readonly beforeCreate?: (
env: FeatureAppEnvironment<TFeatureServices, TConfig>
) => void;
/**
* A callback that is passed to the Feature App's `create` method. A
* short-lived Feature App can call this function when it has completed its
* task. The Integrator (or parent Feature App) can then decide to e.g.
* unmount the Feature App.
*/
readonly done?: () => void;
}
export interface FeatureAppManagerOptions {
/**
* For the `FeatureAppManager` to be able to load Feature Apps from a remote
* location, a module loader must be provided. This can either be one of the
* module loaders that are provided by @feature-hub, i.e.
* `@feature-hub/module-loader-amd`, `@feature-hub/module-loader-federation`,
* and `@feature-hub/module-loader-commonjs`, or a custom loader.
*/
readonly moduleLoader?: ModuleLoader;
/**
* When using a [[moduleLoader]], it might make sense to validate
* external dependencies that are required by Feature Apps against the
* shared dependencies that are provided by the integrator. This makes it
* possible that an error is already thrown when creating a Feature App with
* incompatible external dependencies, and thus enables early feedback as to
* whether a Feature App is compatible with the integration environment.
*/
readonly externalsValidator?: ExternalsValidator;
/**
* A custom logger that shall be used instead of `console`.
*/
readonly logger?: Logger;
}
type FeatureAppId = string;
interface FeatureAppRetainer<TFeatureApp> {
readonly featureApp: TFeatureApp;
retain(): void;
release(): void;
}
/**
* The `FeatureAppManager` manages the lifecycle of Feature Apps.
*/
export class FeatureAppManager {
private readonly asyncFeatureAppDefinitions = new Map<
string,
AsyncValue<FeatureAppDefinition<unknown>>
>();
private readonly featureAppDefinitionsWithRegisteredOwnFeatureServices = new WeakSet<
FeatureAppDefinition<unknown>
>();
private readonly featureAppRetainers = new Map<
FeatureAppId,
FeatureAppRetainer<unknown>
>();
private readonly logger: Logger;
public constructor(
private readonly featureServiceRegistry: FeatureServiceRegistry,
private readonly options: FeatureAppManagerOptions = {}
) {
this.logger = options.logger || console;
}
/**
* Load a [[FeatureAppDefinition]] using the module loader the
* [[FeatureAppManager]] was initilized with.
*
* @throws Throws an error if no module loader was provided on initilization.
*
* @param url A URL pointing to a [[FeatureAppDefinition]] bundle in a module
* format compatible with the module loader.
*
* @param moduleType The module type of the [[FeatureAppDefinition]] bundle.
* This value can be used by the provided
* [[FeatureAppManagerOptions.moduleLoader]].
*
* @returns An [[AsyncValue]] containing a promise that resolves with the
* loaded [[FeatureAppDefinition]]. If called again with the same URL it
* returns the same [[AsyncValue]]. The promise rejects when loading fails, or
* when the loaded bundle doesn't export a [[FeatureAppDefinition]] as
* default.
*/
public getAsyncFeatureAppDefinition(
url: string,
moduleType?: string
): AsyncValue<FeatureAppDefinition<unknown>> {
const key = `${url}${moduleType}`;
let asyncFeatureAppDefinition = this.asyncFeatureAppDefinitions.get(key);
if (!asyncFeatureAppDefinition) {
asyncFeatureAppDefinition = this.createAsyncFeatureAppDefinition(
url,
moduleType
);
this.asyncFeatureAppDefinitions.set(key, asyncFeatureAppDefinition);
}
return asyncFeatureAppDefinition;
}
/**
* Create a [[FeatureAppScope]] which includes validating externals, binding
* all available Feature Service dependencies, and calling the `create` method
* of the [[FeatureAppDefinition]].
*
* @throws Throws an error if Feature Services that the
* [[FeatureAppDefinition]] provides with its `ownFeatureServices` key fail to
* be registered.
* @throws Throws an error if the required externals can't be satisfied.
* @throws Throws an error if the required Feature Services can't be
* satisfied.
* @throws Throws an error the [[FeatureAppDefinition]]'s `create` method
* throws.
*
* @param featureAppID The ID of the Feature App to create a scope for.
* @param featureAppDefinition The definition of the Feature App to create a
* scope for.
*
* @returns A [[FeatureAppScope]] for the provided Feature App ID and
* [[FeatureAppDefinition]]. A new scope is created for every call of
* `createFeatureAppScope`, even with the same ID and definiton.
*/
public createFeatureAppScope<
TFeatureApp,
TFeatureServices extends FeatureServices = FeatureServices,
TConfig = unknown
>(
featureAppId: string,
featureAppDefinition: FeatureAppDefinition<
TFeatureApp,
TFeatureServices,
TConfig
>,
options: FeatureAppScopeOptions<TFeatureServices, TConfig> = {}
): FeatureAppScope<TFeatureApp> {
const featureAppRetainer = this.getFeatureAppRetainer<
TFeatureApp,
TFeatureServices,
TConfig
>(featureAppId, featureAppDefinition, options);
let released = false;
return {
featureApp: featureAppRetainer.featureApp,
release: () => {
if (released) {
this.logger.warn(
`The Feature App with the ID ${JSON.stringify(
featureAppId
)} has already been released for this scope.`
);
} else {
released = true;
featureAppRetainer.release();
}
},
};
}
/**
* Preload a [[FeatureAppDefinition]] using the module loader the
* [[FeatureAppManager]] was initilized with. Useful before hydration of a
* server rendered page to avoid render result mismatch between client and
* server due missing [[FeatureAppDefinition]]s.
*
* @throws Throws an error if no module loader was provided on initilization.
*
* @param url A URL pointing to a [[FeatureAppDefinition]] bundle in a module
* format compatible with the module loader.
*
* @param moduleType The module type of the [[FeatureAppDefinition]] bundle.
* This value can be used by the provided
* [[FeatureAppManagerOptions.moduleLoader]].
*/
public async preloadFeatureApp(
url: string,
moduleType?: string
): Promise<void> {
await this.getAsyncFeatureAppDefinition(url, moduleType).promise;
}
private createAsyncFeatureAppDefinition(
url: string,
moduleType?: string
): AsyncValue<FeatureAppDefinition<unknown>> {
const {moduleLoader: loadModule} = this.options;
if (!loadModule) {
throw new Error('No module loader provided.');
}
return new AsyncValue(
loadModule(url, moduleType).then((featureAppModule) => {
if (!isFeatureAppModule(featureAppModule)) {
throw new Error(
Messages.invalidFeatureAppModule(
url,
moduleType,
this.options.moduleLoader
)
);
}
this.logger.info(
`The Feature App module at the url ${JSON.stringify(
url
)} has been successfully loaded.`
);
return featureAppModule.default;
})
);
}
private registerOwnFeatureServices(
featureAppId: string,
featureAppDefinition: FeatureAppDefinition<unknown>
): void {
if (
this.featureAppDefinitionsWithRegisteredOwnFeatureServices.has(
featureAppDefinition
)
) {
return;
}
if (featureAppDefinition.ownFeatureServiceDefinitions) {
this.featureServiceRegistry.registerFeatureServices(
featureAppDefinition.ownFeatureServiceDefinitions,
featureAppId
);
}
this.featureAppDefinitionsWithRegisteredOwnFeatureServices.add(
featureAppDefinition
);
}
private getFeatureAppRetainer<
TFeatureApp,
TFeatureServices extends FeatureServices = FeatureServices,
TConfig = unknown
>(
featureAppId: string,
featureAppDefinition: FeatureAppDefinition<
TFeatureApp,
TFeatureServices,
TConfig
>,
options: FeatureAppScopeOptions<TFeatureServices, TConfig>
): FeatureAppRetainer<TFeatureApp> {
let featureAppRetainer = this.featureAppRetainers.get(featureAppId);
if (featureAppRetainer) {
featureAppRetainer.retain();
} else {
this.registerOwnFeatureServices(featureAppId, featureAppDefinition);
featureAppRetainer = this.createFeatureAppRetainer(
featureAppDefinition,
featureAppId,
options
);
}
return featureAppRetainer as FeatureAppRetainer<TFeatureApp>;
}
private createFeatureAppRetainer<
TFeatureApp,
TFeatureServices extends FeatureServices,
TConfig
>(
featureAppDefinition: FeatureAppDefinition<
TFeatureApp,
TFeatureServices,
TConfig
>,
featureAppId: string,
options: FeatureAppScopeOptions<TFeatureServices, TConfig>
): FeatureAppRetainer<TFeatureApp> {
this.validateExternals(featureAppDefinition);
const {featureAppName, baseUrl, beforeCreate, config, done} = options;
const binding = this.featureServiceRegistry.bindFeatureServices(
featureAppDefinition,
featureAppId,
featureAppName
);
const env: FeatureAppEnvironment<TFeatureServices, TConfig> = {
baseUrl,
config,
featureAppId,
featureAppName,
featureServices: binding.featureServices as TFeatureServices,
done,
};
if (beforeCreate) {
beforeCreate(env);
}
const featureApp = featureAppDefinition.create(env);
this.logger.info(
`The Feature App with the ID ${JSON.stringify(
featureAppId
)} has been successfully created.`
);
let retainCount = 1;
const featureAppRetainer: FeatureAppRetainer<TFeatureApp> = {
featureApp,
retain: () => {
retainCount += 1;
},
release: () => {
retainCount -= 1;
if (retainCount === 0) {
this.featureAppRetainers.delete(featureAppId);
binding.unbind();
}
},
};
this.featureAppRetainers.set(featureAppId, featureAppRetainer);
return featureAppRetainer;
}
private validateExternals(
featureAppDefinition: FeatureServiceConsumerDefinition
): void {
const {externalsValidator} = this.options;
if (!externalsValidator) {
return;
}
const {dependencies} = featureAppDefinition;
if (dependencies && dependencies.externals) {
externalsValidator.validate(dependencies.externals);
}
}
} | the_stack |
import { ExtensionContext, workspace } from "vscode";
import * as vscode from "vscode";
import {
IFullRender,
renderLevels,
getFullFileStats,
tabsIntoSpaces,
findLineZeroAndInLineIndexZero,
} from "./utils";
import { doubleWidthCharsReg } from "./helpers/regex-main";
import DocumentDecorationManager from "./bracketAlgos/documentDecorationManager";
import EventEmitter = require("events");
import {
applyAllBlockmanSettings,
AdvancedColoringFields,
} from "./settingsManager";
import { colorCombos } from "./colors";
import {
getLastColIndexForLineWithColorDecSpaces,
junkDecors3dArr,
notYetDisposedDecsObject,
nukeAllDecs,
nukeJunkDecorations,
selectFocusedBlock,
updateRender,
} from "./utils2";
const iiGlobal = "blockman_data_iicounter";
const iiGlobal2 = "blockman_data_iicounter2";
const iiGlobal3 = "blockman_data_iicounter3";
const iiGlobal4OnOffAR = "blockman_data_onOffStateAfterRestart";
const iiGlobal5OnOff = "blockman_data_onOffState";
const iiGlobal6AutoShowHideIndentGuides =
"blockman_data_autoShowHideIndentGuides";
let isMac = false;
let osChecked = false;
if (!osChecked) {
try {
// console.log("start of node os check");
const os = require("os"); // Comes with node.js
const myOS: string = os.type().toLowerCase();
const macCheck = myOS === "darwin";
if (macCheck === true) {
isMac = macCheck;
}
osChecked = true;
// console.log("end of node os check");
} catch (err) {
console.log(`Maybe error of: require("os")`);
console.log(err);
}
}
if (!osChecked) {
try {
// console.log("start of web os check");
// @ts-ignore
const macCheck =
// @ts-ignore
navigator.userAgent.toLowerCase().indexOf("mac") !== -1;
console.log("macCheck:", macCheck);
if (macCheck === true) {
isMac = macCheck;
}
osChecked = true;
// console.log("end of web os check");
} catch (err) {
console.log(`Maybe error of: window.navigator.userAgent`);
console.log(err);
}
}
console.log("isMac is:", isMac);
console.log("osChecked:", osChecked);
// const GOLDEN_LINE_HEIGHT_RATIO = platform.isMacintosh ? 1.5 : 1.35;
const GOLDEN_LINE_HEIGHT_RATIO = isMac ? 1.5 : 1.35;
const MINIMUM_LINE_HEIGHT = 8;
const stateHolder: {
myState?: vscode.Memento & {
setKeysForSync(keys: string[]): void;
};
} = {
myState: undefined,
};
export let bracketManager: DocumentDecorationManager | undefined | null;
// colorCombos.forEach((combo) => {
// combo.focusedBlock = makeGradientNotation(combo.focusedBlock);
// combo.onEachDepth = combo.onEachDepth.map((color) =>
// makeGradientNotation(color),
// );
// });
const classicDark1Combo = colorCombos.find(
(x) => x.name === "Classic Dark 1 (Gradients)",
)!;
const bigVars = {
currColorCombo: classicDark1Combo,
};
export const glo = {
isOn: true,
nominalLineHeight: 1,
currZoomLevel: 0, // zero means original, 1 means plus 10%, 2 means plus 20%........
eachCharFrameHeight: 1, // (px) no more needed, so before we remove it, it will be just 1,
eachCharFrameWidth: 1, // (px) no more needed, so before we remove it, it will be just 1,
letterSpacing: 0, // (px)
maxDepth: 9, // (as minus one) -2 -> no blocks, -1 -> ground block, 0 -> first depth blocks, and so on...
enableFocus: true,
renderIncBeforeAfterVisRange: 20, // 2-3 is minimal
renderTimerForInit: 50, // ms
renderTimerForChange: 1200, // ms
renderTimerForFocus: 200, // ms
renderTimerForScroll: 100, // ms
analyzeCurlyBrackets: true,
analyzeSquareBrackets: false,
analyzeRoundBrackets: false,
analyzeTags: true,
analyzeIndentDedentTokens: true,
renderInSingleLineAreas: false,
borderSize: 1,
borderRadius: 5,
coloring: {
onEachDepth: bigVars.currColorCombo.onEachDepth,
border: bigVars.currColorCombo.border,
borderOfDepth0: bigVars.currColorCombo.borderOfDepth0,
focusedBlock: bigVars.currColorCombo.focusedBlock,
borderOfFocusedBlock: bigVars.currColorCombo.borderOfFocusedBlock,
advanced: {
forBorders: [] as {
priority: number;
sequence: string[];
kind: AdvancedColoringFields;
}[],
forBackgrounds: [] as {
priority: number;
sequence: string[];
kind: AdvancedColoringFields;
}[],
},
},
colorDecoratorsInStyles: true,
trySupportDoubleWidthChars: false, // for Chinese characters and possibly others too
blackListOfFileFormats: ["plaintext", "markdown"],
// maxHistoryOfParsedTabs: 7,
};
const calcLineHeight = (): number => {
return glo.nominalLineHeight * (1 + glo.currZoomLevel * 0.1);
};
const updateBlockmanLineHeightAndLetterSpacing = () => {
/**
* Determined from empirical observations.
*/
const editorConfig: any = workspace.getConfiguration("editor");
// console.log("editorConfig:", editorConfig);
let editorLineHeight: number = editorConfig.get("lineHeight");
const editorFontSize: number = editorConfig.get("fontSize");
if (editorLineHeight === 0) {
// 0 is the default
editorLineHeight = Math.round(
GOLDEN_LINE_HEIGHT_RATIO * editorFontSize,
); // fontSize is editor.fontSize
} else if (editorLineHeight < MINIMUM_LINE_HEIGHT) {
editorLineHeight = editorLineHeight * editorFontSize;
}
glo.nominalLineHeight = editorLineHeight;
glo.eachCharFrameHeight = calcLineHeight();
// now letter spacing:
const editorLetterSpacing: number = editorConfig.get("letterSpacing");
glo.letterSpacing = editorLetterSpacing;
};
// extention-wide GLOBALS _start_
export const oneCharNonLineBreakingWhiteSpaces = [" "];
export const oneCharLineBreaks = ["\n"];
export const allWhiteSpace = [
...oneCharNonLineBreakingWhiteSpaces,
...oneCharLineBreaks,
];
// export let eachCharFrameWidth = 10.8035; // px
// export let eachCharFrameHeight = 24.0; // px
// export let currMaxDepth = 4; // -1 -> no blocks, 0 -> entire file block, 1 -> first depth blocks, and so on...
// export let renderIncBeforeAfterVisRange = 7;
interface IFocusBlock {
depth: number;
indexInTheDepth: number;
}
export interface IInLineInDepthDecorsRefs {
mainBody: vscode.TextEditorDecorationType | null;
leftLineOfOpening: vscode.TextEditorDecorationType | "f" | null; // f -> explicit false, not exist
rightLineOfClosing: vscode.TextEditorDecorationType | "f" | null; // f -> explicit false, not exist
}
// maybe the queue not in order
export type TyInLineInDepthInQueueInfo =
| {
// queue and blockIndex related, you know...
lineZero: number;
depthIndex: number;
// sameLineQueueIndex: number;
inDepthBlockIndex: number;
decorsRefs: IInLineInDepthDecorsRefs;
divType?: "m"; // middle
midStartLine?: number;
midEndLine?: number;
}
| undefined;
export type TyDepthDecInfo = TyInLineInDepthInQueueInfo[];
export type TyLineDecInfo = TyDepthDecInfo[];
export type TyOneFileEditorDecInfo = TyLineDecInfo[];
export interface IEditorInfo {
editorRef: vscode.TextEditor;
needToAnalyzeFile: boolean;
textLinesMap: number[];
decors: TyOneFileEditorDecInfo; // by depth !!!!!!!!!!!
upToDateLines: {
upEdge: number;
lowEdge: number;
};
focusDuo: {
currIsFreezed?: true | false;
curr: IFocusBlock | null;
prev: IFocusBlock | null;
};
focusTreePath: number[] | null; // number is the indexInDepth for each depth from depth0 to focus
innersFromFocus: (number[] | null)[] | null; // number is the indexInDepth for each depth from depth0 to focus [excl] as null and from focus [incl] to maxDepth as number[]
timerForDo: any;
renderingInfoForFullFile: IFullRender | undefined;
// focusedBlock: { depth: number; index: number } | null;
monoText: string;
colorDecoratorsArr: {
cDLineZero: number;
cDCharZeroInDoc: number;
cDCharZeroInMonoText: number;
cDGlobalIndexZeroInMonoText: number;
}[];
}
// export const maxNumberOfControlledEditors = 5;
export let infosOfControlledEditors: IEditorInfo[] = [];
// extention-wide GLOBALS _end_
export const dropTextLinesMapForEditor = (editor: vscode.TextEditor) => {
for (
let edInfoIndex = 0;
edInfoIndex < infosOfControlledEditors.length;
edInfoIndex += 1
) {
const currEdInfo = infosOfControlledEditors[edInfoIndex];
if (currEdInfo.editorRef === editor) {
currEdInfo.textLinesMap = [];
break;
}
}
};
export const haveSameDocs = (
ed1: vscode.TextEditor,
ed2: vscode.TextEditor,
) => {
if (ed1 === ed2) {
return true;
}
if (ed1.document === ed2.document) {
return true;
}
if (ed1.document.uri === ed2.document.uri) {
return true;
}
if (ed1.document.uri.fsPath === ed2.document.uri.fsPath) {
return true;
}
if (ed1.document.uri.path === ed2.document.uri.path) {
return true;
}
return false;
};
export const areSameDocs = (
d1: vscode.TextDocument,
d2: vscode.TextDocument,
) => {
if (d1 === d2) {
return true;
}
if (d1.uri === d2.uri) {
return true;
}
if (d1.uri.fsPath === d2.uri.fsPath) {
return true;
}
if (d1.uri.path === d2.uri.path) {
return true;
}
return false;
};
export const updateAllControlledEditors = ({
alsoStillVisibleAndHist,
}: {
alsoStillVisibleAndHist?: boolean;
}) => {
const supMode = "init";
const visibleEditors = vscode.window.visibleTextEditors;
const infosOfStillVisibleEditors = infosOfControlledEditors.filter(
(edInfo) => visibleEditors.includes(edInfo.editorRef),
);
// nukeJunkDecorations();
if (infosOfStillVisibleEditors.length === 0) {
nukeJunkDecorations();
nukeAllDecs();
}
const stillVisibleEditors = infosOfStillVisibleEditors.map(
(edInfo) => edInfo.editorRef,
);
const newEditors = visibleEditors.filter(
(editor) => !stillVisibleEditors.includes(editor),
);
const infosOfNewEditors: IEditorInfo[] = [];
newEditors.forEach((editor) => {
infosOfNewEditors.push({
editorRef: editor,
needToAnalyzeFile: true,
textLinesMap: [],
decors: [],
upToDateLines: {
upEdge: -1,
lowEdge: -1,
},
focusDuo: {
curr: null,
prev: null,
},
timerForDo: null,
focusTreePath: null,
innersFromFocus: null, // not from focus but from d0 nulls and then number[] from focus
renderingInfoForFullFile: undefined,
monoText: "",
colorDecoratorsArr: [],
});
});
let infosOfDisposedEditors = infosOfControlledEditors.filter(
(edInfo) => !stillVisibleEditors.includes(edInfo.editorRef),
);
infosOfDisposedEditors.forEach((edInfo) => {
junkDecors3dArr.push(edInfo.decors);
});
const finalArrOfInfos = [
...infosOfStillVisibleEditors,
...infosOfNewEditors,
];
infosOfControlledEditors = finalArrOfInfos;
infosOfNewEditors.forEach((editorInfo: IEditorInfo) => {
editorInfo.needToAnalyzeFile = true;
updateRender({ editorInfo, timer: glo.renderTimerForInit });
});
if (alsoStillVisibleAndHist) {
infosOfStillVisibleEditors.forEach((editorInfo: IEditorInfo) => {
editorInfo.upToDateLines.upEdge = -1;
editorInfo.upToDateLines.lowEdge = -1;
editorInfo.needToAnalyzeFile = true;
updateRender({ editorInfo, timer: glo.renderTimerForInit });
});
}
};
export const updateControlledEditorsForOneDoc = ({
editor,
doc,
supMode,
}: {
editor?: vscode.TextEditor;
doc?: vscode.TextDocument;
supMode: "reparse" | "focus" | "scroll";
}) => {
let thisTimer = glo.renderTimerForChange;
if (supMode === "scroll") {
thisTimer = glo.renderTimerForScroll;
} else if (supMode === "focus") {
thisTimer = glo.renderTimerForFocus;
}
let thisDoc: vscode.TextDocument | undefined;
if (doc) {
thisDoc = doc;
} else if (editor) {
thisDoc = editor.document;
} else {
console.log("both -> doc and editor are falsy");
return;
}
infosOfControlledEditors.forEach((editorInfo: IEditorInfo) => {
if (
(thisDoc as vscode.TextDocument) === editorInfo.editorRef.document
// areSameDocs(thisDoc!, editorInfo.editorRef.document)
) {
if (
["scroll", "focus"].includes(supMode) &&
editorInfo.needToAnalyzeFile
) {
// !!! VERY IMPORTANT for optimization
return; // it's the same as 'continue' for 'for/while' loop.
}
// console.log("kok", supMode);
updateRender({ editorInfo, timer: thisTimer, supMode });
}
});
};
const setLightColorComboIfLightTheme = () => {
const currVscodeThemeKind = vscode.window.activeColorTheme.kind;
if (currVscodeThemeKind === vscode.ColorThemeKind.Light) {
// glo.coloring.
workspace
.getConfiguration("blockman")
.update("n04ColorComboPreset", "Classic Light (Gradients)", 1);
}
};
const setColorDecoratorsBool = () => {
const vsConfigOfEditors = vscode.workspace.getConfiguration("editor");
const colorDecoratorsBool: boolean | undefined =
vsConfigOfEditors.get("colorDecorators");
// console.log(vsConfigOfEditors, colorDecoratorsBool);
if (colorDecoratorsBool === true || colorDecoratorsBool === false) {
glo.colorDecoratorsInStyles = colorDecoratorsBool;
}
};
const setUserwideIndentGuides = (myBool: boolean) => {
const st = stateHolder.myState;
if (st) {
const autoShowHideIndentGuides = st.get(
iiGlobal6AutoShowHideIndentGuides,
);
if (autoShowHideIndentGuides === "off") {
return;
}
}
const indent1 = (boo: boolean) => {
try {
// old API
vscode.workspace
.getConfiguration()
.update("editor.renderIndentGuides", myBool, 1); // 1 means Userwide
} catch (err) {
//
}
};
const indent2 = (boo: boolean) => {
try {
vscode.workspace
.getConfiguration()
.update("editor.guides.indentation", myBool, 1); // 1 means Userwide
} catch (err) {
//
}
};
const indent3 = (boo: boolean) => {
try {
vscode.workspace
.getConfiguration()
.update("editor.guides.bracketPairs", myBool, 1); // 1 means Userwide
} catch (err) {
//
}
};
indent1(myBool);
indent2(myBool);
indent3(myBool);
// vscode.workspace
// .getConfiguration()
// .update("editor.highlightActiveIndentGuide", myBool, 1); // 1 means Userwide
};
interface IConfigOfVscode {
inlayHints: boolean; // "editor.inlayHints.enabled"
lineHighlightBackground?: string; // "workbench.colorCustomizations" -> "editor.lineHighlightBackground"
lineHighlightBorder?: string; // "workbench.colorCustomizations" -> "editor.lineHighlightBorder"
editorWordWrap?: "on" | "off"; // "editor.wordWrap"
diffEditorWordWrap?: "on" | "off"; // "diffEditor.wordWrap"
// markdownEditorWordWrap?: string; // "[markdown]_editor.wordWrap"
renderIndentGuides?: boolean; // "editor.renderIndentGuides" - old API of indent guides
guidesIndentation: boolean; // "editor.guides.indentation" - new API of indent guides
guidesBracketPairs: boolean; // "editor.guides.bracketPairs" - // new advanced indent guides
// highlightActiveIndentGuide?: boolean; // "editor.highlightActiveIndentGuide"
[key: string]: string | boolean | undefined;
}
// for archive
// const configOfVscodeBeforeBlockman: IConfigOfVscode = {
// renderIndentGuides: true,
// };
// for blockman
const configOfVscodeWithBlockman: IConfigOfVscode = {
inlayHints: false,
lineHighlightBackground: "#1073cf2d",
lineHighlightBorder: "#9fced11f",
editorWordWrap: "off",
diffEditorWordWrap: "off",
renderIndentGuides: false,
guidesIndentation: false,
guidesBracketPairs: false,
};
// let vvvv = vscode.workspace.getConfiguration().get("editor.wordWrap");
const setUserwideConfigOfVscode = (userwideConfig: IConfigOfVscode) => {
let vscodeColorConfig: any = vscode.workspace
.getConfiguration("workbench")
.get("colorCustomizations");
vscode.workspace.getConfiguration("workbench").update(
"colorCustomizations",
{
...vscodeColorConfig,
"editor.lineHighlightBackground":
userwideConfig.lineHighlightBackground,
"editor.lineHighlightBorder": userwideConfig.lineHighlightBorder,
},
1,
);
vscode.workspace
.getConfiguration()
.update("editor.wordWrap", userwideConfig.editorWordWrap, 1);
vscode.workspace
.getConfiguration()
.update("diffEditor.wordWrap", userwideConfig.diffEditorWordWrap, 1);
// let vscodeMarkdownConfig: any = vscode.workspace
// .getConfiguration()
// .get("[markdown]");
// vscode.workspace.getConfiguration().update(
// "[markdown]",
// {
// ...vscodeMarkdownConfig,
// "editor.wordWrap": userwideConfig.markdownEditorWordWrap,
// },
// 1,
// );
if (userwideConfig.renderIndentGuides !== undefined) {
setUserwideIndentGuides(userwideConfig.guidesBracketPairs);
}
};
// maybe not needed anymore
const importantMessage = () => {
vscode.window.showInformationMessage(`blaaaa`, { modal: true });
};
const softRestart = () => {
nukeAllDecs();
nukeJunkDecorations();
infosOfControlledEditors = [];
updateAllControlledEditors({ alsoStillVisibleAndHist: true });
};
let settingsChangeTimout: NodeJS.Timeout | undefined;
export function activate(context: ExtensionContext) {
stateHolder.myState = context.globalState;
workspace.getConfiguration("blockman").update("n01LineHeight", 0, 1); // TODO: later
// const onOff: boolean | undefined =
// context.globalState.get("blockman_data_on");
// if (onOff !== undefined) {
// glo.isOn = onOff;
// } else {
// context.globalState.update("blockman_data_on", true);
// glo.isOn = true;
// }
updateBlockmanLineHeightAndLetterSpacing();
// adjustVscodeUserConfig();
setColorDecoratorsBool();
bracketManager = new DocumentDecorationManager();
vscode.extensions.onDidChange(() => restart());
// console.log("all Config:", vscode.workspace.getConfiguration()); // lineHighlightBorder
// let bbqq = context.globalStorageUri;
if (stateHolder.myState) {
const st = stateHolder.myState;
const iicounter = st.get(iiGlobal);
const iicounter2 = st.get(iiGlobal2);
const iicounter3 = st.get(iiGlobal3);
const onOffStateAfterRestart = st.get(iiGlobal4OnOffAR);
const onOffState = st.get(iiGlobal5OnOff);
if (onOffState === "off" && onOffStateAfterRestart === "off") {
glo.isOn = false;
st.update(iiGlobal5OnOff, glo.isOn ? "on" : "off");
}
// console.log(iicounter);
if (iicounter === undefined) {
console.log("first activation 1");
// collectVSCodeConfigArchive();
setUserwideConfigOfVscode(configOfVscodeWithBlockman);
setLightColorComboIfLightTheme();
st.update(iiGlobal, "1");
// console.log("iyo undefined, gaxda 1:", st.get(iiGlobal));
} else if (iicounter === "1") {
st.update(iiGlobal, "2");
// console.log("iyo 1, gaxda 2:", st.get(iiGlobal));
} else if (iicounter === "2") {
// console.log("aris 2:", st.get(iiGlobal));
// ----
}
if (iicounter2 === undefined) {
console.log("first activation 2");
vscode.workspace
.getConfiguration()
.update(
"editor.inlayHints.enabled",
configOfVscodeWithBlockman.inlayHints,
1,
);
st.update(iiGlobal2, "1");
} else if (iicounter2 === "1") {
st.update(iiGlobal2, "2");
//
} else if (iicounter2 === "2") {
//
}
if (iicounter3 === undefined) {
console.log("first activation 3");
vscode.workspace
.getConfiguration()
.update(
"editor.guides.indentation",
configOfVscodeWithBlockman.guidesIndentation,
1,
);
st.update(iiGlobal3, "1");
} else if (iicounter3 === "1") {
st.update(iiGlobal3, "2");
//
} else if (iicounter3 === "2") {
//-
}
}
if (glo.isOn) {
setUserwideIndentGuides(false);
}
// setLightColorComboIfLightTheme(); // not on every activation
applyAllBlockmanSettings();
context.subscriptions.push(
// vscode.commands.registerCommand(
// "bracket-pair-colorizer-2.expandBracketSelection",
// () => {
// const editor = window.activeTextEditor;
// if (!editor) {
// return;
// }
// documentDecorationManager.expandBracketSelection(editor);
// },
// ),
vscode.commands.registerCommand("blockman.helloWorld", () => {
console.log(
"Hello, I'm Blockman, a visual helper for software developers.",
);
vscode.window.showInformationMessage(
`Hello, I'm Blockman, a visual helper for software developers.`,
{ modal: false },
);
}),
vscode.commands.registerCommand("blockman.toggleEnableDisable", () => {
const st = stateHolder.myState;
if (glo.isOn) {
glo.isOn = false;
// context.globalState.update("blockman_data_on", false);
nukeAllDecs();
nukeJunkDecorations();
infosOfControlledEditors = [];
// setUserwideConfigOfVscode(configOfVscodeBeforeBlockman);
setUserwideIndentGuides(true);
} else {
glo.isOn = true;
// context.globalState.update("blockman_data_on", true);
// setUserwideConfigOfVscode(configOfVscodeWithBlockman);
setUserwideIndentGuides(false);
updateAllControlledEditors({ alsoStillVisibleAndHist: true });
}
if (st) {
st.update(iiGlobal5OnOff, glo.isOn ? "on" : "off");
}
}),
vscode.commands.registerCommand("blockman.toggleKeepOff", () => {
const st = stateHolder.myState;
if (st) {
const onOffStateAfterRestart = st.get(iiGlobal4OnOffAR);
let newAROnOffState =
onOffStateAfterRestart === "off" ? "on" : "off";
st.update(iiGlobal4OnOffAR, newAROnOffState);
if (newAROnOffState === "off") {
vscode.window.showInformationMessage(
`If you disable Blockman, it will still be disabled after restarting VSCode.`,
{ modal: false },
);
} else {
vscode.window.showInformationMessage(
`If you disable Blockman, it will be enabled after restarting VSCode`,
{ modal: false },
);
}
} else {
vscode.window.showInformationMessage(
`Something's wrong, context.globalState is falsy.`,
{ modal: false },
);
}
}),
vscode.commands.registerCommand(
"blockman.toggleDisableAutomaticShowHideIndentGuides",
() => {
const st = stateHolder.myState;
if (st) {
const autoShowHideIndentGuides = st.get(
iiGlobal6AutoShowHideIndentGuides,
);
let newVal =
autoShowHideIndentGuides === "off" ? "on" : "off";
st.update(iiGlobal6AutoShowHideIndentGuides, newVal);
if (newVal === "off") {
vscode.window.showInformationMessage(
`OK, Blockman will NOT change anything about indent guides.`,
{ modal: false },
);
} else {
vscode.window.showInformationMessage(
`Cool, Blockman will automatically show/hide indent guides.`,
{ modal: false },
);
}
} else {
vscode.window.showInformationMessage(
`Something's wrong, context.globalState is falsy.`,
{ modal: false },
);
}
},
),
vscode.commands.registerCommand("blockman.printLeak", () => {
console.log(notYetDisposedDecsObject.decs);
}),
// vscode.commands.registerCommand("blockman.zoomLineHeight", () => {
// glo.currZoomLevel += 1;
// glo.eachCharFrameHeight = calcLineHeight();
// updateAllControlledEditors({ alsoStillVisibleAndHist: true });
// }),
// vscode.commands.registerCommand("blockman.unzoomLineHeight", () => {
// glo.currZoomLevel -= 1;
// glo.eachCharFrameHeight = calcLineHeight();
// updateAllControlledEditors({ alsoStillVisibleAndHist: true });
// }),
vscode.commands.registerCommand(
"blockman.toggleTrySupportDoubleWidthChars",
() => {
glo.trySupportDoubleWidthChars =
!glo.trySupportDoubleWidthChars;
softRestart();
const isOn: string = glo.trySupportDoubleWidthChars
? "ON"
: "OFF";
vscode.window.showInformationMessage(
`Double-width char support (experimental) is ${isOn}`,
{ modal: false },
);
},
),
vscode.commands.registerCommand("blockman.toggleFreezeFocus", () => {
const thisEditor = vscode.window.activeTextEditor;
if (thisEditor) {
const thisEditorInfo = infosOfControlledEditors.find(
(x) => x.editorRef === thisEditor,
);
if (thisEditorInfo) {
const currFr = thisEditorInfo.focusDuo.currIsFreezed;
thisEditorInfo.focusDuo.currIsFreezed = !currFr;
}
}
}),
vscode.commands.registerCommand("blockman.selectFocused", () => {
selectFocusedBlock();
}),
workspace.onDidChangeConfiguration((event) => {
console.log("settings changed");
// if (
// event.affectsConfiguration("bracket-pair-colorizer-2") ||
// event.affectsConfiguration("editor.lineHeight") ||
// event.affectsConfiguration("editor.fontSize")
// ) {
// console.log(
// "all:",
// vscode.workspace
// .getConfiguration("editor")
// .get("lineHeight"),
// ); // lineHighlightBorder
// // restart();
// }
// if (event.affectsConfiguration("blockman")) { // sometimes cannot catch the change from the scope
updateBlockmanLineHeightAndLetterSpacing();
setColorDecoratorsBool();
// console.log("scrrr:", glo.renderTimerForScroll);
// updateAllControlledEditors({
// alsoUndisposed: true,
// });
// }
if (glo.isOn) {
if (settingsChangeTimout) {
clearTimeout(settingsChangeTimout);
}
settingsChangeTimout = setTimeout(() => {
applyAllBlockmanSettings(); // setTimeout is important because VSCode needs certain amount of time to update latest changes of settings.
updateAllControlledEditors({
alsoStillVisibleAndHist: true,
});
}, 500);
} else {
nukeAllDecs();
nukeJunkDecorations();
infosOfControlledEditors = [];
}
}),
vscode.window.onDidChangeTextEditorOptions((event) => {
if (!glo.isOn) {
return;
}
infosOfControlledEditors.forEach((editorInfo: IEditorInfo) => {
if (event.textEditor === editorInfo.editorRef) {
editorInfo.needToAnalyzeFile = true;
}
});
updateControlledEditorsForOneDoc({
editor: event.textEditor,
supMode: "reparse",
});
}),
vscode.window.onDidChangeVisibleTextEditors((event) => {
if (!glo.isOn) {
return;
}
const visEditors = event;
updateAllControlledEditors({});
}),
workspace.onDidChangeTextDocument((event) => {
if (!glo.isOn) {
return;
}
// console.log("araaaa nulze meti");
// return;
if (event.contentChanges.length > 0) {
// console.log("changed text");
const thisDoc = event.document;
infosOfControlledEditors.forEach((editorInfo: IEditorInfo) => {
if (thisDoc === editorInfo.editorRef.document) {
editorInfo.needToAnalyzeFile = true;
}
});
// console.log("chhhhhhhhhhhh:", glo.renderTimerForChange);
// console.log("reparse");
updateControlledEditorsForOneDoc({
doc: thisDoc,
supMode: "reparse",
});
}
}),
workspace.onDidOpenTextDocument((event) => {
// documentDecorationManager.onDidOpenTextDocument(event);
// setTimeout(() => {
// let eds = window.visibleTextEditors;
// console.log("eds-opennnnnnnn:", eds);
// }, 2000);
}),
vscode.window.onDidChangeTextEditorSelection((event) => {
const thisDoc = event.textEditor.document;
// console.log("focus");
// return;
if (!glo.isOn) {
return;
}
updateControlledEditorsForOneDoc({
doc: thisDoc,
supMode: "focus",
});
}),
vscode.window.onDidChangeTextEditorVisibleRanges((event) => {
// console.log("scroll");
// return;
if (!glo.isOn) {
return;
}
const thisEditor = event.textEditor;
updateControlledEditorsForOneDoc({
editor: thisEditor,
supMode: "scroll",
});
}),
vscode.window.onDidChangeActiveTextEditor((event) => {
// needToAnalyzeFile = true;
// let thisEditor = window.activeTextEditor;
// if (thisEditor) {
// updateRender({ thisEditor });
// }
}),
workspace.onDidCloseTextDocument((event) => {
if (bracketManager) {
bracketManager.onDidCloseTextDocument(event);
}
}),
);
// documentDecorationManager.updateAllDocuments();
// setTimeout(() => {
updateAllControlledEditors({});
// }, 5000);
function restart() {
// documentDecorationManager.Dispose();
// documentDecorationManager = new DocumentDecorationManager();
// documentDecorationManager.updateAllDocuments();
bracketManager?.Dispose();
bracketManager = new DocumentDecorationManager();
softRestart();
}
}
// tslint:disable-next-line:no-empty
export function deactivate() {} | the_stack |
import { Injectable } from '@angular/core';
import { CoreQuestionBehaviourDelegate, CoreQuestionQuestionWithAnswers } from '@features/question/services/behaviour-delegate';
import { CoreQuestionAnswerDBRecord } from '@features/question/services/database/question';
import { CoreQuestion, CoreQuestionQuestionParsed, CoreQuestionsAnswers } from '@features/question/services/question';
import { CoreSites } from '@services/sites';
import { CoreTimeUtils } from '@services/utils/time';
import { CoreUtils } from '@services/utils/utils';
import { makeSingleton, Translate } from '@singletons';
import { CoreLogger } from '@singletons/logger';
import { AddonModQuizAttemptDBRecord, ATTEMPTS_TABLE_NAME } from './database/quiz';
import { AddonModQuizAttemptWSData, AddonModQuizProvider, AddonModQuizQuizWSData } from './quiz';
/**
* Service to handle offline quiz.
*/
@Injectable({ providedIn: 'root' })
export class AddonModQuizOfflineProvider {
protected logger: CoreLogger;
constructor() {
this.logger = CoreLogger.getInstance('AddonModQuizOfflineProvider');
}
/**
* Classify the answers in questions.
*
* @param answers List of answers.
* @return Object with the questions, the keys are the slot. Each question contains its answers.
*/
classifyAnswersInQuestions(answers: CoreQuestionsAnswers): AddonModQuizQuestionsWithAnswers {
const questionsWithAnswers: AddonModQuizQuestionsWithAnswers = {};
// Classify the answers in each question.
for (const name in answers) {
const slot = CoreQuestion.getQuestionSlotFromName(name);
const nameWithoutPrefix = CoreQuestion.removeQuestionPrefix(name);
if (!questionsWithAnswers[slot]) {
questionsWithAnswers[slot] = {
answers: {},
prefix: name.substr(0, name.indexOf(nameWithoutPrefix)),
};
}
questionsWithAnswers[slot].answers[nameWithoutPrefix] = answers[name];
}
return questionsWithAnswers;
}
/**
* Given a list of questions with answers classified in it, returns a list of answers (including prefix in the name).
*
* @param questions Questions.
* @return Answers.
*/
extractAnswersFromQuestions(questions: AddonModQuizQuestionsWithAnswers): CoreQuestionsAnswers {
const answers: CoreQuestionsAnswers = {};
for (const slot in questions) {
const question = questions[slot];
for (const name in question.answers) {
answers[question.prefix + name] = question.answers[name];
}
}
return answers;
}
/**
* Get all the offline attempts in a certain site.
*
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with the offline attempts.
*/
async getAllAttempts(siteId?: string): Promise<AddonModQuizAttemptDBRecord[]> {
const db = await CoreSites.getSiteDb(siteId);
return db.getAllRecords(ATTEMPTS_TABLE_NAME);
}
/**
* Retrieve an attempt answers from site DB.
*
* @param attemptId Attempt ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with the answers.
*/
getAttemptAnswers(attemptId: number, siteId?: string): Promise<CoreQuestionAnswerDBRecord[]> {
return CoreQuestion.getAttemptAnswers(AddonModQuizProvider.COMPONENT, attemptId, siteId);
}
/**
* Retrieve an attempt from site DB.
*
* @param attemptId Attempt ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with the attempt.
*/
async getAttemptById(attemptId: number, siteId?: string): Promise<AddonModQuizAttemptDBRecord> {
const db = await CoreSites.getSiteDb(siteId);
return db.getRecord(ATTEMPTS_TABLE_NAME, { id: attemptId });
}
/**
* Retrieve an attempt from site DB.
*
* @param attemptId Attempt ID.
* @param siteId Site ID. If not defined, current site.
* @param userId User ID. If not defined, user current site's user.
* @return Promise resolved with the attempts.
*/
async getQuizAttempts(quizId: number, siteId?: string, userId?: number): Promise<AddonModQuizAttemptDBRecord[]> {
const site = await CoreSites.getSite(siteId);
return site.getDb().getRecords(ATTEMPTS_TABLE_NAME, { quizid: quizId, userid: userId || site.getUserId() });
}
/**
* Load local state in the questions.
*
* @param attemptId Attempt ID.
* @param questions List of questions.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when done.
*/
async loadQuestionsLocalStates(
attemptId: number,
questions: CoreQuestionQuestionParsed[],
siteId?: string,
): Promise<CoreQuestionQuestionParsed[]> {
await Promise.all(questions.map(async (question) => {
const dbQuestion = await CoreUtils.ignoreErrors(
CoreQuestion.getQuestion(AddonModQuizProvider.COMPONENT, attemptId, question.slot, siteId),
);
if (!dbQuestion) {
// Question not found.
return;
}
const state = CoreQuestion.getState(dbQuestion.state);
question.state = dbQuestion.state;
question.status = Translate.instant('core.question.' + state.status);
}));
return questions;
}
/**
* Process an attempt, saving its data.
*
* @param quiz Quiz.
* @param attempt Attempt.
* @param questions Object with the questions of the quiz. The keys should be the question slot.
* @param data Data to save.
* @param finish Whether to finish the quiz.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved in success, rejected otherwise.
*/
async processAttempt(
quiz: AddonModQuizQuizWSData,
attempt: AddonModQuizAttemptWSData,
questions: Record<number, CoreQuestionQuestionParsed>,
data: CoreQuestionsAnswers,
finish?: boolean,
siteId?: string,
): Promise<void> {
siteId = siteId || CoreSites.getCurrentSiteId();
const now = CoreTimeUtils.timestamp();
const db = await CoreSites.getSiteDb(siteId);
// Check if an attempt already exists. Return a new one if it doesn't.
let entry = await CoreUtils.ignoreErrors(this.getAttemptById(attempt.id, siteId));
if (entry) {
entry.timemodified = now;
entry.finished = finish ? 1 : 0;
} else {
entry = {
quizid: quiz.id,
userid: attempt.userid!,
id: attempt.id,
courseid: quiz.course,
timecreated: now,
attempt: attempt.attempt!,
currentpage: attempt.currentpage,
timemodified: now,
finished: finish ? 1 : 0,
};
}
// Save attempt in DB.
await db.insertRecord(ATTEMPTS_TABLE_NAME, entry);
// Attempt has been saved, now we need to save the answers.
await this.saveAnswers(quiz, attempt, questions, data, now, siteId);
}
/**
* Remove an attempt and its answers from local DB.
*
* @param attemptId Attempt ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when done.
*/
async removeAttemptAndAnswers(attemptId: number, siteId?: string): Promise<void> {
siteId = siteId || CoreSites.getCurrentSiteId();
const db = await CoreSites.getSiteDb(siteId);
await Promise.all([
CoreQuestion.removeAttemptAnswers(AddonModQuizProvider.COMPONENT, attemptId, siteId),
CoreQuestion.removeAttemptQuestions(AddonModQuizProvider.COMPONENT, attemptId, siteId),
db.deleteRecords(ATTEMPTS_TABLE_NAME, { id: attemptId }),
]);
}
/**
* Remove a question and its answers from local DB.
*
* @param attemptId Attempt ID.
* @param slot Question slot.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when finished.
*/
async removeQuestionAndAnswers(attemptId: number, slot: number, siteId?: string): Promise<void> {
siteId = siteId || CoreSites.getCurrentSiteId();
await Promise.all([
CoreQuestion.removeQuestion(AddonModQuizProvider.COMPONENT, attemptId, slot, siteId),
CoreQuestion.removeQuestionAnswers(AddonModQuizProvider.COMPONENT, attemptId, slot, siteId),
]);
}
/**
* Save an attempt's answers and calculate state for questions modified.
*
* @param quiz Quiz.
* @param attempt Attempt.
* @param questions Object with the questions of the quiz. The keys should be the question slot.
* @param answers Answers to save.
* @param timeMod Time modified to set in the answers. If not defined, current time.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when done.
*/
async saveAnswers(
quiz: AddonModQuizQuizWSData,
attempt: AddonModQuizAttemptWSData,
questions: Record<number, CoreQuestionQuestionParsed>,
answers: CoreQuestionsAnswers,
timeMod?: number,
siteId?: string,
): Promise<void> {
siteId = siteId || CoreSites.getCurrentSiteId();
timeMod = timeMod || CoreTimeUtils.timestamp();
const questionsWithAnswers: Record<number, CoreQuestionQuestionWithAnswers> = {};
const newStates: Record<number, string> = {};
// Classify the answers in each question.
for (const name in answers) {
const slot = CoreQuestion.getQuestionSlotFromName(name);
const nameWithoutPrefix = CoreQuestion.removeQuestionPrefix(name);
if (questions[slot]) {
if (!questionsWithAnswers[slot]) {
questionsWithAnswers[slot] = questions[slot];
questionsWithAnswers[slot].answers = {};
}
questionsWithAnswers[slot].answers![nameWithoutPrefix] = answers[name];
}
}
// First determine the new state of each question. We won't save the new state yet.
await Promise.all(Object.values(questionsWithAnswers).map(async (question) => {
const state = await CoreQuestionBehaviourDelegate.determineNewState(
quiz.preferredbehaviour!,
AddonModQuizProvider.COMPONENT,
attempt.id,
question,
quiz.coursemodule,
siteId,
);
// Check if state has changed.
if (state && state.name != question.state) {
newStates[question.slot] = state.name;
}
// Delete previously stored answers for this question.
await CoreQuestion.removeQuestionAnswers(AddonModQuizProvider.COMPONENT, attempt.id, question.slot, siteId);
}));
// Now save the answers.
await CoreQuestion.saveAnswers(
AddonModQuizProvider.COMPONENT,
quiz.id,
attempt.id,
attempt.userid!,
answers,
timeMod,
siteId,
);
try {
// Answers have been saved, now we can save the questions with the states.
await CoreUtils.allPromises(Object.keys(newStates).map(async (slot) => {
const question = questionsWithAnswers[Number(slot)];
await CoreQuestion.saveQuestion(
AddonModQuizProvider.COMPONENT,
quiz.id,
attempt.id,
attempt.userid!,
question,
newStates[slot],
siteId,
);
}));
} catch (error) {
// Ignore errors when saving question state.
this.logger.error('Error saving question state', error);
}
}
/**
* Set attempt's current page.
*
* @param attemptId Attempt ID.
* @param page Page to set.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved in success, rejected otherwise.
*/
async setAttemptCurrentPage(attemptId: number, page: number, siteId?: string): Promise<void> {
const db = await CoreSites.getSiteDb(siteId);
await db.updateRecords(ATTEMPTS_TABLE_NAME, { currentpage: page }, { id: attemptId });
}
}
export const AddonModQuizOffline = makeSingleton(AddonModQuizOfflineProvider);
/**
* Answers classified by question slot.
*/
export type AddonModQuizQuestionsWithAnswers = Record<number, {
prefix: string;
answers: CoreQuestionsAnswers;
}>; | the_stack |
module android.widget {
import AlertDialog = android.app.AlertDialog;
import DialogInterface = android.content.DialogInterface;
import OnClickListener = android.content.DialogInterface.OnClickListener;
import DataSetObserver = android.database.DataSetObserver;
import Rect = android.graphics.Rect;
import Drawable = android.graphics.drawable.Drawable;
import Log = android.util.Log;
import Gravity = android.view.Gravity;
import MotionEvent = android.view.MotionEvent;
import View = android.view.View;
import ViewGroup = android.view.ViewGroup;
import ViewTreeObserver = android.view.ViewTreeObserver;
import OnGlobalLayoutListener = android.view.ViewTreeObserver.OnGlobalLayoutListener;
import ForwardingListener = android.widget.ListPopupWindow.ForwardingListener;
import OnDismissListener = android.widget.PopupWindow.OnDismissListener;
import AbsSpinner = android.widget.AbsSpinner;
import Adapter = android.widget.Adapter;
import AdapterView = android.widget.AdapterView;
import ListAdapter = android.widget.ListAdapter;
import ListPopupWindow = android.widget.ListPopupWindow;
import ListView = android.widget.ListView;
import PopupWindow = android.widget.PopupWindow;
import SpinnerAdapter = android.widget.SpinnerAdapter;
import Context = android.content.Context;
import R = android.R;
import AttrBinder = androidui.attr.AttrBinder;
/**
* A view that displays one child at a time and lets the user pick among them.
* The items in the Spinner come from the {@link Adapter} associated with
* this view.
*
* <p>See the <a href="{@docRoot}guide/topics/ui/controls/spinner.html">Spinners</a> guide.</p>
*
* @attr ref android.R.styleable#Spinner_dropDownHorizontalOffset
* @attr ref android.R.styleable#Spinner_dropDownSelector
* @attr ref android.R.styleable#Spinner_dropDownVerticalOffset
* @attr ref android.R.styleable#Spinner_dropDownWidth
* @attr ref android.R.styleable#Spinner_gravity
* @attr ref android.R.styleable#Spinner_popupBackground
* @attr ref android.R.styleable#Spinner_prompt
* @attr ref android.R.styleable#Spinner_spinnerMode
*/
export class Spinner extends AbsSpinner implements OnClickListener {
static TAG:string = "Spinner";
// Only measure this many items to get a decent max width.
private static MAX_ITEMS_MEASURED:number = 15;
/**
* Use a dialog window for selecting spinner options.
*/
static MODE_DIALOG:number = 0;
/**
* Use a dropdown anchored to the Spinner for selecting spinner options.
*/
static MODE_DROPDOWN:number = 1;
/**
* Use the theme-supplied value to select the dropdown mode.
*/
private static MODE_THEME:number = -1;
///** Forwarding listener used to implement drag-to-open. */
//private mForwardingListener:ForwardingListener;
private mPopup:Spinner.SpinnerPopup;
private mTempAdapter:Spinner.DropDownAdapter;
mDropDownWidth:number = 0;
private mGravity:number = 0;
private mDisableChildrenWhenDisabled:boolean;
private mTempRect:Rect = new Rect();
/**
* Construct a new spinner with the given context's theme, the supplied attribute set,
* and default style. <code>mode</code> may be one of {@link #MODE_DIALOG} or
* {@link #MODE_DROPDOWN} and determines how the user will select choices from the spinner.
*
* @param context The Context the view is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the view.
* @param defStyle The default style to apply to this view. If 0, no style
* will be applied (beyond what is included in the theme). This may
* either be an attribute resource, whose value will be retrieved
* from the current theme, or an explicit style resource.
* @param mode Constant describing how the user will select choices from the spinner.
*
* @see #MODE_DIALOG
* @see #MODE_DROPDOWN
*/
constructor(context:Context, bindElement?:HTMLElement, defStyle=R.attr.spinnerStyle, mode=Spinner.MODE_THEME) {
super(context, bindElement, defStyle);
const a = context.obtainStyledAttributes(bindElement, defStyle);
if (mode == Spinner.MODE_THEME) {
if ('dialog' === a.getAttrValue('spinnerMode')) {
mode = Spinner.MODE_DIALOG;
} else {
mode = Spinner.MODE_DROPDOWN;
}
}
switch (mode) {
case Spinner.MODE_DIALOG: {
this.mPopup = new Spinner.DialogPopup(this);
break;
}
case Spinner.MODE_DROPDOWN: {
const popup = new Spinner.DropdownPopup(context, defStyle, this);
this.mDropDownWidth = a.getLayoutDimension('dropDownWidth', ViewGroup.LayoutParams.WRAP_CONTENT);
popup.setBackgroundDrawable(a.getDrawable('popupBackground'));
const verticalOffset = a.getDimensionPixelOffset('dropDownVerticalOffset', 0);
if (verticalOffset != 0) {
popup.setVerticalOffset(verticalOffset);
}
const horizontalOffset = a.getDimensionPixelOffset('dropDownHorizontalOffset', 0);
if (horizontalOffset != 0) {
popup.setHorizontalOffset(horizontalOffset);
}
this.mPopup = popup;
// mForwardingListener = new ForwardingListener(this) {
// @Override
// public ListPopupWindow getPopup() {
// return popup;
// }
//
// @Override
// public boolean onForwardingStarted() {
// if (!mPopup.isShowing()) {
// mPopup.show(getTextDirection(), getTextAlignment());
// }
// return true;
// }
// };
break;
}
}
this.mGravity = Gravity.parseGravity(a.getAttrValue('gravity'), Gravity.CENTER);
this.mPopup.setPromptText(a.getString('prompt'));
this.mDisableChildrenWhenDisabled = a.getBoolean('disableChildrenWhenDisabled', false);
a.recycle();
// Finish setting things up if this happened.
if (this.mTempAdapter != null) {
this.mPopup.setAdapter(this.mTempAdapter);
this.mTempAdapter = null;
}
}
protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap {
return super.createClassAttrBinder().set('dropDownWidth', {
setter(v:Spinner, value:any, a:AttrBinder) {
v.mDropDownWidth = a.parseNumberPixelSize(value, v.mDropDownWidth);
}, getter(v:Spinner) {
return v.mDropDownWidth;
}
}).set('popupBackground', {
setter(v:Spinner, value:any, a:AttrBinder) {
v.mPopup.setBackgroundDrawable(a.parseDrawable(value));
}, getter(v:Spinner) {
return v.mPopup.getBackground();
}
}).set('dropDownVerticalOffset', {
setter(v:Spinner, value:any, a:AttrBinder) {
const verticalOffset:number = a.parseNumberPixelSize(value, 0);
if (verticalOffset != 0) {
v.mPopup.setVerticalOffset(verticalOffset);
}
}, getter(v:Spinner) {
return v.mPopup.getVerticalOffset();
}
}).set('dropDownHorizontalOffset', {
setter(v:Spinner, value:any, a:AttrBinder) {
const horizontalOffset:number = a.parseNumberPixelSize(value, 0);
if (horizontalOffset != 0) {
v.mPopup.setHorizontalOffset(horizontalOffset);
}
}, getter(v:Spinner) {
return v.mPopup.getHorizontalOffset();
}
}).set('gravity', {
setter(v:Spinner, value:any, a:AttrBinder) {
v.mGravity = a.parseGravity(value, Gravity.CENTER);
}, getter(v:Spinner) {
return v.mGravity;
}
}).set('prompt', {
setter(v:Spinner, value:any, a:AttrBinder) {
v.mPopup.setPromptText(a.parseString(value));
}, getter(v:Spinner) {
return v.mPopup.getHintText();
}
}).set('disableChildrenWhenDisabled', {
setter(v:Spinner, value:any, a:AttrBinder) {
v.mDisableChildrenWhenDisabled = a.parseBoolean(value, false);
}, getter(v:Spinner) {
return v.mDisableChildrenWhenDisabled;
}
});
}
/**
* Set the background drawable for the spinner's popup window of choices.
* Only valid in {@link #MODE_DROPDOWN}; this method is a no-op in other modes.
*
* @param background Background drawable
*
* @attr ref android.R.styleable#Spinner_popupBackground
*/
setPopupBackgroundDrawable(background:Drawable):void {
if (!(this.mPopup instanceof Spinner.DropdownPopup)) {
Log.e(Spinner.TAG, "setPopupBackgroundDrawable: incompatible spinner mode; ignoring...");
return;
}
(<Spinner.DropdownPopup> this.mPopup).setBackgroundDrawable(background);
}
///**
// * Set the background drawable for the spinner's popup window of choices.
// * Only valid in {@link #MODE_DROPDOWN}; this method is a no-op in other modes.
// *
// * @param resId Resource ID of a background drawable
// *
// * @attr ref android.R.styleable#Spinner_popupBackground
// */
//setPopupBackgroundResource(resId:number):void {
// this.setPopupBackgroundDrawable(this.getContext().getResources().getDrawable(resId));
//}
/**
* Get the background drawable for the spinner's popup window of choices.
* Only valid in {@link #MODE_DROPDOWN}; other modes will return null.
*
* @return background Background drawable
*
* @attr ref android.R.styleable#Spinner_popupBackground
*/
getPopupBackground():Drawable {
return this.mPopup.getBackground();
}
/**
* Set a vertical offset in pixels for the spinner's popup window of choices.
* Only valid in {@link #MODE_DROPDOWN}; this method is a no-op in other modes.
*
* @param pixels Vertical offset in pixels
*
* @attr ref android.R.styleable#Spinner_dropDownVerticalOffset
*/
setDropDownVerticalOffset(pixels:number):void {
this.mPopup.setVerticalOffset(pixels);
}
/**
* Get the configured vertical offset in pixels for the spinner's popup window of choices.
* Only valid in {@link #MODE_DROPDOWN}; other modes will return 0.
*
* @return Vertical offset in pixels
*
* @attr ref android.R.styleable#Spinner_dropDownVerticalOffset
*/
getDropDownVerticalOffset():number {
return this.mPopup.getVerticalOffset();
}
/**
* Set a horizontal offset in pixels for the spinner's popup window of choices.
* Only valid in {@link #MODE_DROPDOWN}; this method is a no-op in other modes.
*
* @param pixels Horizontal offset in pixels
*
* @attr ref android.R.styleable#Spinner_dropDownHorizontalOffset
*/
setDropDownHorizontalOffset(pixels:number):void {
this.mPopup.setHorizontalOffset(pixels);
}
/**
* Get the configured horizontal offset in pixels for the spinner's popup window of choices.
* Only valid in {@link #MODE_DROPDOWN}; other modes will return 0.
*
* @return Horizontal offset in pixels
*
* @attr ref android.R.styleable#Spinner_dropDownHorizontalOffset
*/
getDropDownHorizontalOffset():number {
return this.mPopup.getHorizontalOffset();
}
/**
* Set the width of the spinner's popup window of choices in pixels. This value
* may also be set to {@link android.view.ViewGroup.LayoutParams#MATCH_PARENT}
* to match the width of the Spinner itself, or
* {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} to wrap to the measured size
* of contained dropdown list items.
*
* <p>Only valid in {@link #MODE_DROPDOWN}; this method is a no-op in other modes.</p>
*
* @param pixels Width in pixels, WRAP_CONTENT, or MATCH_PARENT
*
* @attr ref android.R.styleable#Spinner_dropDownWidth
*/
setDropDownWidth(pixels:number):void {
if (!(this.mPopup instanceof Spinner.DropdownPopup)) {
Log.e(Spinner.TAG, "Cannot set dropdown width for MODE_DIALOG, ignoring");
return;
}
this.mDropDownWidth = pixels;
}
/**
* Get the configured width of the spinner's popup window of choices in pixels.
* The returned value may also be {@link android.view.ViewGroup.LayoutParams#MATCH_PARENT}
* meaning the popup window will match the width of the Spinner itself, or
* {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} to wrap to the measured size
* of contained dropdown list items.
*
* @return Width in pixels, WRAP_CONTENT, or MATCH_PARENT
*
* @attr ref android.R.styleable#Spinner_dropDownWidth
*/
getDropDownWidth():number {
return this.mDropDownWidth;
}
setEnabled(enabled:boolean):void {
super.setEnabled(enabled);
if (this.mDisableChildrenWhenDisabled) {
const count:number = this.getChildCount();
for (let i:number = 0; i < count; i++) {
this.getChildAt(i).setEnabled(enabled);
}
}
}
/**
* Describes how the selected item view is positioned. Currently only the horizontal component
* is used. The default is determined by the current theme.
*
* @param gravity See {@link android.view.Gravity}
*
* @attr ref android.R.styleable#Spinner_gravity
*/
setGravity(gravity:number):void {
if (this.mGravity != gravity) {
if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == 0) {
gravity |= Gravity.START;
}
this.mGravity = gravity;
this.requestLayout();
}
}
/**
* Describes how the selected item view is positioned. The default is determined by the
* current theme.
*
* @return A {@link android.view.Gravity Gravity} value
*/
getGravity():number {
return this.mGravity;
}
/**
* Sets the Adapter used to provide the data which backs this Spinner.
* <p>
* Note that Spinner overrides {@link Adapter#getViewTypeCount()} on the
* Adapter associated with this view. Calling
* {@link Adapter#getItemViewType(int) getItemViewType(int)} on the object
* returned from {@link #getAdapter()} will always return 0. Calling
* {@link Adapter#getViewTypeCount() getViewTypeCount()} will always return
* 1.
*
* @see AbsSpinner#setAdapter(SpinnerAdapter)
*/
setAdapter(adapter:SpinnerAdapter):void {
super.setAdapter(adapter);
this.mRecycler.clear();
if (this.mPopup != null) {
this.mPopup.setAdapter(new Spinner.DropDownAdapter(adapter));
} else {
this.mTempAdapter = new Spinner.DropDownAdapter(adapter);
}
}
getBaseline():number {
let child:View = null;
if (this.getChildCount() > 0) {
child = this.getChildAt(0);
} else if (this.mAdapter != null && this.mAdapter.getCount() > 0) {
child = this.makeView(0, false);
this.mRecycler.put(0, child);
}
if (child != null) {
const childBaseline:number = child.getBaseline();
return childBaseline >= 0 ? child.getTop() + childBaseline : -1;
} else {
return -1;
}
}
protected onDetachedFromWindow():void {
super.onDetachedFromWindow();
if (this.mPopup != null && this.mPopup.isShowing()) {
this.mPopup.dismiss();
}
}
/**
* <p>A spinner does not support item click events. Calling this method
* will raise an exception.</p>
* <p>Instead use {@link AdapterView#setOnItemSelectedListener}.
*
* @param l this listener will be ignored
*/
setOnItemClickListener(l:AdapterView.OnItemClickListener):void {
throw Error(`new RuntimeException("setOnItemClickListener cannot be used with a spinner.")`);
}
/**
* @hide internal use only
*/
setOnItemClickListenerInt(l:AdapterView.OnItemClickListener):void {
super.setOnItemClickListener(l);
}
//onTouchEvent(event:MotionEvent):boolean {
// if (this.mForwardingListener != null && this.mForwardingListener.onTouch(this, event)) {
// return true;
// }
// return super.onTouchEvent(event);
//}
protected onMeasure(widthMeasureSpec:number, heightMeasureSpec:number):void {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (this.mPopup != null && View.MeasureSpec.getMode(widthMeasureSpec) == View.MeasureSpec.AT_MOST) {
const measuredWidth:number = this.getMeasuredWidth();
this.setMeasuredDimension(Math.min(Math.max(measuredWidth, this.measureContentWidth(this.getAdapter(), this.getBackground())), View.MeasureSpec.getSize(widthMeasureSpec)), this.getMeasuredHeight());
}
}
/**
* @see android.view.View#onLayout(boolean,int,int,int,int)
*
* Creates and positions all views
*
*/
protected onLayout(changed:boolean, l:number, t:number, r:number, b:number):void {
super.onLayout(changed, l, t, r, b);
this.mInLayout = true;
this.layoutSpinner(0, false);
this.mInLayout = false;
}
/**
* Creates and positions all views for this Spinner.
*
* @param delta Change in the selected position. +1 means selection is moving to the right,
* so views are scrolling to the left. -1 means selection is moving to the left.
*/
layoutSpinner(delta:number, animate:boolean):void {
let childrenLeft:number = this.mSpinnerPadding.left;
let childrenWidth:number = this.mRight - this.mLeft - this.mSpinnerPadding.left - this.mSpinnerPadding.right;
if (this.mDataChanged) {
this.handleDataChanged();
}
// Handle the empty set by removing all views
if (this.mItemCount == 0) {
this.resetList();
return;
}
if (this.mNextSelectedPosition >= 0) {
this.setSelectedPositionInt(this.mNextSelectedPosition);
}
this.recycleAllViews();
// Clear out old views
this.removeAllViewsInLayout();
// Make selected view and position it
this.mFirstPosition = this.mSelectedPosition;
if (this.mAdapter != null) {
let sel:View = this.makeView(this.mSelectedPosition, true);
let width:number = sel.getMeasuredWidth();
let selectedOffset:number = childrenLeft;
const layoutDirection:number = this.getLayoutDirection();
const absoluteGravity:number = Gravity.getAbsoluteGravity(this.mGravity, layoutDirection);
switch(absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.CENTER_HORIZONTAL:
selectedOffset = childrenLeft + (childrenWidth / 2) - (width / 2);
break;
case Gravity.RIGHT:
selectedOffset = childrenLeft + childrenWidth - width;
break;
}
sel.offsetLeftAndRight(selectedOffset);
}
// Flush any cached views that did not get reused above
this.mRecycler.clear();
this.invalidate();
this.checkSelectionChanged();
this.mDataChanged = false;
this.mNeedSync = false;
this.setNextSelectedPositionInt(this.mSelectedPosition);
}
/**
* Obtain a view, either by pulling an existing view from the recycler or
* by getting a new one from the adapter. If we are animating, make sure
* there is enough information in the view's layout parameters to animate
* from the old to new positions.
*
* @param position Position in the spinner for the view to obtain
* @param addChild true to add the child to the spinner, false to obtain and configure only.
* @return A view for the given position
*/
private makeView(position:number, addChild:boolean):View {
let child:View;
if (!this.mDataChanged) {
child = this.mRecycler.get(position);
if (child != null) {
// Position the view
this.setUpChild(child, addChild);
return child;
}
}
// Nothing found in the recycler -- ask the adapter for a view
child = this.mAdapter.getView(position, null, this);
// Position the view
this.setUpChild(child, addChild);
return child;
}
/**
* Helper for makeAndAddView to set the position of a view
* and fill out its layout paramters.
*
* @param child The view to position
* @param addChild true if the child should be added to the Spinner during setup
*/
private setUpChild(child:View, addChild:boolean):void {
// Respect layout params that are already in the view. Otherwise
// make some up...
let lp:ViewGroup.LayoutParams = child.getLayoutParams();
if (lp == null) {
lp = this.generateDefaultLayoutParams();
}
if (addChild) {
this.addViewInLayout(child, 0, lp);
}
child.setSelected(this.hasFocus());
if (this.mDisableChildrenWhenDisabled) {
child.setEnabled(this.isEnabled());
}
// Get measure specs
let childHeightSpec:number = ViewGroup.getChildMeasureSpec(this.mHeightMeasureSpec, this.mSpinnerPadding.top + this.mSpinnerPadding.bottom, lp.height);
let childWidthSpec:number = ViewGroup.getChildMeasureSpec(this.mWidthMeasureSpec, this.mSpinnerPadding.left + this.mSpinnerPadding.right, lp.width);
// Measure child
child.measure(childWidthSpec, childHeightSpec);
let childLeft:number;
let childRight:number;
// Position vertically based on gravity setting
let childTop:number = this.mSpinnerPadding.top + ((this.getMeasuredHeight() - this.mSpinnerPadding.bottom - this.mSpinnerPadding.top - child.getMeasuredHeight()) / 2);
let childBottom:number = childTop + child.getMeasuredHeight();
let width:number = child.getMeasuredWidth();
childLeft = 0;
childRight = childLeft + width;
child.layout(childLeft, childTop, childRight, childBottom);
}
performClick():boolean {
let handled:boolean = super.performClick();
if (!handled) {
handled = true;
if (!this.mPopup.isShowing()) {
this.mPopup.showPopup(this.getTextDirection(), this.getTextAlignment());
}
}
return handled;
}
onClick(dialog:DialogInterface, which:number):void {
this.setSelection(which);
dialog.dismiss();
}
//onInitializeAccessibilityEvent(event:AccessibilityEvent):void {
// super.onInitializeAccessibilityEvent(event);
// event.setClassName(Spinner.class.getName());
//}
//
//onInitializeAccessibilityNodeInfo(info:AccessibilityNodeInfo):void {
// super.onInitializeAccessibilityNodeInfo(info);
// info.setClassName(Spinner.class.getName());
// if (this.mAdapter != null) {
// info.setCanOpenPopup(true);
// }
//}
/**
* Sets the prompt to display when the dialog is shown.
* @param prompt the prompt to set
*/
setPrompt(prompt:string):void {
this.mPopup.setPromptText(prompt);
}
///**
// * Sets the prompt to display when the dialog is shown.
// * @param promptId the resource ID of the prompt to display when the dialog is shown
// */
//setPromptId(promptId:number):void {
// this.setPrompt(this.getContext().getText(promptId));
//}
/**
* @return The prompt to display when the dialog is shown
*/
getPrompt():string {
return this.mPopup.getHintText();
}
measureContentWidth(adapter:SpinnerAdapter, background:Drawable):number {
if (adapter == null) {
return 0;
}
let width:number = 0;
let itemView:View = null;
let itemType:number = 0;
const widthMeasureSpec:number = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
const heightMeasureSpec:number = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
// Make sure the number of items we'll measure is capped. If it's a huge data set
// with wildly varying sizes, oh well.
let start:number = Math.max(0, this.getSelectedItemPosition());
const end:number = Math.min(adapter.getCount(), start + Spinner.MAX_ITEMS_MEASURED);
const count:number = end - start;
start = Math.max(0, start - (Spinner.MAX_ITEMS_MEASURED - count));
for (let i:number = start; i < end; i++) {
const positionType:number = adapter.getItemViewType(i);
if (positionType != itemType) {
itemType = positionType;
itemView = null;
}
itemView = adapter.getView(i, itemView, this);
if (itemView.getLayoutParams() == null) {
itemView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
itemView.measure(widthMeasureSpec, heightMeasureSpec);
width = Math.max(width, itemView.getMeasuredWidth());
}
// Add background padding to measured width
if (background != null) {
background.getPadding(this.mTempRect);
width += this.mTempRect.left + this.mTempRect.right;
}
return width;
}
//onSaveInstanceState():Parcelable {
// const ss:Spinner.SavedState = new Spinner.SavedState(super.onSaveInstanceState());
// ss.showDropdown = this.mPopup != null && this.mPopup.isShowing();
// return ss;
//}
//
//onRestoreInstanceState(state:Parcelable):void {
// let ss:Spinner.SavedState = <Spinner.SavedState> state;
// super.onRestoreInstanceState(ss.getSuperState());
// if (ss.showDropdown) {
// let vto:ViewTreeObserver = this.getViewTreeObserver();
// if (vto != null) {
// const listener:OnGlobalLayoutListener = (()=>{
// const inner_this=this;
// class _Inner extends OnGlobalLayoutListener {
//
// onGlobalLayout():void {
// if (!inner_this.mPopup.isShowing()) {
// inner_this.mPopup.showPopup(inner_this.getTextDirection(), inner_this.getTextAlignment());
// }
// const vto:ViewTreeObserver = inner_this.getViewTreeObserver();
// if (vto != null) {
// vto.removeOnGlobalLayoutListener(this);
// }
// }
// }
// return new _Inner();
// })();
// vto.addOnGlobalLayoutListener(listener);
// }
// }
//}
}
export module Spinner{
//export class SavedState extends AbsSpinner.SavedState {
//
// showDropdown:boolean;
//
// constructor( superState:Parcelable) {
// super(superState);
// }
//
// constructor( _in:Parcel) {
// super(_in);
// this.showDropdown = _in.readByte() != 0;
// }
//
// writeToParcel(out:Parcel, flags:number):void {
// super.writeToParcel(out, flags);
// out.writeByte(<byte> (this.showDropdown ? 1 : 0));
// }
//
// static CREATOR:Parcelable.Creator<AbsSpinner.SavedState> = (()=>{
// const inner_this=this;
// class _Inner extends Parcelable.Creator<AbsSpinner.SavedState> {
//
// createFromParcel(_in:Parcel):AbsSpinner.SavedState {
// return new AbsSpinner.SavedState(_in);
// }
//
// newArray(size:number):AbsSpinner.SavedState[] {
// return new Array<AbsSpinner.SavedState>(size);
// }
// }
// return new _Inner();
// })();
//}
/**
* <p>Wrapper class for an Adapter. Transforms the embedded Adapter instance
* into a ListAdapter.</p>
*/
export class DropDownAdapter implements ListAdapter, SpinnerAdapter {
private mAdapter:SpinnerAdapter;
private mListAdapter:ListAdapter;
/**
* <p>Creates a new ListAdapter wrapper for the specified adapter.</p>
*
* @param adapter the Adapter to transform into a ListAdapter
*/
constructor(adapter:SpinnerAdapter) {
this.mAdapter = adapter;
if (ListAdapter.isImpl(adapter)) {
this.mListAdapter = <ListAdapter><any>adapter;
}
}
getCount():number {
return this.mAdapter == null ? 0 : this.mAdapter.getCount();
}
getItem(position:number):any {
return this.mAdapter == null ? null : this.mAdapter.getItem(position);
}
getItemId(position:number):number {
return this.mAdapter == null ? -1 : this.mAdapter.getItemId(position);
}
getView(position:number, convertView:View, parent:ViewGroup):View {
return this.getDropDownView(position, convertView, parent);
}
getDropDownView(position:number, convertView:View, parent:ViewGroup):View {
return (this.mAdapter == null) ? null : this.mAdapter.getDropDownView(position, convertView, parent);
}
hasStableIds():boolean {
return this.mAdapter != null && this.mAdapter.hasStableIds();
}
registerDataSetObserver(observer:DataSetObserver):void {
if (this.mAdapter != null) {
this.mAdapter.registerDataSetObserver(observer);
}
}
unregisterDataSetObserver(observer:DataSetObserver):void {
if (this.mAdapter != null) {
this.mAdapter.unregisterDataSetObserver(observer);
}
}
/**
* If the wrapped SpinnerAdapter is also a ListAdapter, delegate this call.
* Otherwise, return true.
*/
areAllItemsEnabled():boolean {
const adapter:ListAdapter = this.mListAdapter;
if (adapter != null) {
return adapter.areAllItemsEnabled();
} else {
return true;
}
}
/**
* If the wrapped SpinnerAdapter is also a ListAdapter, delegate this call.
* Otherwise, return true.
*/
isEnabled(position:number):boolean {
const adapter:ListAdapter = this.mListAdapter;
if (adapter != null) {
return adapter.isEnabled(position);
} else {
return true;
}
}
getItemViewType(position:number):number {
return 0;
}
getViewTypeCount():number {
return 1;
}
isEmpty():boolean {
return this.getCount() == 0;
}
}
/**
* Implements some sort of popup selection interface for selecting a spinner option.
* Allows for different spinner modes.
*/
export interface SpinnerPopup {
setAdapter(adapter:ListAdapter):void ;
/**
* Show the popup
*/
showPopup(textDirection:number, textAlignment:number):void ;
/**
* Dismiss the popup
*/
dismiss():void ;
/**
* @return true if the popup is showing, false otherwise.
*/
isShowing():boolean ;
/**
* Set hint text to be displayed to the user. This should provide
* a description of the choice being made.
* @param hintText Hint text to set.
*/
setPromptText(hintText:string):void ;
getHintText():string ;
setBackgroundDrawable(bg:Drawable):void ;
setVerticalOffset(px:number):void ;
setHorizontalOffset(px:number):void ;
getBackground():Drawable ;
getVerticalOffset():number ;
getHorizontalOffset():number ;
}
export class DialogPopup implements Spinner.SpinnerPopup, DialogInterface.OnClickListener {
_Spinner_this:Spinner;
constructor(arg:Spinner){
this._Spinner_this = arg;
}
private mPopup:AlertDialog;
private mListAdapter:ListAdapter;
private mPrompt:string;
dismiss():void {
this.mPopup.dismiss();
this.mPopup = null;
}
isShowing():boolean {
return this.mPopup != null ? this.mPopup.isShowing() : false;
}
setAdapter(adapter:ListAdapter):void {
this.mListAdapter = adapter;
}
setPromptText(hintText:string):void {
this.mPrompt = hintText;
}
getHintText():string {
return this.mPrompt;
}
showPopup(textDirection:number, textAlignment:number):void {
if (this.mListAdapter == null) {
return;
}
let builder:AlertDialog.Builder = new AlertDialog.Builder(this._Spinner_this.getContext());
if (this.mPrompt != null) {
builder.setTitle(this.mPrompt);
}
this.mPopup = builder.setSingleChoiceItemsWithAdapter(this.mListAdapter, this._Spinner_this.getSelectedItemPosition(), this).create();
const listView:ListView = this.mPopup.getListView();
listView.setTextDirection(textDirection);
listView.setTextAlignment(textAlignment);
this.mPopup.show();
}
onClick(dialog:DialogInterface, which:number):void {
this._Spinner_this.setSelection(which);
if (this._Spinner_this.mOnItemClickListener != null) {
this._Spinner_this.performItemClick(null, which, this.mListAdapter.getItemId(which));
}
this.dismiss();
}
setBackgroundDrawable(bg:Drawable):void {
Log.e(Spinner.TAG, "Cannot set popup background for MODE_DIALOG, ignoring");
}
setVerticalOffset(px:number):void {
Log.e(Spinner.TAG, "Cannot set vertical offset for MODE_DIALOG, ignoring");
}
setHorizontalOffset(px:number):void {
Log.e(Spinner.TAG, "Cannot set horizontal offset for MODE_DIALOG, ignoring");
}
getBackground():Drawable {
return null;
}
getVerticalOffset():number {
return 0;
}
getHorizontalOffset():number {
return 0;
}
}
export class DropdownPopup extends ListPopupWindow implements Spinner.SpinnerPopup {
_Spinner_this:Spinner;
private mHintText:string;
//private mAdapter:ListAdapter;
constructor(context:Context, defStyleRes:Map<string, string>, arg:Spinner) {
super(context, defStyleRes);
this._Spinner_this = arg;
this.setAnchorView(this._Spinner_this);
this.setModal(true);
this.setPromptPosition(DropdownPopup.POSITION_PROMPT_ABOVE);
this.setOnItemClickListener((()=>{
const inner_this=this;
class _Inner implements AdapterView.OnItemClickListener {
onItemClick(parent:AdapterView<any>, v:View, position:number, id:number):void {
inner_this._Spinner_this.setSelection(position);
if (inner_this._Spinner_this.mOnItemClickListener != null) {
inner_this._Spinner_this.performItemClick(v, position, inner_this.mAdapter.getItemId(position));
}
inner_this.dismiss();
}
}
return new _Inner();
})());
}
setAdapter(adapter:ListAdapter):void {
super.setAdapter(adapter);
//this.mAdapter = adapter;
}
getHintText():string {
return this.mHintText;
}
setPromptText(hintText:string):void {
// Hint text is ignored for dropdowns, but maintain it here.
this.mHintText = hintText;
}
computeContentWidth():void {
const background:Drawable = this.getBackground();
let hOffset:number = 0;
if (background != null) {
background.getPadding(this._Spinner_this.mTempRect);
hOffset = this._Spinner_this.isLayoutRtl() ? this._Spinner_this.mTempRect.right : -this._Spinner_this.mTempRect.left;
} else {
this._Spinner_this.mTempRect.left = this._Spinner_this.mTempRect.right = 0;
}
const spinnerPaddingLeft:number = this._Spinner_this.getPaddingLeft();
const spinnerPaddingRight:number = this._Spinner_this.getPaddingRight();
const spinnerWidth:number = this._Spinner_this.getWidth();
if (this._Spinner_this.mDropDownWidth == DropdownPopup.WRAP_CONTENT) {
let contentWidth:number = this._Spinner_this.measureContentWidth(<SpinnerAdapter><any>this.mAdapter, this.getBackground());
const contentWidthLimit:number = this._Spinner_this.mContext.getResources().getDisplayMetrics().widthPixels - this._Spinner_this.mTempRect.left - this._Spinner_this.mTempRect.right;
if (contentWidth > contentWidthLimit) {
contentWidth = contentWidthLimit;
}
this.setContentWidth(Math.max(contentWidth, spinnerWidth - spinnerPaddingLeft - spinnerPaddingRight));
} else if (this._Spinner_this.mDropDownWidth == DropdownPopup.MATCH_PARENT) {
this.setContentWidth(spinnerWidth - spinnerPaddingLeft - spinnerPaddingRight);
} else {
this.setContentWidth(this._Spinner_this.mDropDownWidth);
}
if (this._Spinner_this.isLayoutRtl()) {
hOffset += spinnerWidth - spinnerPaddingRight - this.getWidth();
} else {
hOffset += spinnerPaddingLeft;
}
this.setHorizontalOffset(hOffset);
}
showPopup(textDirection:number, textAlignment:number):void {
const wasShowing:boolean = this.isShowing();
this.computeContentWidth();
this.setInputMethodMode(ListPopupWindow.INPUT_METHOD_NOT_NEEDED);
super.show();
const listView:ListView = this.getListView();
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setTextDirection(textDirection);
listView.setTextAlignment(textAlignment);
this.setSelection(this._Spinner_this.getSelectedItemPosition());
if (wasShowing) {
// showing it will still stick around.
return;
}
// Make sure we hide if our anchor goes away.
// TODO: This might be appropriate to push all the way down to PopupWindow,
// but it may have other side effects to investigate first. (Text editing handles, etc.)
const vto:ViewTreeObserver = this._Spinner_this.getViewTreeObserver();
if (vto != null) {
const layoutListener:android.view.ViewTreeObserver.OnGlobalLayoutListener = (()=>{
const inner_this=this;
class _Inner implements android.view.ViewTreeObserver.OnGlobalLayoutListener {
onGlobalLayout():void {
if (!inner_this._Spinner_this.isVisibleToUser()) {
inner_this.dismiss();
} else {
inner_this.computeContentWidth();
// Use super.show here to update; we don't want to move the selected
// position or adjust other things that would be reset otherwise.
inner_this.show();
}
}
}
return new _Inner();
})();
vto.addOnGlobalLayoutListener(layoutListener);
this.setOnDismissListener((()=>{
const inner_this=this;
class _Inner implements PopupWindow.OnDismissListener {
onDismiss():void {
const vto:ViewTreeObserver = inner_this._Spinner_this.getViewTreeObserver();
if (vto != null) {
vto.removeOnGlobalLayoutListener(layoutListener);
}
}
}
return new _Inner();
})());
}
}
}
}
} | the_stack |
/*
* GridViewScroll with jQuery v1.0.0.3
* http://gridviewscroll.aspcity.idv.tw/
* Copyright (c) 2017 Likol Lee
* Released under the MIT license
* 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.
*/
class GridViewScrollOptions {
elementID: string;
width: string;
height: string;
freezeColumn: boolean;
freezeFooter: boolean;
freezeColumnCssClass: string;
freezeFooterCssClass: string;
freezeHeaderRowCount: number;
freezeColumnCount: number;
onscroll: GridViewScrollOnScroll;
}
class GridViewScrollScrollPosition {
scrollTop: number;
scrollLeft: number;
}
type GridViewScrollOnScroll = (scrollTop: number, scrollLeft: number) => any;
class GridViewScroll {
private _initialized: boolean;
private OnScroll: GridViewScrollOnScroll;
private GridID: string;
private GridWidth: string;
private GridHeight: string;
private Width: number;
private Height: number;
private FreezeColumn: boolean;
private FreezeFooter: boolean;
private FreezeColumnCssClass: string;
private FreezeFooterCssClass: string;
private FreezeHeaderRowCount: number;
private FreezeColumnCount: number;
private Parent: HTMLElement;
private ContentGrid: HTMLTableElement;
private ContentGridHeaderRows: Array<HTMLTableRowElement>;
private ContentGridItemRow: HTMLTableRowElement;
private ContentGridFooterRow: HTMLTableRowElement;
private Header: HTMLDivElement;
private HeaderFixed: HTMLDivElement;
private Content: HTMLDivElement;
private ContentFixed: HTMLDivElement;
private HeaderGrid: HTMLTableElement;
private HeaderGridHeaderRows: Array<HTMLTableRowElement>;
private HeaderGridHeaderCells: Array<HTMLTableCellElement>;
private HeaderFreeze: HTMLDivElement;
private HeaderFreezeGrid: HTMLTableElement;
private HeaderFreezeGridHeaderRows: Array<HTMLTableRowElement>;
private ContentFreeze: HTMLDivElement;
private ContentFreezeGrid: HTMLTableElement;
private FooterFreeze: HTMLDivElement;
private FooterFreezeGrid: HTMLTableElement;
private FooterFreezeGridHeaderRow: HTMLTableRowElement;
private FooterFreezeColumn: HTMLDivElement;
private FooterFreezeColumnGrid: HTMLTableElement;
private FooterFreezeColumnGridHeaderRow: HTMLTableRowElement;
private ScrollbarWidth: number;
private IsVerticalScrollbarEnabled: boolean; // 垂直卷軸
private IsHorizontalScrollbarEnabled: boolean; // 水平卷軸
private FreezeCellWidths: Array<number>;
constructor(options: GridViewScrollOptions) {
this._initialized = false;
if (options.elementID == null)
options.elementID = "";
if (options.width == null)
options.width = "700";
if (options.height == null)
options.height = "350";
if (options.freezeColumnCssClass == null)
options.freezeColumnCssClass = "";
if (options.freezeFooterCssClass == null)
options.freezeFooterCssClass = "";
if (options.freezeHeaderRowCount == null)
options.freezeHeaderRowCount = 1;
if (options.freezeColumnCount == null)
options.freezeColumnCount = 1;
this.initializeOptions(options);
}
private initializeOptions(options: GridViewScrollOptions) {
this.GridID = options.elementID;
this.GridWidth = options.width;
this.GridHeight = options.height;
this.FreezeColumn = options.freezeColumn;
this.FreezeFooter = options.freezeFooter;
this.FreezeColumnCssClass = options.freezeColumnCssClass;
this.FreezeFooterCssClass = options.freezeFooterCssClass;
this.FreezeHeaderRowCount = options.freezeHeaderRowCount;
this.FreezeColumnCount = options.freezeColumnCount;
this.OnScroll = options.onscroll;
}
enhance(): void {
this.FreezeCellWidths = [];
this.IsVerticalScrollbarEnabled = false;
this.IsHorizontalScrollbarEnabled = false;
if (this.GridID == null || this.GridID == "") {
return;
}
this.ContentGrid = <HTMLTableElement>document.getElementById(this.GridID);
if (this.ContentGrid == null) {
return;
}
if (this.ContentGrid.rows.length < 2) {
return;
}
if (this._initialized) {
this.undo();
}
this._initialized = true;
this.Parent = <HTMLElement>this.ContentGrid.parentNode;
this.ContentGrid.style.display = "none";
if (typeof this.GridWidth == 'string' && this.GridWidth.indexOf("%") > -1) {
var percentage = parseInt(this.GridWidth);
this.Width = this.Parent.offsetWidth * percentage / 100;
}
else {
this.Width = parseInt(this.GridWidth);
}
if (typeof this.GridHeight == 'string' && this.GridHeight.indexOf("%") > -1) {
var percentage = parseInt(this.GridHeight);
this.Height = this.Parent.offsetHeight * percentage / 100;
}
else {
this.Height = parseInt(this.GridHeight);
}
this.ContentGrid.style.display = "";
this.ContentGridHeaderRows = this.getGridHeaderRows();
this.ContentGridItemRow = this.ContentGrid.rows.item(this.FreezeHeaderRowCount);
let footerIndex = this.ContentGrid.rows.length - 1;
this.ContentGridFooterRow = this.ContentGrid.rows.item(footerIndex);
this.Content = <HTMLDivElement>document.createElement('div');
this.Content.id = this.GridID + "_Content";
this.Content.style.position = "relative";
this.Content = this.Parent.insertBefore(this.Content, this.ContentGrid);
this.ContentFixed = <HTMLDivElement>document.createElement('div');
this.ContentFixed.id = this.GridID + "_Content_Fixed";
this.ContentFixed.style.overflow = "auto";
this.ContentFixed = this.Content.appendChild(this.ContentFixed);
this.ContentGrid = this.ContentFixed.appendChild(this.ContentGrid);
this.ContentFixed.style.width = String(this.Width) + "px";
if (this.ContentGrid.offsetWidth > this.Width) {
this.IsHorizontalScrollbarEnabled = true;
}
if (this.ContentGrid.offsetHeight > this.Height) {
this.IsVerticalScrollbarEnabled = true;
}
this.Header = <HTMLDivElement>document.createElement('div');
this.Header.id = this.GridID + "_Header";
this.Header.style.position = "relative";
this.HeaderFixed = <HTMLDivElement>document.createElement('div');
this.HeaderFixed.id = this.GridID + "_Header_Fixed";
this.HeaderFixed.style.overflow = "hidden";
this.Header = this.Parent.insertBefore(this.Header, this.Content);
this.HeaderFixed = this.Header.appendChild(this.HeaderFixed);
this.ScrollbarWidth = this.getScrollbarWidth();
this.prepareHeader();
this.calculateHeader();
this.Header.style.width = String(this.Width) + "px";
if (this.IsVerticalScrollbarEnabled) {
this.HeaderFixed.style.width = String(this.Width - this.ScrollbarWidth) + "px";
if (this.IsHorizontalScrollbarEnabled) {
this.ContentFixed.style.width = this.HeaderFixed.style.width;
if (this.isRTL()) {
this.ContentFixed.style.paddingLeft = String(this.ScrollbarWidth) + "px";
}
else {
this.ContentFixed.style.paddingRight = String(this.ScrollbarWidth) + "px";
}
}
this.ContentFixed.style.height = String(this.Height - this.Header.offsetHeight) + "px";
}
else {
this.HeaderFixed.style.width = this.Header.style.width;
this.ContentFixed.style.width = this.Header.style.width;
}
if (this.FreezeColumn && this.IsHorizontalScrollbarEnabled) {
this.appendFreezeHeader();
this.appendFreezeContent();
}
if (this.FreezeFooter && this.IsVerticalScrollbarEnabled) {
this.appendFreezeFooter();
if (this.FreezeColumn && this.IsHorizontalScrollbarEnabled) {
this.appendFreezeFooterColumn();
}
}
var self = this;
this.ContentFixed.onscroll = function (event: UIEvent) {
let scrollTop = self.ContentFixed.scrollTop;
let scrollLeft = self.ContentFixed.scrollLeft;
self.HeaderFixed.scrollLeft = scrollLeft;
if(self.ContentFreeze != null)
self.ContentFreeze.scrollTop = scrollTop;
if (self.FooterFreeze != null)
self.FooterFreeze.scrollLeft = scrollLeft;
if (self.OnScroll != null) {
self.OnScroll(scrollTop, scrollLeft)
}
}
}
get scrollPosition() {
let position = new GridViewScrollScrollPosition();
position.scrollTop = this.ContentFixed.scrollTop;
position.scrollLeft = this.ContentFixed.scrollLeft;
return position;
}
set scrollPosition(gridViewScrollScrollPosition: GridViewScrollScrollPosition) {
let scrollTop = gridViewScrollScrollPosition.scrollTop;
let scrollLeft = gridViewScrollScrollPosition.scrollLeft;
this.ContentFixed.scrollTop = scrollTop;
this.ContentFixed.scrollLeft = scrollLeft;
if (this.ContentFreeze != null)
this.ContentFreeze.scrollTop = scrollTop;
if (this.FooterFreeze != null)
this.FooterFreeze.scrollLeft = scrollLeft;
}
private getGridHeaderRows() : Array<HTMLTableRowElement> {
let gridHeaderRows = new Array<HTMLTableRowElement>();
for (var i = 0; i < this.FreezeHeaderRowCount; i++) {
gridHeaderRows.push(this.ContentGrid.rows.item(i));
}
return gridHeaderRows;
}
private prepareHeader() : void {
this.HeaderGrid = <HTMLTableElement>this.ContentGrid.cloneNode(false);
this.HeaderGrid.id = this.GridID + "_Header_Fixed_Grid";
this.HeaderGrid = this.HeaderFixed.appendChild(this.HeaderGrid);
this.prepareHeaderGridRows();
for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {
this.appendHelperElement(this.ContentGridItemRow.cells.item(i));
this.appendHelperElement(this.HeaderGridHeaderCells[i]);
}
}
private prepareHeaderGridRows(): void {
this.HeaderGridHeaderRows = new Array<HTMLTableRowElement>();
for (var i = 0; i < this.FreezeHeaderRowCount; i++) {
let gridHeaderRow = this.ContentGridHeaderRows[i];
let headerGridHeaderRow = <HTMLTableRowElement>gridHeaderRow.cloneNode(true);
this.HeaderGridHeaderRows.push(headerGridHeaderRow);
this.HeaderGrid.appendChild(headerGridHeaderRow);
}
this.prepareHeaderGridCells();
}
private prepareHeaderGridCells(): void {
this.HeaderGridHeaderCells = new Array<HTMLTableCellElement>();
for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {
for (let rowIndex in this.HeaderGridHeaderRows) {
let cgridHeaderRow = this.HeaderGridHeaderRows[rowIndex];
let fixedCellIndex = 0;
for (var cellIndex = 0; cellIndex < cgridHeaderRow.cells.length; cellIndex++) {
let cgridHeaderCell = <HTMLTableCellElement>cgridHeaderRow.cells.item(cellIndex);
if (cgridHeaderCell.colSpan == 1 && i == fixedCellIndex) {
this.HeaderGridHeaderCells.push(cgridHeaderCell);
}
else {
fixedCellIndex += cgridHeaderCell.colSpan - 1;
}
fixedCellIndex++;
}
}
}
}
private calculateHeader(): void {
for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {
let gridItemCell = this.ContentGridItemRow.cells.item(i);
let helperElement = <HTMLDivElement>gridItemCell.firstChild;
let helperWidth = parseInt(String(helperElement.offsetWidth));
this.FreezeCellWidths.push(helperWidth);
helperElement.style.width = helperWidth + "px";
helperElement = <HTMLDivElement>this.HeaderGridHeaderCells[i].firstChild;
helperElement.style.width = helperWidth + "px";
}
for (var i = 0; i < this.FreezeHeaderRowCount; i++) {
this.ContentGridHeaderRows[i].style.display = "none";
}
}
private appendFreezeHeader() : void {
this.HeaderFreeze = <HTMLDivElement>document.createElement('div');
this.HeaderFreeze.id = this.GridID + "_Header_Freeze";
this.HeaderFreeze.style.position = "absolute";
this.HeaderFreeze.style.overflow = "hidden";
this.HeaderFreeze.style.top = "0px";
this.HeaderFreeze.style.left = "0px";
this.HeaderFreeze.style.width = "";
this.HeaderFreezeGrid = <HTMLTableElement>this.HeaderGrid.cloneNode(false);
this.HeaderFreezeGrid.id = this.GridID + "_Header_Freeze_Grid";
this.HeaderFreezeGrid = this.HeaderFreeze.appendChild(this.HeaderFreezeGrid);
this.HeaderFreezeGridHeaderRows = new Array<HTMLTableRowElement>();
for (var i = 0; i < this.HeaderGridHeaderRows.length; i++) {
let headerFreezeGridHeaderRow = <HTMLTableRowElement>this.HeaderGridHeaderRows[i].cloneNode(false);
this.HeaderFreezeGridHeaderRows.push(headerFreezeGridHeaderRow);
let columnIndex = 0;
let columnCount = 0;
while (columnCount < this.FreezeColumnCount ) {
let freezeColumn = <HTMLTableCellElement>this.HeaderGridHeaderRows[i].cells.item(columnIndex).cloneNode(true);
headerFreezeGridHeaderRow.appendChild(freezeColumn);
columnCount += freezeColumn.colSpan;
columnIndex++;
}
this.HeaderFreezeGrid.appendChild(headerFreezeGridHeaderRow);
}
this.HeaderFreeze = this.Header.appendChild(this.HeaderFreeze);
}
private appendFreezeContent(): void {
this.ContentFreeze = <HTMLDivElement>document.createElement('div');
this.ContentFreeze.id = this.GridID + "_Content_Freeze";
this.ContentFreeze.style.position = "absolute";
this.ContentFreeze.style.overflow = "hidden";
this.ContentFreeze.style.top = "0px";
this.ContentFreeze.style.left = "0px";
this.ContentFreeze.style.width = "";
this.ContentFreezeGrid = <HTMLTableElement>this.HeaderGrid.cloneNode(false);
this.ContentFreezeGrid.id = this.GridID + "_Content_Freeze_Grid";
this.ContentFreezeGrid = this.ContentFreeze.appendChild(this.ContentFreezeGrid);
let freezeCellHeights = [];
let paddingTop = this.getPaddingTop(this.ContentGridItemRow.cells.item(0));
let paddingBottom = this.getPaddingBottom(this.ContentGridItemRow.cells.item(0));
for (var i = 0; i < this.ContentGrid.rows.length; i++) {
let gridItemRow = this.ContentGrid.rows.item(i);
let gridItemCell = gridItemRow.cells.item(0);
let helperElement;
if ((<HTMLElement>gridItemCell.firstChild).className == "gridViewScrollHelper") {
helperElement = <HTMLDivElement>gridItemCell.firstChild;
}
else {
helperElement = this.appendHelperElement(gridItemCell);
}
let helperHeight = parseInt(String(gridItemCell.offsetHeight - paddingTop - paddingBottom));
freezeCellHeights.push(helperHeight);
let cgridItemRow = <HTMLTableRowElement>gridItemRow.cloneNode(false);
let cgridItemCell = gridItemCell.cloneNode(true);
if (this.FreezeColumnCssClass != null || this.FreezeColumnCssClass != "")
cgridItemRow.className = this.FreezeColumnCssClass;
let columnIndex = 0;
let columnCount = 0;
while (columnCount < this.FreezeColumnCount) {
let freezeColumn = <HTMLTableCellElement>gridItemRow.cells.item(columnIndex).cloneNode(true);
cgridItemRow.appendChild(freezeColumn);
columnCount += freezeColumn.colSpan;
columnIndex++;
}
this.ContentFreezeGrid.appendChild(cgridItemRow);
}
for (var i = 0; i < this.ContentGrid.rows.length; i++) {
let gridItemRow = this.ContentGrid.rows.item(i);
let gridItemCell = gridItemRow.cells.item(0);
let cgridItemRow = this.ContentFreezeGrid.rows.item(i);
let cgridItemCell = cgridItemRow.cells.item(0);
let helperElement = <HTMLDivElement>gridItemCell.firstChild;
helperElement.style.height = String(freezeCellHeights[i]) + "px";
helperElement = <HTMLDivElement>cgridItemCell.firstChild;
helperElement.style.height = String(freezeCellHeights[i]) + "px";
}
if (this.IsVerticalScrollbarEnabled) {
this.ContentFreeze.style.height = String(this.Height - this.Header.offsetHeight - this.ScrollbarWidth) + "px";
}
else {
this.ContentFreeze.style.height = String(this.ContentFixed.offsetHeight - this.ScrollbarWidth) + "px";
}
this.ContentFreeze = this.Content.appendChild(this.ContentFreeze);
}
private appendFreezeFooter(): void {
this.FooterFreeze = <HTMLDivElement>document.createElement('div');
this.FooterFreeze.id = this.GridID + "_Footer_Freeze";
this.FooterFreeze.style.position = "absolute";
this.FooterFreeze.style.overflow = "hidden";
this.FooterFreeze.style.left = "0px";
this.FooterFreeze.style.width = String(this.ContentFixed.offsetWidth - this.ScrollbarWidth) + "px";
this.FooterFreezeGrid = <HTMLTableElement>this.HeaderGrid.cloneNode(false);
this.FooterFreezeGrid.id = this.GridID + "_Footer_Freeze_Grid";
this.FooterFreezeGrid = this.FooterFreeze.appendChild(this.FooterFreezeGrid);
this.FooterFreezeGridHeaderRow = <HTMLTableRowElement>this.ContentGridFooterRow.cloneNode(true);
if (this.FreezeFooterCssClass != null || this.FreezeFooterCssClass != "")
this.FooterFreezeGridHeaderRow.className = this.FreezeFooterCssClass;
for (var i = 0; i < this.FooterFreezeGridHeaderRow.cells.length; i++) {
let cgridHeaderCell = this.FooterFreezeGridHeaderRow.cells.item(i);
let helperElement = this.appendHelperElement(cgridHeaderCell);
helperElement.style.width = String(this.FreezeCellWidths[i]) + "px";
}
this.FooterFreezeGridHeaderRow = <HTMLTableRowElement>this.FooterFreezeGrid.appendChild(this.FooterFreezeGridHeaderRow);
this.FooterFreeze = this.Content.appendChild(this.FooterFreeze);
let footerFreezeTop = this.ContentFixed.offsetHeight - this.FooterFreeze.offsetHeight;
if (this.IsHorizontalScrollbarEnabled) {
footerFreezeTop -= this.ScrollbarWidth;
}
this.FooterFreeze.style.top = String(footerFreezeTop) + "px";
}
private appendFreezeFooterColumn(): void {
this.FooterFreezeColumn = <HTMLDivElement>document.createElement('div');
this.FooterFreezeColumn.id = this.GridID + "_Footer_FreezeColumn";
this.FooterFreezeColumn.style.position = "absolute";
this.FooterFreezeColumn.style.overflow = "hidden";
this.FooterFreezeColumn.style.left = "0px";
this.FooterFreezeColumn.style.width = "";
this.FooterFreezeColumnGrid = <HTMLTableElement>this.HeaderGrid.cloneNode(false);
this.FooterFreezeColumnGrid.id = this.GridID + "_Footer_FreezeColumn_Grid";
this.FooterFreezeColumnGrid = this.FooterFreezeColumn.appendChild(this.FooterFreezeColumnGrid);
this.FooterFreezeColumnGridHeaderRow = <HTMLTableRowElement>this.FooterFreezeGridHeaderRow.cloneNode(false);
this.FooterFreezeColumnGridHeaderRow = <HTMLTableRowElement>this.FooterFreezeColumnGrid.appendChild(this.FooterFreezeColumnGridHeaderRow);
if (this.FreezeFooterCssClass != null)
this.FooterFreezeColumnGridHeaderRow.className = this.FreezeFooterCssClass;
let columnIndex = 0;
let columnCount = 0;
while (columnCount < this.FreezeColumnCount) {
let freezeColumn = <HTMLTableCellElement>this.FooterFreezeGridHeaderRow.cells.item(columnIndex).cloneNode(true);
this.FooterFreezeColumnGridHeaderRow.appendChild(freezeColumn);
columnCount += freezeColumn.colSpan;
columnIndex++;
}
let footerFreezeTop = this.ContentFixed.offsetHeight - this.FooterFreeze.offsetHeight;
if (this.IsHorizontalScrollbarEnabled) {
footerFreezeTop -= this.ScrollbarWidth;
}
this.FooterFreezeColumn.style.top = String(footerFreezeTop) + "px";
this.FooterFreezeColumn = this.Content.appendChild(this.FooterFreezeColumn);
}
private appendHelperElement(gridItemCell: HTMLTableCellElement): HTMLDivElement {
let helperElement = <HTMLDivElement>document.createElement('div');
helperElement.className = "gridViewScrollHelper";
while (gridItemCell.hasChildNodes()) {
helperElement.appendChild(gridItemCell.firstChild);
}
return gridItemCell.appendChild(helperElement);
}
private getScrollbarWidth(): number {
var innerElement = document.createElement('p');
innerElement.style.width = "100%";
innerElement.style.height = "200px";
var outerElement = document.createElement('div');
outerElement.style.position = "absolute";
outerElement.style.top = "0px";
outerElement.style.left = "0px";
outerElement.style.visibility = "hidden";
outerElement.style.width = "200px";
outerElement.style.height = "150px";
outerElement.style.overflow = "hidden";
outerElement.appendChild(innerElement);
document.body.appendChild(outerElement);
var innerElementWidth = innerElement.offsetWidth;
outerElement.style.overflow = 'scroll';
var outerElementWidth = innerElement.offsetWidth;
if (innerElementWidth === outerElementWidth) outerElementWidth = outerElement.clientWidth;
document.body.removeChild(outerElement);
return innerElementWidth - outerElementWidth;
}
private isRTL(): boolean {
let direction = "";
if (window.getComputedStyle) {
direction = window.getComputedStyle(this.ContentGrid, null).getPropertyValue('direction');
} else {
direction = (<any>this.ContentGrid).currentStyle.direction;
}
return direction === "rtl";
}
private getPaddingTop(element: HTMLElement): number {
let value = "";
if (window.getComputedStyle) {
value = window.getComputedStyle(element, null).getPropertyValue('padding-Top');
} else {
value = (<any>element).currentStyle.paddingTop;
}
return parseInt(value);
}
private getPaddingBottom(element: HTMLElement): number {
let value = "";
if (window.getComputedStyle) {
value = window.getComputedStyle(element, null).getPropertyValue('padding-Bottom');
} else {
value = (<any>element).currentStyle.paddingBottom;
}
return parseInt(value);
}
undo(): void {
this.undoHelperElement();
for (let contentGridHeaderRow of this.ContentGridHeaderRows) {
contentGridHeaderRow.style.display = "";
}
this.Parent.insertBefore(this.ContentGrid, this.Header);
this.Parent.removeChild(this.Header);
this.Parent.removeChild(this.Content);
this._initialized = false;
}
private undoHelperElement(): void {
for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {
let gridItemCell = this.ContentGridItemRow.cells.item(i);
let helperElement = <HTMLDivElement>gridItemCell.firstChild;
while (helperElement.hasChildNodes()) {
gridItemCell.appendChild(helperElement.firstChild);
}
gridItemCell.removeChild(helperElement);
}
if (this.FreezeColumn) {
for (var i = 2; i < this.ContentGrid.rows.length; i++) {
let gridItemRow = this.ContentGrid.rows.item(i);
let gridItemCell = gridItemRow.cells.item(0);
let helperElement = <HTMLDivElement>gridItemCell.firstChild;
while (helperElement.hasChildNodes()) {
gridItemCell.appendChild(helperElement.firstChild);
}
gridItemCell.removeChild(helperElement);
}
}
}
} | the_stack |
import { Subscription } from 'expo-modules-core';
import * as Notifications from 'expo-notifications';
import * as TaskManager from 'expo-task-manager';
import React from 'react';
import { Alert, Platform, ScrollView, View } from 'react-native';
import registerForPushNotificationsAsync from '../api/registerForPushNotificationsAsync';
import HeadingText from '../components/HeadingText';
import ListButton from '../components/ListButton';
import MonoText from '../components/MonoText';
const BACKGROUND_NOTIFICATION_TASK = 'BACKGROUND-NOTIFICATION-TASK';
const BACKGROUND_TASK_SUCCESSFUL = 'Background task successfully ran!';
const BACKGROUND_TEST_INFO = `To test background notification handling:\n(1) Background the app.\n(2) Send a push notification from your terminal. The push token can be found in your logs, and the command to send a notification can be found at https://docs.expo.io/push-notifications/sending-notifications/#http2-api. On iOS, you need to include "_contentAvailable": "true" in your payload.\n(3) After receiving the notification, check your terminal for:\n"${BACKGROUND_TASK_SUCCESSFUL}"`;
TaskManager.defineTask(BACKGROUND_NOTIFICATION_TASK, (_data) => {
console.log(BACKGROUND_TASK_SUCCESSFUL);
});
export default class NotificationScreen extends React.Component<
// See: https://github.com/expo/expo/pull/10229#discussion_r490961694
// eslint-disable-next-line @typescript-eslint/ban-types
{},
{
lastNotifications?: Notifications.Notification;
}
> {
static navigationOptions = {
title: 'Notifications',
};
private _onReceivedListener: Subscription | undefined;
private _onResponseReceivedListener: Subscription | undefined;
// See: https://github.com/expo/expo/pull/10229#discussion_r490961694
// eslint-disable-next-line @typescript-eslint/ban-types
constructor(props: {}) {
super(props);
this.state = {};
}
componentDidMount() {
if (Platform.OS !== 'web') {
this._onReceivedListener = Notifications.addNotificationReceivedListener(
this._handelReceivedNotification
);
this._onResponseReceivedListener = Notifications.addNotificationResponseReceivedListener(
this._handelNotificationResponseReceived
);
Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK);
// Using the same category as in `registerForPushNotificationsAsync`
Notifications.setNotificationCategoryAsync('welcome', [
{
buttonTitle: `Don't open app`,
identifier: 'first-button',
options: {
opensAppToForeground: false,
},
},
{
buttonTitle: 'Respond with text',
identifier: 'second-button-with-text',
textInput: {
submitButtonTitle: 'Submit button',
placeholder: 'Placeholder text',
},
},
{
buttonTitle: 'Open app',
identifier: 'third-button',
options: {
opensAppToForeground: true,
},
},
])
.then((_category) => {})
.catch((error) => console.warn('Could not have set notification category', error));
}
}
componentWillUnmount() {
this._onReceivedListener?.remove();
this._onResponseReceivedListener?.remove();
}
render() {
return (
<ScrollView contentContainerStyle={{ padding: 10, paddingBottom: 40 }}>
<HeadingText>Local Notifications</HeadingText>
<ListButton
onPress={this._presentLocalNotificationAsync}
title="Present a notification immediately"
/>
<ListButton
onPress={this._scheduleLocalNotificationAsync}
title="Schedule notification for 10 seconds from now"
/>
<ListButton
onPress={this._scheduleLocalNotificationWithCustomSoundAsync}
title="Schedule notification with custom sound in 1 second (not supported in Expo Go)"
/>
<ListButton
onPress={this._scheduleLocalNotificationAndCancelAsync}
title="Schedule notification for 10 seconds from now and then cancel it immediately"
/>
<ListButton
onPress={Notifications.cancelAllScheduledNotificationsAsync}
title="Cancel all scheduled notifications"
/>
<HeadingText>Push Notifications</HeadingText>
<ListButton onPress={this._sendNotificationAsync} title="Send me a push notification" />
<BackgroundNotificationHandlingSection />
<HeadingText>Badge Number</HeadingText>
<ListButton
onPress={this._incrementIconBadgeNumberAsync}
title="Increment the app icon's badge number"
/>
<ListButton onPress={this._clearIconBadgeAsync} title="Clear the app icon's badge number" />
<HeadingText>Dismissing notifications</HeadingText>
<ListButton
onPress={this._countPresentedNotifications}
title="Count presented notifications"
/>
<ListButton onPress={this._dismissSingle} title="Dismiss a single notification" />
<ListButton onPress={this._dismissAll} title="Dismiss all notifications" />
{this.state.lastNotifications && (
<MonoText containerStyle={{ marginBottom: 20 }}>
{JSON.stringify(this.state.lastNotifications, null, 2)}
</MonoText>
)}
<HeadingText>Notification Permissions</HeadingText>
<ListButton onPress={this.getPermissionsAsync} title="Get permissions" />
<ListButton onPress={this.requestPermissionsAsync} title="Request permissions" />
<HeadingText>Notification triggers debugging</HeadingText>
<ListButton
onPress={() =>
Notifications.getNextTriggerDateAsync({ seconds: 10 }).then((timestamp) =>
alert(new Date(timestamp!))
)
}
title="Get next date for time interval + 10 seconds"
/>
<ListButton
onPress={() =>
Notifications.getNextTriggerDateAsync({
hour: 9,
minute: 0,
repeats: true,
}).then((timestamp) => alert(new Date(timestamp!)))
}
title="Get next date for 9 AM"
/>
<ListButton
onPress={() =>
Notifications.getNextTriggerDateAsync({
hour: 9,
minute: 0,
weekday: 1,
repeats: true,
}).then((timestamp) => alert(new Date(timestamp!)))
}
title="Get next date for Sunday, 9 AM"
/>
</ScrollView>
);
}
_handelReceivedNotification = (notification: Notifications.Notification) => {
this.setState({
lastNotifications: notification,
});
};
_handelNotificationResponseReceived = (
notificationResponse: Notifications.NotificationResponse
) => {
console.log({ notificationResponse });
// Calling alert(message) immediately fails to show the alert on Android
// if after backgrounding the app and then clicking on a notification
// to foreground the app
setTimeout(() => Alert.alert('You clicked on the notification 🥇'), 1000);
};
private getPermissionsAsync = async () => {
const permission = await Notifications.getPermissionsAsync();
console.log('Get permission: ', permission);
alert(`Status: ${permission.status}`);
};
private requestPermissionsAsync = async () => {
const permission = await Notifications.requestPermissionsAsync();
alert(`Status: ${permission.status}`);
};
_obtainUserFacingNotifPermissionsAsync = async () => {
let permission = await Notifications.getPermissionsAsync();
if (permission.status !== 'granted') {
permission = await Notifications.requestPermissionsAsync();
if (permission.status !== 'granted') {
Alert.alert(`We don't have permission to present notifications.`);
}
}
return permission;
};
_obtainRemoteNotifPermissionsAsync = async () => {
let permission = await Notifications.getPermissionsAsync();
if (permission.status !== 'granted') {
permission = await Notifications.requestPermissionsAsync();
if (permission.status !== 'granted') {
Alert.alert(`We don't have permission to receive remote notifications.`);
}
}
return permission;
};
_presentLocalNotificationAsync = async () => {
await this._obtainUserFacingNotifPermissionsAsync();
await Notifications.scheduleNotificationAsync({
content: {
title: 'Here is a scheduled notification!',
body: 'This is the body',
data: {
hello: 'there',
future: 'self',
},
sound: true,
},
trigger: null,
});
};
_scheduleLocalNotificationAsync = async () => {
await this._obtainUserFacingNotifPermissionsAsync();
await Notifications.scheduleNotificationAsync({
content: {
title: 'Here is a local notification!',
body: 'This is the body',
data: {
hello: 'there',
future: 'self',
},
sound: true,
},
trigger: {
seconds: 10,
},
});
};
_scheduleLocalNotificationWithCustomSoundAsync = async () => {
await this._obtainUserFacingNotifPermissionsAsync();
// Prepare the notification channel
await Notifications.setNotificationChannelAsync('custom-sound', {
name: 'Notification with custom sound',
importance: Notifications.AndroidImportance.HIGH,
sound: 'cat.wav', // <- for Android 8.0+
});
await Notifications.scheduleNotificationAsync({
content: {
title: 'Here is a local notification!',
body: 'This is the body',
data: {
hello: 'there',
future: 'self',
},
sound: 'cat.wav',
},
trigger: {
channelId: 'custom-sound',
seconds: 1,
},
});
};
_scheduleLocalNotificationAndCancelAsync = async () => {
await this._obtainUserFacingNotifPermissionsAsync();
const notificationId = await Notifications.scheduleNotificationAsync({
content: {
title: 'This notification should not appear',
body: 'It should have been cancelled. :(',
sound: true,
},
trigger: {
seconds: 10,
},
});
await Notifications.cancelScheduledNotificationAsync(notificationId);
};
_incrementIconBadgeNumberAsync = async () => {
const currentNumber = await Notifications.getBadgeCountAsync();
await Notifications.setBadgeCountAsync(currentNumber + 1);
const actualNumber = await Notifications.getBadgeCountAsync();
Alert.alert(`Set the badge number to ${actualNumber}`);
};
_clearIconBadgeAsync = async () => {
await Notifications.setBadgeCountAsync(0);
Alert.alert(`Cleared the badge`);
};
_sendNotificationAsync = async () => {
const permission = await this._obtainRemoteNotifPermissionsAsync();
if (permission.status === 'granted') {
registerForPushNotificationsAsync();
}
};
_countPresentedNotifications = async () => {
const presentedNotifications = await Notifications.getPresentedNotificationsAsync();
Alert.alert(`You currently have ${presentedNotifications.length} notifications presented`);
};
_dismissAll = async () => {
await Notifications.dismissAllNotificationsAsync();
Alert.alert(`Notifications dismissed`);
};
_dismissSingle = async () => {
const presentedNotifications = await Notifications.getPresentedNotificationsAsync();
if (!presentedNotifications.length) {
Alert.alert(`No notifications to be dismissed`);
return;
}
const identifier = presentedNotifications[0].request.identifier;
await Notifications.dismissNotificationAsync(identifier);
Alert.alert(`Notification dismissed`);
};
}
/**
* If this test is failing for you on iOS, make sure you:
*
* - Have the `remote-notification` UIBackgroundMode in app.json or info.plist
* - Included "_contentAvailable": "true" in your notification payload
* - Have "Background App Refresh" enabled in your Settings
*
* If it's still not working, try killing the rest of your active apps, since the OS
* may still decide not to launch the app for its own reasons.
*/
function BackgroundNotificationHandlingSection() {
const [showInstructions, setShowInstructions] = React.useState(false);
return (
<View>
{showInstructions ? (
<View>
<ListButton
onPress={() => setShowInstructions(false)}
title="Hide background notification handling instructions"
/>
<MonoText>{BACKGROUND_TEST_INFO}</MonoText>
</View>
) : (
<ListButton
onPress={() => {
setShowInstructions(true);
getPermissionsAndLogToken();
}}
title="Show background notification handling instructions"
/>
)}
</View>
);
}
async function getPermissionsAndLogToken() {
let permission = await Notifications.getPermissionsAsync();
if (permission.status !== 'granted') {
permission = await Notifications.requestPermissionsAsync();
if (permission.status !== 'granted') {
Alert.alert(`We don't have permission to receive remote notifications.`);
}
}
if (permission.status === 'granted') {
const { data: token } = await Notifications.getExpoPushTokenAsync();
console.log(`Got this device's push token: ${token}`);
}
} | the_stack |
import { Guid } from 'guid-typescript';
import { Logger } from './Logger';
import { cdmStatusLevel, cdmLogCode, CdmCorpusContext, environmentType } from '../../internal';
import { CdmHttpClient, CdmHttpResponse, CdmHttpRequest } from '../Network';
import { TelemetryClient } from './TelemetryClient';
import { TelemetryConfig } from './TelemetryConfig';
export class TelemetryKustoClient implements TelemetryClient {
/**
* Maximum number of retries allowed for an HTTP request.
*/
public maxNumRetries: number = 5;
/**
* Maximum timeout for completing an HTTP request including retries.
*/
public maxTimeoutMilliseconds: number = 10000;
/**
* Maximum timeout for a single HTTP request.
*/
public timeoutMilliseconds: number = 1000;
/**
* The CDM corpus context.
*/
private ctx: CdmCorpusContext;
/**
* The Kusto configuration.
*/
private config: TelemetryConfig;
/**
* Indicates whether the telemetry client is enabled or not.
*/
private isEnabled: boolean = false;
/**
* Queuing all log ingestion request to Kusto
*/
private requestQueue: Array<[cdmStatusLevel, string]>;
/**
* The timestamp when the telemetry client is enabled.
*/
private lastIngestionTime: Date;
/**
* An HTTP client for post requests which ingests data into Kusto.
*/
private readonly httpClient: CdmHttpClient;
/**
* Kusto data ingestion command.
*/
private readonly ingestionCommand: string = '.ingest inline into table';
/**
* The frequency in millisecond by which to check and ingest the request queue.
*/
private readonly ingestionFrequency: number = 500;
/**
* The maximum size of the request queue.
*/
private readonly requestQueueMaxSize: number = 200;
/**
* The time in millisecond to pause sending http request when throttling.
*/
private static readonly backoffForThrottling: number = 200;
private readonly logExecTimeMethods: string[] = [
'createResolvedEntityAsync',
'calculateEntityGraphAsync',
'calculateEntityGraphAsync(perEntity)'
];
/**
* Constructs a telemetry client for ingesting logs into Kusto.
* @param ctx The CDM corpus context.
* @param config The configuration for the client.
*/
constructor(ctx: CdmCorpusContext, config: TelemetryConfig) {
this.ctx = ctx;
this.config = config;
this.httpClient = new CdmHttpClient();
this.requestQueue = new Array<[cdmStatusLevel, string]>();
}
/**
* Enqueue the request queue with the information to be logged.
* @param timestamp The log timestamp.
* @param level Logging status level.
* @param className Usually the class that is calling the method.
* @param method Usually denotes method calling this method.
* @param corpusPath Usually denotes corpus path of document.
* @param message Informational message.
* @param requireIngestion (Optional) Whether the log needs to be ingested.
* @param code (Optional) Error or warning code.
*/
public addToIngestionQueue(timestamp: string, level: cdmStatusLevel, className: string, method: string,
corpusPath: string, message: string, requireIngestion: boolean = false, code: cdmLogCode = cdmLogCode.None): void {
// Check if the Kusto config and the concurrent queue has been initialized
if (this.config === undefined || this.requestQueue === undefined) {
return;
}
// Skip if the telemetry client is not enabled
if (!this.isEnabled) {
return
}
// Not ingest logs from telemetry client to avoid cycling
if (className === TelemetryKustoClient.name) {
return;
}
// If ingestion is not required and the level is Progress
if (level === cdmStatusLevel.progress && !requireIngestion) {
// If the execution time needs to be logged
if (this.logExecTimeMethods.includes(method)) {
// Check if the log contains execution time info
const execTimeMessage: string = 'Leaving scope. Time elapsed:';
// Skip if the log is not for execution time
if (!message.startsWith(execTimeMessage)) {
return;
}
}
// Skip if the method execution time doesn't need to be logged
else {
return;
}
}
// Configured in case no user-created content can be ingested into Kusto due to compliance issue
// Note: The RemoveUserContent property could be deleted in the if the compliance issue gets resolved
if (this.config.removeUserContent) {
corpusPath = null;
if (level === cdmStatusLevel.warning || level === cdmStatusLevel.error) {
message = null;
}
}
const logEntry = this.processLogEntry(timestamp, className, method, message, code, corpusPath,
this.ctx.correlationId, this.ctx.events.apiCorrelationId, this.ctx.corpus.appId);
// Add the status level and log entry to the queue to be ingested
this.requestQueue.push([level, logEntry]);
const currentTime: Date = new Date();
// Ingest when request queue exceeds max size or by ingestion frequency
if (this.requestQueue.length >= this.requestQueueMaxSize ||
(currentTime.valueOf() - this.lastIngestionTime.valueOf()) > this.ingestionFrequency) {
this.lastIngestionTime = currentTime;
this.ingestRequestQueue();
}
}
/**
* Check if all the requests have been ingested.
* @returns A Boolean indicating whether the queue is empty or not.
*/
public checkRequestQueueIsEmpty(): boolean {
if (this.requestQueue === undefined || this.requestQueue.length === 0) {
return true;
}
return false;
}
/**
* Enable the telemetry client which ingests logs into Kusto database.
*/
public enable(): void {
// Check if the Kusto config and the concurrent queue has been initialized
if (this.config == null || this.requestQueue == null) {
const message: string = "The telemetry client has not been initialized";
Logger.warning(this.ctx, TelemetryKustoClient.name, "enable", null, cdmLogCode.WarnTelemetryIngestionFailed, message);
return;
}
this.isEnabled = true;
this.lastIngestionTime = new Date();
}
/**
* Get an authorization token and send the query to Kusto.
* @param query The Kusto query command to be posted to the cluster.
*/
public async postKustoQuery(query: string): Promise<void> {
const authToken: string = await this.config.getAuthenticationToken();
const queryEndpoint = `https://${this.config.kustoClusterName}.kusto.windows.net/v1/rest/mgmt`;
const kustoHost = `${this.config.kustoClusterName}.kusto.windows.net`;
const queryBody = `{"db":"${this.config.kustoDatabaseName}","csl":"${query}"}`;
const headers: Map<string, string> = new Map<string, string>([
['Accept', 'application/json'],
['Authorization', authToken],
['Host', kustoHost]
]);
const httpRequest = new CdmHttpRequest(queryEndpoint);
httpRequest.method = 'POST';
httpRequest.headers = headers;
httpRequest.content = queryBody;
httpRequest.contentType = 'application/json';
httpRequest.numberOfRetries = this.maxNumRetries;
httpRequest.timeout = this.timeoutMilliseconds;
httpRequest.maximumTimeout = this.maxTimeoutMilliseconds;
const response: CdmHttpResponse = await this.httpClient.SendAsync(httpRequest, this.getRetryWaitTime, this.ctx);
if (response === undefined) {
throw new Error('Kusto query post failed. The result of a request is undefined.');
}
if (!response.isSuccessful) {
throw new Error(`Kusto query post failed. HTTP ${response.statusCode} - ${response.reason}.`);
}
}
/**
* A callback function for http request retries.
* @param response The Http response.
* @param hasFailed Indicates whether the request has failed.
* @param retryNumber The number of retries happened.
* @returns The wait time before starting the next retry.
*/
private getRetryWaitTime(response: CdmHttpResponse, hasFailed: boolean, retryNumber: number): number {
if (response !== undefined && ((response.isSuccessful && !hasFailed))) {
return undefined;
} else {
// Default wait time is calculated using exponential backoff with with random jitter value to avoid 'waves'.
const upperBound: number = 1 << retryNumber;
return Math.floor(Math.random() * upperBound) * TelemetryKustoClient.backoffForThrottling;
}
}
/**
* Ingest log entries into the table specified.
* @param logTable The table to be ingested into.
* @param logEntries Batched log entries.
*/
private async ingestIntoTable(logTable: string, logEntries: string): Promise<void> {
if (logEntries !== undefined && logEntries.length !== 0) {
const query: string = `${this.ingestionCommand} ${logTable} <|\n${logEntries}`;
try {
await this.postKustoQuery(query);
} catch (e) {
Logger.warning(this.ctx, TelemetryKustoClient.name, this.ingestIntoTable.name, null, cdmLogCode.WarnTelemetryIngestionFailed, e);
}
}
}
/**
* Ingest all the logs existing in the request queue.
*/
public async ingestRequestQueue() {
// Dequeue and send the ingestion request if the queue is not empty
if (this.requestQueue.length !== 0) {
// Batch log entries for each table
let infoLogEntries: string = '';
let warningLogEntries: string = '';
let errorLogEntries: string = '';
let request: [cdmStatusLevel, string];
// Try to dequeue the first request in the queue
while ((request = this.requestQueue.shift()) !== undefined) {
const logEntry: string = request[1];
switch (request[0]) {
case cdmStatusLevel.progress:
infoLogEntries += logEntry;
break;
case cdmStatusLevel.warning:
warningLogEntries += logEntry;
break;
case cdmStatusLevel.error:
errorLogEntries += logEntry;
break;
default:
break;
}
}
// Ingest logs into corresponding tables in the Kusto database
if (this.ctx !== undefined && this.config !== undefined) {
if (infoLogEntries.length !== 0) {
await this.ingestIntoTable(this.config.kustoInfoLogTable, infoLogEntries);
}
if (warningLogEntries.length !== 0) {
await this.ingestIntoTable(this.config.kustoWarningLogTable, warningLogEntries);
}
if (errorLogEntries.length !== 0) {
await this.ingestIntoTable(this.config.kustoErrorLogTable, errorLogEntries);
}
}
}
}
/**
* Process the input log information to remove all unauthorized information.
* @param timestamp The log timestamp.
* @param className Usually the class that is calling the method.
* @param method Usually denotes method calling this method.
* @param message Informational message.
* @param logCode Error code, usually empty.
* @param corpusPath Usually denotes corpus path of document.
* @param correlationId The corpus correlation id.
* @param apiCorrelationId The method correlation id.
* @param appId The app id assigned by user.
* @return A complete log entry.
*/
private processLogEntry(timestamp: string, className: string, method: string, message: string,
logCode: cdmLogCode, corpusPath: string, correlationId: string, apiCorrelationId: Guid, appId: string): string {
// Remove user created contents
if (this.config.ingestAtLevel === environmentType.PROD || this.config.ingestAtLevel === environmentType.TEST) {
corpusPath = null;
}
if (message === null || message === undefined) {
message = '';
}
// Remove all commas from message to ensure the correct syntax of Kusto query
message = message.replace(',', ';');
const code: string = cdmLogCode[logCode];
// Additional properties associated with the log
const property: Map<string, string> = new Map<string, string>([
['Environment', this.config.ingestAtLevel.toString()],
['SDKLanguage', 'TypeScript'],
['Region', this.config.region]
]);
const propertyJson: string = this.serializeMap(property);
return `${timestamp},${className},${method},${message},${code},${corpusPath},${correlationId},${apiCorrelationId},${appId},${propertyJson}\n`;
}
/**
* Serialize the map and return a string.
* @param map The map object to be serialized.
* @returns The serialized map.
*/
private serializeMap(map: Map<string, string>): string {
let mapAsString: string = '';
for (const key of map.keys()) {
mapAsString += `${key}:${map.get(key)};`
}
return mapAsString;
}
} | the_stack |
import { string as yupString, addMethod, ref, object as yupObject, array, bool as yupBool } from 'yup';
const validationStyle = {
warningStyle: 'color: #C6003F;font-size:medium;',
recommendationStyle: 'font-size:medium;',
specialRecommendationStyle: 'color: #0061C1;font-size:medium;'
};
const VALIDATIONRULES = {
TITLE: {
MIN: 5,
MAX: 50
},
PURPOSE: {
MIN: 40,
MAX: 250
},
EXECUTIVE: {
MIN: 40,
MAX: 250
},
EXECUTIVECOMBINED: {
MIN: 40,
MAX: 250
},
CONTEXTEXPLANATION: {
MIN: 40,
MAX: 500
},
CONTEXTEXPLANATIONCOMBINED: {
MIN: 40,
MAX: 500
},
STATISTICALNOTES: {
MIN: 40,
MAX: 250
},
STRUCTURENOTES: {
MIN: 40,
MAX: 250
},
DATAELEMENTDESCRIPTIONACCESSOR: {
MIN: 0,
MAX: 125
},
ELEMENTDESCRIPTIONACCESSOR: {
MAX: 125
},
ANNOTATIONNOTETITLE: {
MIN: 5,
MAX: 50
},
ANNOTATIONNOTELABEL: {
MIN: 25,
MAX: 125
},
ANNOTATIONACCESSIBILITYDESCRIPTION: {
MIN: 25,
MAX: 125
},
UNIQUEID: {
MIN: 1,
MAX: 125
}
};
const VALIDATIONMESSAGES = {
WARNINGS: {
TITLE: 'Either mainTitle or accessibility.title is required',
LONGDESCRIPTION: 'Either accessibility.longDescription or accessibility.contextExplanation is required',
EXECUTIVESUMMARY: 'Either accessibility.purpose or accessibility.executiveSummary is required',
ONCLICKFUNC: 'accessibility.elementsAreInterface needs a boolean value either true or false',
ANNOTATIONDESCRIPTION: 'Either annotation.accessibilityDescription or annotation.note.label is required',
WARNINGLOGGROUP: 'CHARTNAME has accessibility warnings and other messages',
NORMALIZED: 'Either tooltipLabel or dataLabel should have normalized format'
},
RECOMMENDATIONS: {
EXECUTIVESUMMARY:
'Either accessibility.purpose or accessibility.executiveSummary should have minimum 40 characters and a combined length between 40 and 250 characters',
LONGDESCRIPTION:
'Either accessibility.longDescription or accessibility.contextExplanation should have minimum 40 characters and a combined length between 40 and 500 characters',
TITLE: 'Either mainTitle or accessibility.title should have length between 5 and 50 characters',
STATISTICALNOTES: 'accessibility.statisticalNotes should have length between 40 and 250 characters',
STRUCTURENOTES: 'accessibility.structureNotes should have length between 40 and 250 characters',
DATAELEMENTDESCRIPTIONACCESSOR:
'accessibility.elementDescriptionAccessor should have length between 0 and 125 characters',
ELEMENTDESCRIPTIONACCESSOR:
'Passing accessibility.elementDescriptionAccessor can add description to chart elements',
ANNOTATIONNOTETITLE: 'Should have length between 5 and 50 characters',
ANNOTATIONNOTELABEL: 'Should have length between 25 and 125 characters',
ANNOTATIONACCESSIBILITYDESCRIPTION: 'Should have length between 25 and 125 characters',
UNIQUEID: 'Should have human readable uniqueID',
INCLUDEDATAKEYNAMES:
"accessibility.includeDataKeyNames: data's key names are recommended as human-readable with includeDataKeyNames set to true",
RECOMMENDATIONLOGGROUP: 'CHARTNAME has strong accessibility recommendations',
SPECIALRECOMMENDATION:
'Success! CHARTNAME has met minimum accessibility, we recommend you disable accessibility validation by setting accessibility.disableValidation'
}
};
const ACCESSIBILITYPROPS = {
MAINTITLE: 'mainTitle',
LONGDESCRIPTION: 'longDescription',
CONTEXTEXPLANATION: 'contextExplanation',
PURPOSE: 'purpose',
ONCLICKFUNC: 'onClickFunc',
NOTE: 'note',
DISABLEVALIDATION: 'disableValidation',
INCLUDEDATAKEYNAMES: 'includeDataKeyNames',
CHARTNAME: 'CHARTNAME',
TOOLTIPLABEL: 'tooltipLabel',
DATALABEL: 'dataLabel',
VALUEACCESSOR: 'valueAccessor'
};
const options = {
abortEarly: false
};
const accessibilityWarningsSubSchema = {
requiredSchema: yupString()
.required()
.trim(),
requiredSubSchema: yupObject().shape({
label: yupString()
.required()
.trim()
}),
requiredBooleanSchema: yupBool().required()
};
const getCustomSchema = function(min: number, max: number) {
return yupString()
.required()
.trim()
.min(min)
.max(max);
};
const getCustomRegexSchema = function(regexWord) {
return yupString()
.required()
.trim()
.matches(regexWord);
};
const validateBySchemaRefs = function(
validationMessage: string,
tooltipLabelRef,
dataLabelRef,
valueAccessorRef,
schema
) {
return this.test({
message: validationMessage,
test: function(value) {
const tooltipLabelValue = this.resolve(tooltipLabelRef);
const dataLabelValue = this.resolve(dataLabelRef);
const valueAccessorValue = this.resolve(valueAccessorRef);
if (
value &&
yupString()
.min(1)
.isValidSync(valueAccessorValue, options)
) {
let valueAccessorIndex = Array.prototype.findIndex.call(
tooltipLabelValue.labelAccessor,
el => el.trim() === ('' + valueAccessorValue).trim()
);
return valueAccessorIndex > -1
? schema.isValidSync(((tooltipLabelValue || {}).format || [''])[valueAccessorIndex], options)
: schema.isValidSync((dataLabelValue || {}).format, options);
}
return true;
}
});
};
const validateBySchemaRef = function(validationMessage: string, ref, firstSchema, secondSchema) {
return this.test({
message: validationMessage,
test: function(value) {
secondSchema = secondSchema ? secondSchema : firstSchema;
const refField = this.resolve(ref);
const isFieldValid = firstSchema.isValidSync(value, options);
const isRefFieldValid = secondSchema.isValidSync(refField, options);
return isRefFieldValid || isFieldValid ? true : false;
}
});
};
const validateBySchemaRefBoolean = function(schema, booleanSchema, ref, validationMessage: string) {
return this.test({
message: validationMessage,
test: function(value) {
const refField = this.resolve(ref);
return schema.isValidSync(refField, options)
? booleanSchema.isValidSync(value, { abortyEarly: false, strict: true })
: true;
}
});
};
const validateBySchemaRefAndCondition = function(schema, combinedSchema, ref, validationMessage: string) {
return this.test({
message: validationMessage,
test: function(value) {
const refField = (this.resolve(ref) || '').toString().trim();
const field = (value || '').toString().trim();
const fieldRefFieldCombined = `${refField}${field}`;
const isValidRefField = schema.isValidSync(refField, options);
const isValidField = schema.isValidSync(field, options);
const isValid = combinedSchema.isValidSync(fieldRefFieldCombined, options);
const derivedValidStatus =
(refField.length && !isValidRefField) || (field.length && !isValidField) ? false : true;
return derivedValidStatus && (isValidField || isValidRefField) && isValid ? true : false;
}
});
};
const validateBySchema = function(schema, validationMessage: string) {
return this.test({
message: validationMessage,
test: function(value) {
return schema.isValidSync(value, options);
}
});
};
const getAccessibilityWarningsSchema = function() {
return yupObject().shape({
title: (yupString() as any).validateBySchemaRef(
VALIDATIONMESSAGES.WARNINGS.TITLE,
ref(`\$${ACCESSIBILITYPROPS.MAINTITLE}`),
accessibilityWarningsSubSchema.requiredSchema
),
longDescription: (yupString() as any).validateBySchemaRef(
VALIDATIONMESSAGES.WARNINGS.LONGDESCRIPTION,
ref(`${ACCESSIBILITYPROPS.CONTEXTEXPLANATION}`),
accessibilityWarningsSubSchema.requiredSchema
),
executiveSummary: (yupString() as any).validateBySchemaRef(
VALIDATIONMESSAGES.WARNINGS.EXECUTIVESUMMARY,
ref(`${ACCESSIBILITYPROPS.PURPOSE}`),
accessibilityWarningsSubSchema.requiredSchema
),
elementsAreInterface: (yupBool() as any).validateBySchemaRefBoolean(
accessibilityWarningsSubSchema.requiredSchema,
accessibilityWarningsSubSchema.requiredBooleanSchema,
ref(`\$${ACCESSIBILITYPROPS.ONCLICKFUNC}`),
VALIDATIONMESSAGES.WARNINGS.ONCLICKFUNC
),
normalized: (yupBool() as any).validateBySchemaRefs(
VALIDATIONMESSAGES.WARNINGS.NORMALIZED,
ref(`\$${ACCESSIBILITYPROPS.TOOLTIPLABEL}`),
ref(`\$${ACCESSIBILITYPROPS.DATALABEL}`),
ref(`\$${ACCESSIBILITYPROPS.VALUEACCESSOR}`),
getCustomRegexSchema(/^normalized$/)
),
annotations: array().of(
yupObject().shape({
accessibilityDescription: (yupString() as any).validateBySchemaRef(
VALIDATIONMESSAGES.WARNINGS.ANNOTATIONDESCRIPTION,
ref(`${ACCESSIBILITYPROPS.NOTE}`),
accessibilityWarningsSubSchema.requiredSchema,
accessibilityWarningsSubSchema.requiredSubSchema
)
})
)
});
};
const getAccessibilityRecommendationSchema = function() {
return yupObject().shape({
title: (yupString() as any).validateBySchemaRef(
VALIDATIONMESSAGES.RECOMMENDATIONS.TITLE,
ref(`\$${ACCESSIBILITYPROPS.MAINTITLE}`),
getCustomSchema(VALIDATIONRULES.TITLE.MIN, VALIDATIONRULES.TITLE.MAX)
),
longDescription: (yupString() as any).validateBySchemaRefAndCondition(
getCustomSchema(VALIDATIONRULES.CONTEXTEXPLANATION.MIN, VALIDATIONRULES.CONTEXTEXPLANATION.MAX),
getCustomSchema(VALIDATIONRULES.CONTEXTEXPLANATIONCOMBINED.MIN, VALIDATIONRULES.CONTEXTEXPLANATIONCOMBINED.MAX),
ref(`${ACCESSIBILITYPROPS.CONTEXTEXPLANATION}`),
VALIDATIONMESSAGES.RECOMMENDATIONS.LONGDESCRIPTION
),
executiveSummary: (yupString() as any).validateBySchemaRefAndCondition(
getCustomSchema(VALIDATIONRULES.PURPOSE.MIN, VALIDATIONRULES.PURPOSE.MAX),
getCustomSchema(VALIDATIONRULES.EXECUTIVECOMBINED.MIN, VALIDATIONRULES.EXECUTIVECOMBINED.MAX),
ref(`${ACCESSIBILITYPROPS.PURPOSE}`),
VALIDATIONMESSAGES.RECOMMENDATIONS.EXECUTIVESUMMARY
),
statisticalNotes: (yupString() as any).validateBySchema(
getCustomSchema(VALIDATIONRULES.STATISTICALNOTES.MIN, VALIDATIONRULES.STATISTICALNOTES.MAX),
VALIDATIONMESSAGES.RECOMMENDATIONS.STATISTICALNOTES
),
structureNotes: (yupString() as any).validateBySchema(
getCustomSchema(VALIDATIONRULES.STRUCTURENOTES.MIN, VALIDATIONRULES.STRUCTURENOTES.MAX),
VALIDATIONMESSAGES.RECOMMENDATIONS.STRUCTURENOTES
),
elementDescriptionAccessor: (yupString().nullable() as any).validateBySchema(
yupString()
.nullable()
.max(VALIDATIONRULES.ELEMENTDESCRIPTIONACCESSOR.MAX),
VALIDATIONMESSAGES.RECOMMENDATIONS.ELEMENTDESCRIPTIONACCESSOR
),
annotations: array().of(
yupObject().shape({
note: yupObject().shape({
title: (yupString() as any).validateBySchema(
getCustomSchema(VALIDATIONRULES.ANNOTATIONNOTETITLE.MIN, VALIDATIONRULES.ANNOTATIONNOTETITLE.MAX),
VALIDATIONMESSAGES.RECOMMENDATIONS.ANNOTATIONNOTETITLE
),
label: (yupString() as any).validateBySchema(
getCustomSchema(VALIDATIONRULES.ANNOTATIONNOTELABEL.MIN, VALIDATIONRULES.ANNOTATIONNOTELABEL.MAX),
VALIDATIONMESSAGES.RECOMMENDATIONS.ANNOTATIONNOTELABEL
)
}),
accessibilityDescription: (yupString() as any).validateBySchema(
getCustomSchema(
VALIDATIONRULES.ANNOTATIONACCESSIBILITYDESCRIPTION.MIN,
VALIDATIONRULES.ANNOTATIONACCESSIBILITYDESCRIPTION.MAX
),
VALIDATIONMESSAGES.RECOMMENDATIONS.ANNOTATIONACCESSIBILITYDESCRIPTION
)
})
),
data: array()
.nullable()
.of(
yupObject().shape({
note: (yupString().nullable() as any).validateBySchema(
yupString()
.nullable()
.max(VALIDATIONRULES.DATAELEMENTDESCRIPTIONACCESSOR.MAX),
VALIDATIONMESSAGES.RECOMMENDATIONS.DATAELEMENTDESCRIPTIONACCESSOR
)
})
),
uniqueID: (yupString() as any).validateBySchema(
yupString()
.required()
.trim()
.min(VALIDATIONRULES.UNIQUEID.MIN),
VALIDATIONMESSAGES.RECOMMENDATIONS.UNIQUEID
)
});
};
function validateRecommendations(chartName, accessibilityProps, optionsWithContext, isAnyWarnings) {
const recommendationSpecialMessage = VALIDATIONMESSAGES.RECOMMENDATIONS.SPECIALRECOMMENDATION.replace(
ACCESSIBILITYPROPS.CHARTNAME,
chartName
);
const recommendationGroup = VALIDATIONMESSAGES.RECOMMENDATIONS.RECOMMENDATIONLOGGROUP.replace(
ACCESSIBILITYPROPS.CHARTNAME,
chartName
);
try {
const accessibilityRecommendationSchema = getAccessibilityRecommendationSchema();
accessibilityRecommendationSchema.validateSync(accessibilityProps, optionsWithContext);
if (!isAnyWarnings && accessibilityProps && !accessibilityProps[ACCESSIBILITYPROPS.DISABLEVALIDATION]) {
console.log(`%c ${recommendationSpecialMessage}`, validationStyle.specialRecommendationStyle);
}
} catch (errors) {
let allErrors = {};
if (!isAnyWarnings) {
console.groupCollapsed(`%c ${recommendationGroup}`, validationStyle.recommendationStyle);
}
errors.inner.map(error => {
allErrors[error.path] = error.message;
console.log(`%c ${error.path}: ${error.message}`, validationStyle.recommendationStyle);
});
}
if (!accessibilityProps && !accessibilityProps[ACCESSIBILITYPROPS.INCLUDEDATAKEYNAMES]) {
console.log(`%c ${VALIDATIONMESSAGES.RECOMMENDATIONS.INCLUDEDATAKEYNAMES}`, validationStyle.recommendationStyle);
}
console.groupEnd();
}
function validateWarnings(chartName, accessibilityProps, optionsWithContext) {
const warningGroup = VALIDATIONMESSAGES.WARNINGS.WARNINGLOGGROUP.replace(ACCESSIBILITYPROPS.CHARTNAME, chartName);
try {
const accessibilityWarningSchema = getAccessibilityWarningsSchema();
accessibilityWarningSchema.validateSync(accessibilityProps, optionsWithContext);
return false;
} catch (errors) {
console.groupCollapsed(`%c ${warningGroup}`, validationStyle.warningStyle);
let allErrors = {};
errors.inner.map(error => {
allErrors[error.path] = error.message;
console.warn(`%c ${error.path}: ${error.message}`, validationStyle.warningStyle);
});
return true;
}
}
export interface IOtherProps {
context?: object;
data?: object;
uniqueID?: string;
annotations?: object;
misc?: object;
}
const validateAccessibilityProps = function(
chartName: string,
accessibilityObject: object = {},
otherProps: IOtherProps = { context: {}, data: {}, uniqueID: '', annotations: [], misc: {} }
) {
const { context, annotations, data, uniqueID, misc } = otherProps;
const optionsWithContext = {
context,
abortEarly: false
};
const accessibilityProps = { ...accessibilityObject, annotations, data, uniqueID, ...misc };
addMethod(yupString, 'validateBySchemaRefAndCondition', validateBySchemaRefAndCondition);
addMethod(yupString, 'validateBySchema', validateBySchema);
addMethod(yupBool, 'validateBySchemaRefs', validateBySchemaRefs);
addMethod(yupString, 'validateBySchemaRef', validateBySchemaRef);
addMethod(yupBool, 'validateBySchemaRefBoolean', validateBySchemaRefBoolean);
const isAnyWarnings = validateWarnings(chartName, accessibilityProps, optionsWithContext);
validateRecommendations(chartName, accessibilityProps, optionsWithContext, isAnyWarnings);
};
export { validateAccessibilityProps }; | the_stack |
import { parse, stringify } from 'himalaya-wxml'
import * as t from 'babel-types'
import traverse, { Visitor } from 'babel-traverse'
import { AllKindNode, Attribute, WX_IF, WX_ELSE_IF, WX_ELSE, WX_FOR, parseContent, WX_KEY, Element, WX_FOR_ITEM, WX_FOR_INDEX, NodeType, Text } from './wxml'
import { buildTemplateName, getWXMLsource } from './template'
import * as fs from 'fs'
import { relative, resolve } from 'path'
import { setting, parseCode, buildImportStatement, codeFrameError } from './utils'
import { replaceIdentifier, replaceMemberExpression } from './script'
import { kebabCase } from 'lodash'
const { prettyPrint } = require('html')
interface Result {
ast: t.File
template: string
imports: VueImport[]
}
export function parseVue (dirPath: string, wxml: string, jsCode = ''): Result {
let ast = parseCode(jsCode)
let foundWXInstance = false
const vistor: Visitor = {
BlockStatement (path) {
path.scope.rename('wx', 'Taro')
},
Identifier (path) {
if (path.isReferenced() && path.node.name === 'wx') {
path.replaceWith(t.identifier('Taro'))
}
},
CallExpression (path) {
const callee = path.get('callee')
replaceIdentifier(callee)
replaceMemberExpression(callee)
if (
callee.isIdentifier({ name: 'Page' }) ||
callee.isIdentifier({ name: 'Component' }) ||
callee.isIdentifier({ name: 'App' })
) {
foundWXInstance = true
const componentType = callee.node.name
ast.program.body.push(
t.exportDefaultDeclaration(t.callExpression(
t.identifier('withWeapp'),
[path.node.arguments[0], t.stringLiteral(componentType)]
))
)
// path.insertAfter(t.exportDefaultDeclaration(t.identifier(defaultClassName)))
path.remove()
}
}
}
traverse(ast, vistor)
if (!foundWXInstance) {
ast = parseCode(jsCode + ';Component({})')
traverse(ast, vistor)
}
const taroImport = buildImportStatement('@tarojs/taro', [], 'Taro')
const withWeappImport = buildImportStatement(
'@tarojs/with-weapp',
[],
'withWeapp'
)
ast.program.body.unshift(
taroImport,
withWeappImport
// ...wxses.filter(wxs => !wxs.src.startsWith('./wxs__')).map(wxs => buildImportStatement(wxs.src, [], wxs.module))
)
const { imports, template } = parseWXML(dirPath, wxml, [])
return {
ast,
imports,
template
}
}
export function parseWXML (dirPath: string, wxml: string, imports: VueImport[]) {
// const parseResult = getCacheWxml(dirPath)
// if (parseResult) {
// return parseResult
// }
try {
wxml = prettyPrint(wxml, {
max_char: 0,
indent_char: 0,
unformatted: ['text', 'wxs']
})
} catch (error) {
//
}
const nodes: AllKindNode[] = parse(wxml.trim()).map(node => parseNode(node, dirPath, imports))
const template = generateVueFile(nodes)
return {
nodes,
template,
imports
}
}
function parseElement (element: Element, dirPath: string, imports: VueImport[]): Element | Text {
let forItem = 'item'
let forIndex = 'index'
switch (element.tagName) {
case 'template':
parseTemplate(element, imports)
break
case 'wxs':
parseWXS(element, imports)
break
case 'import':
case 'include':
parseModule(element, dirPath, imports)
return {
type: NodeType.Text,
content: ''
}
default:
break
}
return {
tagName: element.tagName,
type: element.type,
children: element.children.map(child => parseNode(child, dirPath, imports)),
attributes: element.attributes
.filter(a => {
let match = true
if (a.key === WX_FOR_ITEM) {
match = false
// 这里用 `||` 不用 `??` 是因为用户可能会填一个空字符串
forItem = a.value || forItem
} else if (a.key === WX_FOR_INDEX) {
match = false
forIndex = a.value || forIndex
}
return match
}).map(a => {
return parseAttribute(a, forItem, forIndex)
})
}
}
function parseNode (node: AllKindNode, dirPath: string, imports: VueImport[]): AllKindNode {
if (node.type === NodeType.Text) {
return node
} else if (node.type === NodeType.Comment) {
return node
}
return parseElement(node, dirPath, imports)
}
const VUE_IF = 'v-if'
const VUE_ELSE_IF = 'v-else-if'
const VUE_FOR = 'v-for'
const VUE_ELSE = 'v-else'
const VUE_KEY = 'key'
const WX_FOR_2 = 'wx:for-items'
function parseAttribute (attr: Attribute, forItem: string, forIndex: string): Attribute {
let { key, value } = attr
let isVueDirectives = true
const isBind = key.startsWith('bind')
const isCatch = key.startsWith('catch')
const isEvent = isBind || isCatch
switch (key) {
case WX_IF:
key = VUE_IF
break
case WX_ELSE_IF:
key = VUE_ELSE_IF
break
case WX_ELSE:
key = VUE_ELSE
break
case WX_FOR:
case WX_FOR_2:
key = VUE_FOR
break
case WX_KEY:
key = VUE_KEY
value = value || forIndex
isVueDirectives = false
break
default:
isVueDirectives = false
break
}
const { type, content } = parseContent(value ?? '', true)
if (type === 'expression') {
if (content?.startsWith('(') && content.endsWith(')')) {
value = content.slice(1, content.length - 1)
} else {
value = content
}
if (key === VUE_FOR) {
value = `(${forItem}, ${forIndex}) in ${value}`
}
if (key === 'data') {
if (value.includes(':') || (value.includes('...') && value.includes(','))) {
value = `{ ${value} }`
}
}
if (!isVueDirectives && !isEvent) {
key = ':' + key
}
}
if (key === VUE_KEY) {
// 微信小程序真的太多没在文档里的用法了
if (value?.includes('this') || value?.includes('*item')) {
value = forItem
}
if (value !== forItem || value !== forIndex) {
value = `${forItem}.${value} || ${value} || ${forIndex}`
}
key = ':' + key
}
if (value === null && key !== VUE_ELSE) {
value = 'true'
}
if (isBind) {
key = key.replace(/^bind/g, '@')
}
if (isCatch) {
key = key.replace(/^catch/g, '@') + '.stop'
}
if (isEvent && value === 'true') {
value = 'emptyHandler'
}
if (key.startsWith(':')) {
key = ':' + kebabCase(key.slice(1))
} else {
key = kebabCase(key)
}
return {
key,
value
}
}
function createElement (tagName: string): Element {
return {
tagName,
type: NodeType.Element,
children: [],
attributes: []
}
}
export function generateVueFile (children: AllKindNode[]): string {
const template = createElement('template')
const container = createElement('block')
container.children = children
template.children = [container]
return stringify([template])
}
interface VueImport {
name?: string
template?: string
ast?: t.File,
wxs?: boolean
}
export function parseTemplate (element: Element, imports: VueImport[]) {
const { attributes, children } = element
const is = attributes.find(a => a.key === 'is')
const data = attributes.find(a => a.key === 'data')
const name = attributes.find(a => a.key === 'name')
if (name) {
const value = name.value
const { type } = parseContent(value ?? '')
if (type === 'expression') {
console.warn('template 的属性 name 只能是一个字符串,考虑更改以下源码逻辑:\n', stringify(element))
}
const componentName = buildTemplateName(name.key)
const component = parseWXML('', stringify(children), imports)!
imports.push({
name: componentName,
template: component.template
})
} else if (is) {
const value = is.value
if (!value) {
console.warn('template 的 `is` 属性不能为空', stringify(element))
}
const { type } = parseContent(value ?? '')
if (type === 'expression') {
console.warn('template 的属性 is 只能是一个字符串,考虑更改以下源码逻辑:\n', stringify(element))
}
element.tagName = buildTemplateName(value!, false)
element.attributes = []
if (data) {
element.attributes.push({
key: 'data',
value: data.value
})
}
} else {
throw new Error('template 标签必须指名 `is` 或 `name` 任意一个标签:\n' + stringify(element))
}
return element
}
export function parseModule (element: Element, dirPath: string, imports: VueImport[]) {
const { attributes, tagName } = element
const src = attributes.find(a => a.key === 'src')
if (!src) {
throw new Error(`${tagName} 标签必须包含 \`src\` 属性` + '\n' + stringify(element))
}
let srcValue = src.value ?? ''
const { type } = parseContent(srcValue)
if (type === 'expression') {
console.warn(tagName + '的属性 src 只能是一个字符串,考虑更改以下源码逻辑:\n', stringify(element))
}
if (srcValue.startsWith('/')) {
const vpath = resolve(setting.rootPath, srcValue.substr(1))
if (!fs.existsSync(vpath)) {
throw new Error(`import/include 的 src 请填入相对路径再进行转换:src="${srcValue}"`)
}
let relativePath = relative(dirPath, vpath)
relativePath = relativePath.replace(/\\/g, '/')
if (relativePath.indexOf('.') !== 0) {
srcValue = './' + relativePath
}
srcValue = relativePath
}
if (tagName === 'import') {
const wxml = getWXMLsource(dirPath, srcValue, tagName)
const mods = parseWXML(resolve(dirPath, srcValue), wxml, imports || [])?.imports
imports.push(...(mods || []))
} else {
console.warn(`暂不支持 ${tagName} 标签的转换`, '考虑修改源码使用 import 替代\n' + stringify(element))
}
}
function parseWXS (element: Element, imports: VueImport[]) {
let moduleName: string | null = null
let src: string | null = null
const { attributes } = element
for (const attr of attributes) {
const { key, value } = attr
if (key === 'module') {
moduleName = value
}
if (key === 'src') {
src = value
}
}
if (!src) {
const script = element.children.reduce((acc, node) => {
if (node.type === NodeType.Text) {
return acc + node.content
}
return acc
}, '')
src = './wxs__' + moduleName
const ast = parseCode(script)
traverse(ast, {
CallExpression (path) {
if (t.isIdentifier(path.node.callee, { name: 'getRegExp' })) {
console.warn(codeFrameError(path.node, '请使用 JavaScript 标准正则表达式把这个 getRegExp 函数重构。'))
}
}
})
imports.push({
ast,
name: moduleName as string,
wxs: true
} as any)
}
if (!moduleName || !src) {
throw new Error('一个 WXS 需要同时存在两个属性:`wxs`, `src`')
}
} | the_stack |
import VSelect from '../VSelect'
// Utilities
import {
mount,
Wrapper,
} from '@vue/test-utils'
// eslint-disable-next-line max-statements
describe('VSelect.ts', () => {
type Instance = InstanceType<typeof VSelect>
let mountFunction: (options?: object) => Wrapper<Instance>
let el
beforeEach(() => {
el = document.createElement('div')
el.setAttribute('data-app', 'true')
document.body.appendChild(el)
mountFunction = (options = {}) => {
return mount(VSelect, {
// https://github.com/vuejs/vue-test-utils/issues/1130
sync: false,
mocks: {
$vuetify: {
lang: {
t: (val: string) => val,
},
theme: {
dark: false,
},
},
},
...options,
})
}
})
afterEach(() => {
document.body.removeChild(el)
})
it('should select an item !multiple', async () => {
const wrapper = mountFunction()
const input = jest.fn()
const change = jest.fn()
wrapper.vm.$on('input', input)
wrapper.vm.$on('change', change)
wrapper.vm.selectItem('foo')
expect(wrapper.vm.internalValue).toBe('foo')
expect(input).toHaveBeenCalledWith('foo')
expect(input).toHaveBeenCalledTimes(1)
await wrapper.vm.$nextTick()
expect(change).toHaveBeenCalledWith('foo')
expect(change).toHaveBeenCalledTimes(1)
wrapper.setProps({ returnObject: true })
const item = { foo: 'bar' }
wrapper.vm.selectItem(item)
expect(wrapper.vm.internalValue).toBe(item)
expect(input).toHaveBeenCalledWith(item)
expect(input).toHaveBeenCalledTimes(2)
await wrapper.vm.$nextTick()
expect(change).toHaveBeenCalledWith(item)
expect(change).toHaveBeenCalledTimes(2)
})
// TODO: this fails without sync, nextTick doesn't help
// https://github.com/vuejs/vue-test-utils/issues/1130
it.skip('should disable v-list-item', async () => {
const selectItem = jest.fn()
const wrapper = mountFunction({
propsData: {
eager: true,
items: [{ text: 'foo', disabled: true, id: 0 }],
},
methods: { selectItem },
})
const el = wrapper.find('.v-list-item')
el.element.click()
expect(selectItem).not.toHaveBeenCalled()
wrapper.setProps({
items: [{ text: 'foo', disabled: false, id: 0 }],
})
await wrapper.vm.$nextTick()
el.element.click()
expect(selectItem).toHaveBeenCalled()
})
it('should update menu status and focus when menu closes', async () => {
const wrapper = mountFunction()
const menu = wrapper.vm.$refs.menu
wrapper.setData({
isMenuActive: true,
isFocused: true,
})
expect(wrapper.vm.isMenuActive).toBe(true)
expect(wrapper.vm.isFocused).toBe(true)
await wrapper.vm.$nextTick()
expect(menu.isActive).toBe(true)
menu.isActive = false
await wrapper.vm.$nextTick()
expect(wrapper.vm.isMenuActive).toBe(false)
expect(wrapper.vm.isFocused).toBe(false)
})
// TODO: this fails without sync, nextTick doesn't help
// https://github.com/vuejs/vue-test-utils/issues/1130
it.skip('should update model when chips are removed', async () => {
const selectItem = jest.fn()
const wrapper = mountFunction({
propsData: {
chips: true,
deletableChips: true,
items: ['foo'],
value: 'foo',
},
methods: { selectItem },
})
const input = jest.fn()
const change = jest.fn()
wrapper.vm.$on('input', input)
expect(wrapper.vm.internalValue).toEqual('foo')
wrapper.find('.v-chip__close').trigger('click')
expect(input).toHaveBeenCalledTimes(1)
wrapper.setProps({
items: ['foo', 'bar'],
multiple: true,
value: ['foo', 'bar'],
})
wrapper.vm.$on('change', change)
await wrapper.vm.$nextTick()
expect(wrapper.vm.internalValue).toEqual(['foo', 'bar'])
wrapper.find('.v-chip__close').trigger('click')
await wrapper.vm.$nextTick()
expect(selectItem).toHaveBeenCalledTimes(1)
})
// TODO: this fails without sync, nextTick doesn't help
// https://github.com/vuejs/vue-test-utils/issues/1130
it.skip('should set selected index', async () => {
const wrapper = mountFunction({
propsData: {
chips: true,
deletableChips: true,
multiple: true,
items: ['foo', 'bar', 'fizz', 'buzz'],
value: ['foo', 'bar', 'fizz', 'buzz'],
},
})
expect(wrapper.vm.selectedIndex).toBe(-1)
const foo = wrapper.find('.v-chip')
foo.trigger('click')
expect(wrapper.vm.selectedIndex).toBe(0)
wrapper.findAll('.v-chip').at(1).trigger('click')
expect(wrapper.vm.selectedIndex).toBe(1)
wrapper.setProps({ disabled: true })
wrapper.find('.v-chip').trigger('click')
expect(wrapper.vm.selectedIndex).toBe(1)
})
it('should not duplicate items after items update when caching is turned on', async () => {
const wrapper = mountFunction({
propsData: {
cacheItems: true,
returnObject: true,
itemText: 'text',
itemValue: 'id',
items: [],
},
})
wrapper.setProps({ items: [{ id: 1, text: 'A' }] })
expect(wrapper.vm.computedItems).toHaveLength(1)
wrapper.setProps({ items: [{ id: 1, text: 'A' }] })
expect(wrapper.vm.computedItems).toHaveLength(1)
})
// TODO: this fails without sync, nextTick doesn't help
// https://github.com/vuejs/vue-test-utils/issues/1130
it.skip('should cache items', async () => {
const wrapper = mountFunction({
propsData: {
cacheItems: true,
items: [],
},
})
wrapper.setProps({ items: ['bar', 'baz'] })
await wrapper.vm.$nextTick()
expect(wrapper.vm.computedItems).toHaveLength(2)
wrapper.setProps({ items: ['foo'] })
await wrapper.vm.$nextTick()
expect(wrapper.vm.computedItems).toHaveLength(3)
wrapper.setProps({ items: ['bar'] })
await wrapper.vm.$nextTick()
expect(wrapper.vm.computedItems).toHaveLength(3)
})
it('should cache items passed via prop', async () => {
const wrapper = mountFunction({
propsData: {
cacheItems: true,
items: [1, 2, 3, 4],
},
})
expect(wrapper.vm.computedItems).toHaveLength(4)
wrapper.setProps({ items: [5] })
expect(wrapper.vm.computedItems).toHaveLength(5)
})
it('should have an affix', async () => {
const wrapper = mountFunction({
propsData: {
prefix: '$',
suffix: 'lbs',
},
})
expect(wrapper.find('.v-text-field__prefix').element.innerHTML).toBe('$')
expect(wrapper.find('.v-text-field__suffix').element.innerHTML).toBe('lbs')
wrapper.setProps({ prefix: undefined, suffix: undefined })
await wrapper.vm.$nextTick()
expect(wrapper.findAll('.v-text-field__prefix')).toHaveLength(0)
expect(wrapper.findAll('.v-text-field__suffix')).toHaveLength(0)
})
it('should use custom clear icon cb', async () => {
const clearIconCb = jest.fn()
const wrapper = mountFunction({
propsData: {
clearable: true,
items: ['foo'],
value: 'foo',
},
})
wrapper.vm.$on('click:clear', clearIconCb)
wrapper.find('.v-input__icon--clear .v-icon').trigger('click')
expect(clearIconCb).toHaveBeenCalled()
})
it('should populate select[multiple=false] when using value as an object', async () => {
const wrapper = mountFunction({
attachToDocument: true,
propsData: {
items: [
{ text: 'foo', value: { id: { subid: 1 } } },
{ text: 'foo', value: { id: { subid: 2 } } },
],
multiple: false,
value: { id: { subid: 2 } },
},
})
const selections = wrapper.findAll('.v-select__selection')
expect(selections).toHaveLength(1)
})
it('should add color to selected index', async () => {
const wrapper = mountFunction({
propsData: {
multiple: true,
items: ['foo', 'bar'],
value: ['foo'],
},
})
wrapper.vm.selectedIndex = 0
await wrapper.vm.$nextTick()
expect(wrapper.html()).toMatchSnapshot()
})
it('should not react to click when disabled', async () => {
const wrapper = mountFunction({
propsData: { items: ['foo', 'bar'] },
})
const slot = wrapper.find('.v-input__slot')
expect(wrapper.vm.isMenuActive).toBe(false)
slot.trigger('click')
expect(wrapper.vm.isMenuActive).toBe(true)
wrapper.setData({ isMenuActive: false })
wrapper.setProps({ disabled: true })
await wrapper.vm.$nextTick()
expect(wrapper.vm.isMenuActive).toBe(false)
slot.trigger('click')
expect(wrapper.vm.isMenuActive).toBe(false)
})
it('should set the menu index', async () => {
const wrapper = mountFunction()
expect(wrapper.vm.getMenuIndex()).toBe(-1)
wrapper.vm.setMenuIndex(1)
expect(wrapper.vm.getMenuIndex()).toBe(1)
})
// Inspired by https://github.com/vuetifyjs/vuetify/pull/1425 - Thanks @kevmo314
it('should open the select when enter is pressed', async () => {
const wrapper = mountFunction({
propsData: {
items: ['foo', 'bar'],
},
})
wrapper.find('input').trigger('keydown.enter')
await wrapper.vm.$nextTick()
expect(document.body.querySelector('[data-app="true"]')).toMatchSnapshot()
})
it('should open the select when space is pressed', async () => {
const wrapper = mountFunction({
propsData: {
items: ['foo', 'bar'],
},
})
wrapper.find('input').trigger('keydown.space')
await wrapper.vm.$nextTick()
expect(document.body.querySelector('[data-app="true"]')).toMatchSnapshot()
})
it('should open the select is multiple and key up is pressed', async () => {
const wrapper = mountFunction({
propsData: {
multiple: true,
items: ['foo', 'bar'],
},
})
wrapper.find('input').trigger('keydown.up')
await wrapper.vm.$nextTick()
expect(document.body.querySelector('[data-app="true"]')).toMatchSnapshot()
})
it('should open the select is multiple and key down is pressed', async () => {
const wrapper = mountFunction({
propsData: {
multiple: true,
items: ['foo', 'bar'],
},
})
wrapper.find('input').trigger('keydown.down')
await wrapper.vm.$nextTick()
expect(document.body.querySelector('[data-app="true"]')).toMatchSnapshot()
})
it('should return full items if using auto prop', async () => {
const wrapper = mountFunction({
propsData: {
items: [...Array(100).keys()],
},
})
expect(wrapper.vm.virtualizedItems).toHaveLength(20)
wrapper.setProps({ menuProps: 'auto' })
expect(wrapper.vm.virtualizedItems).toHaveLength(100)
})
it('should fallback to using text as value if none present', async () => {
const wrapper = mountFunction({
propsData: {
items: [{
text: 'foo',
}],
},
})
expect(wrapper.vm.getValue(wrapper.vm.items[0])).toBe('foo')
})
it('should accept arrays as values', async () => {
const wrapper = mountFunction({
propsData: {
items: [
{ text: 'Foo', value: ['bar'] },
],
},
})
const input = jest.fn()
wrapper.vm.$on('input', input)
wrapper.vm.selectItem(wrapper.vm.items[0])
await wrapper.vm.$nextTick()
expect(input).toHaveBeenCalledWith(['bar'])
expect(wrapper.vm.selectedItems).toEqual([
{ text: 'Foo', value: ['bar'] },
])
})
it('should update inner input element', async () => {
const wrapper = mountFunction({
propsData: {
items: ['foo', 'bar', 'fizz', 'buzz'],
value: ['fizz'],
},
})
const inputs = wrapper.findAll('input')
const element = inputs.at(1).element
expect(element.value).toEqual('fizz')
wrapper.vm.selectItem(wrapper.vm.items[1])
await wrapper.vm.$nextTick()
expect(element.value).toEqual('bar')
})
it('should pass the name attribute to the inner input element', async () => {
const wrapper = mountFunction({
propsData: {
items: ['foo'],
name: ['bar'],
},
})
const inputs = wrapper.findAll('input')
const element = inputs.at(1).element
expect(element.name).toEqual('bar')
})
}) | the_stack |
import '../../../test/common-test-setup-karma';
import {fixture} from '@open-wc/testing-helpers';
import {html} from 'lit';
import './gr-hovercard-account';
import {GrHovercardAccount} from './gr-hovercard-account';
import {
mockPromise,
query,
queryAndAssert,
stubRestApi,
} from '../../../test/test-utils';
import {
AccountDetailInfo,
AccountId,
EmailAddress,
ReviewerState,
} from '../../../api/rest-api.js';
import {
createAccountDetailWithId,
createChange,
} from '../../../test/test-data-generators.js';
import {GrButton} from '../gr-button/gr-button.js';
suite('gr-hovercard-account tests', () => {
let element: GrHovercardAccount;
const ACCOUNT: AccountDetailInfo = {
...createAccountDetailWithId(31),
email: 'kermit@gmail.com' as EmailAddress,
username: 'kermit',
name: 'Kermit The Frog',
_account_id: 31415926535 as AccountId,
};
setup(async () => {
stubRestApi('getAccount').returns(Promise.resolve({...ACCOUNT}));
const change = {
...createChange(),
attention_set: {},
reviewers: {},
owner: {...ACCOUNT},
};
element = await fixture<GrHovercardAccount>(
html`<gr-hovercard-account
class="hovered"
.account=${ACCOUNT}
.change=${change}
>
</gr-hovercard-account>`
);
await element.show();
await element.updateComplete;
});
teardown(async () => {
await element.hide(new MouseEvent('click'));
await element.updateComplete;
});
test('renders', () => {
expect(element).shadowDom.to.equal(`<div
id="container"
role="tooltip"
tabindex="-1"
>
<div class="top">
<div class="avatar">
<gr-avatar hidden="" imagesize="56"></gr-avatar>
</div>
<div class="account">
<h3 class="heading-3 name">
Kermit The Frog
</h3>
<div class="email">
kermit@gmail.com
</div>
</div>
</div>
</div>
`);
});
test('account name is shown', () => {
const name = queryAndAssert<HTMLHeadingElement>(element, '.name');
assert.equal(name.innerText, 'Kermit The Frog');
});
test('computePronoun', async () => {
element.account = createAccountDetailWithId(1);
element._selfAccount = createAccountDetailWithId(1);
await element.updateComplete;
assert.equal(element.computePronoun(), 'Your');
element.account = createAccountDetailWithId(2);
await element.updateComplete;
assert.equal(element.computePronoun(), 'Their');
});
test('account status is not shown if the property is not set', () => {
assert.isUndefined(query(element, '.status'));
});
test('account status is displayed', async () => {
element.account = {...ACCOUNT, status: 'OOO'};
await element.updateComplete;
const status = queryAndAssert<HTMLSpanElement>(element, '.status .value');
assert.equal(status.innerText, 'OOO');
});
test('voteable div is not shown if the property is not set', () => {
assert.isUndefined(query(element, '.voteable'));
});
test('voteable div is displayed', async () => {
element.voteableText = 'CodeReview: +2';
await element.updateComplete;
const voteableEl = queryAndAssert<HTMLSpanElement>(
element,
'.voteable .value'
);
assert.equal(voteableEl.innerText, element.voteableText);
});
test('remove reviewer', async () => {
element.change = {
...createChange(),
removable_reviewers: [ACCOUNT],
reviewers: {
[ReviewerState.REVIEWER]: [ACCOUNT],
},
};
await element.updateComplete;
stubRestApi('removeChangeReviewer').returns(
Promise.resolve({...new Response(), ok: true})
);
const reloadListener = sinon.spy();
element._target?.addEventListener('reload', reloadListener);
const button = queryAndAssert<GrButton>(element, '.removeReviewerOrCC');
assert.isOk(button);
assert.equal(button.innerText, 'Remove Reviewer');
button.click();
await element.updateComplete;
assert.isTrue(reloadListener.called);
});
test('move reviewer to cc', async () => {
element.change = {
...createChange(),
removable_reviewers: [ACCOUNT],
reviewers: {
[ReviewerState.REVIEWER]: [ACCOUNT],
},
};
await element.updateComplete;
const saveReviewStub = stubRestApi('saveChangeReview').returns(
Promise.resolve({...new Response(), ok: true})
);
stubRestApi('removeChangeReviewer').returns(
Promise.resolve({...new Response(), ok: true})
);
const reloadListener = sinon.spy();
element._target?.addEventListener('reload', reloadListener);
const button = queryAndAssert<GrButton>(element, '.changeReviewerOrCC');
assert.isOk(button);
assert.equal(button.innerText, 'Move Reviewer to CC');
button.click();
await element.updateComplete;
assert.isTrue(saveReviewStub.called);
assert.isTrue(reloadListener.called);
});
test('move reviewer to cc', async () => {
element.change = {
...createChange(),
removable_reviewers: [ACCOUNT],
reviewers: {
[ReviewerState.REVIEWER]: [],
},
};
await element.updateComplete;
const saveReviewStub = stubRestApi('saveChangeReview').returns(
Promise.resolve({...new Response(), ok: true})
);
stubRestApi('removeChangeReviewer').returns(
Promise.resolve({...new Response(), ok: true})
);
const reloadListener = sinon.spy();
element._target?.addEventListener('reload', reloadListener);
const button = queryAndAssert<GrButton>(element, '.changeReviewerOrCC');
assert.isOk(button);
assert.equal(button.innerText, 'Move CC to Reviewer');
button.click();
await element.updateComplete;
assert.isTrue(saveReviewStub.called);
assert.isTrue(reloadListener.called);
});
test('remove cc', async () => {
element.change = {
...createChange(),
removable_reviewers: [ACCOUNT],
reviewers: {
[ReviewerState.REVIEWER]: [],
},
};
await element.updateComplete;
stubRestApi('removeChangeReviewer').returns(
Promise.resolve({...new Response(), ok: true})
);
const reloadListener = sinon.spy();
element._target?.addEventListener('reload', reloadListener);
const button = queryAndAssert<GrButton>(element, '.removeReviewerOrCC');
assert.equal(button.innerText, 'Remove CC');
assert.isOk(button);
button.click();
await element.updateComplete;
assert.isTrue(reloadListener.called);
});
test('add to attention set', async () => {
const apiPromise = mockPromise<Response>();
const apiSpy = stubRestApi('addToAttentionSet').returns(apiPromise);
element.highlightAttention = true;
element._target = document.createElement('div');
await element.updateComplete;
const showAlertListener = sinon.spy();
const hideAlertListener = sinon.spy();
const updatedListener = sinon.spy();
element._target.addEventListener('show-alert', showAlertListener);
element._target.addEventListener('hide-alert', hideAlertListener);
element._target.addEventListener('attention-set-updated', updatedListener);
const button = queryAndAssert<GrButton>(element, '.addToAttentionSet');
assert.isOk(button);
assert.isTrue(element._isShowing, 'hovercard is showing');
button.click();
assert.equal(Object.keys(element.change?.attention_set ?? {}).length, 1);
const attention_set_info = Object.values(
element.change?.attention_set ?? {}
)[0];
assert.equal(
attention_set_info.reason,
`Added by <GERRIT_ACCOUNT_${ACCOUNT._account_id}>` +
' using the hovercard menu'
);
assert.equal(
attention_set_info.reason_account?._account_id,
ACCOUNT._account_id
);
assert.isTrue(showAlertListener.called, 'showAlertListener was called');
assert.isTrue(updatedListener.called, 'updatedListener was called');
assert.isFalse(element._isShowing, 'hovercard is hidden');
apiPromise.resolve({...new Response(), ok: true});
await element.updateComplete;
assert.isTrue(apiSpy.calledOnce);
assert.equal(
apiSpy.lastCall.args[2],
`Added by <GERRIT_ACCOUNT_${ACCOUNT._account_id}>` +
' using the hovercard menu'
);
assert.isTrue(hideAlertListener.called, 'hideAlertListener was called');
});
test('remove from attention set', async () => {
const apiPromise = mockPromise<Response>();
const apiSpy = stubRestApi('removeFromAttentionSet').returns(apiPromise);
element.highlightAttention = true;
element.change = {
...createChange(),
attention_set: {
'31415926535': {account: ACCOUNT, reason: 'a good reason'},
},
reviewers: {},
owner: {...ACCOUNT},
};
element._target = document.createElement('div');
await element.updateComplete;
const showAlertListener = sinon.spy();
const hideAlertListener = sinon.spy();
const updatedListener = sinon.spy();
element._target.addEventListener('show-alert', showAlertListener);
element._target.addEventListener('hide-alert', hideAlertListener);
element._target.addEventListener('attention-set-updated', updatedListener);
const button = queryAndAssert<GrButton>(element, '.removeFromAttentionSet');
assert.isOk(button);
assert.isTrue(element._isShowing, 'hovercard is showing');
button.click();
assert.isDefined(element.change?.attention_set);
assert.equal(Object.keys(element.change?.attention_set ?? {}).length, 0);
assert.isTrue(showAlertListener.called, 'showAlertListener was called');
assert.isTrue(updatedListener.called, 'updatedListener was called');
assert.isFalse(element._isShowing, 'hovercard is hidden');
apiPromise.resolve({...new Response(), ok: true});
await element.updateComplete;
assert.isTrue(apiSpy.calledOnce);
assert.equal(
apiSpy.lastCall.args[2],
`Removed by <GERRIT_ACCOUNT_${ACCOUNT._account_id}>` +
' using the hovercard menu'
);
assert.isTrue(hideAlertListener.called, 'hideAlertListener was called');
});
}); | the_stack |
import aceEvent, { AceEvent } from "@wowts/ace_event-3.0";
import { LuaArray } from "@wowts/lua";
import { huge as infinity } from "@wowts/math";
import { concat, insert } from "@wowts/table";
import { AceModule } from "@wowts/tsaddon";
import {
GetSpellCount,
GetTime,
SpellId,
TalentId,
UnitCastingInfo,
} from "@wowts/wow-mock";
import {
ConditionFunction,
ConditionResult,
OvaleConditionClass,
returnBoolean,
returnConstant,
} from "../engine/condition";
import { DebugTools, Tracer } from "../engine/debug";
import { SpellCastEventHandler, States, StateModule } from "../engine/state";
import { OptionUiGroup } from "../ui/acegui-helpers";
import { OvaleClass } from "../Ovale";
import { Aura, OvaleAuraClass } from "./Aura";
import { SpellCast } from "./LastSpell";
import { OvalePaperDollClass } from "./PaperDoll";
import { OvaleSpellBookClass } from "./SpellBook";
import { OvaleCombatClass } from "./combat";
type EclipseType = "lunar" | "solar";
type EclipseState =
| "any_next"
| "in_both"
| "in_lunar"
| "in_solar"
| "lunar_next"
| "solar_next";
class EclipseData {
starfire = 0;
starfireMax = 0;
wrath = 0;
wrathMax = 0;
}
const balanceSpellId = {
starfire: SpellId.starfire,
wrath: SpellId.wrath_balance,
};
const balanceAffinitySpellId = {
talent: TalentId.balance_affinity_talent,
starfire: 197628,
wrath: SpellId.wrath,
};
const celestialAlignmentId = SpellId.celestial_alignment;
const incarnationId = SpellId.incarnation_chosen_of_elune;
const eclipseLunarId = SpellId.eclipse_lunar_buff;
const eclipseSolarId = SpellId.eclipse_solar_buff;
const leafOnTheWaterId = 334604;
export class Eclipse extends States<EclipseData> implements StateModule {
private module: AceModule & AceEvent;
private tracer: Tracer;
private hasEclipseHandlers = false;
private isCasting = false;
private adjustCount = false;
private starfireId = 0;
private wrathId = 0;
private debugEclipse: OptionUiGroup = {
type: "group",
name: "Eclipse",
args: {
eclipse: {
type: "input",
name: "Eclipse",
multiline: 25,
width: "full",
get: () => {
const output: LuaArray<string> = {};
insert(output, `Starfire spell ID: ${this.starfireId}`);
insert(output, `Wrath spell ID: ${this.wrathId}`);
insert(output, "");
insert(
output,
`Total Starfire(s) to Solar Eclipse: ${this.current.starfireMax}`
);
insert(
output,
`Total Wrath(s) to Lunar Eclipse: ${this.current.starfireMax}`
);
insert(output, "");
insert(
output,
`Starfire(s) to Solar Eclipse: ${this.current.starfire}`
);
insert(
output,
`Wrath(s) to Lunar Eclipse: ${this.current.wrath}`
);
return concat(output, "\n");
},
},
},
};
constructor(
private ovale: OvaleClass,
debug: DebugTools,
private aura: OvaleAuraClass,
private combat: OvaleCombatClass,
private paperDoll: OvalePaperDollClass,
private spellBook: OvaleSpellBookClass
) {
super(EclipseData);
this.module = ovale.createModule(
"Eclipse",
this.onEnable,
this.onDisable,
aceEvent
);
this.tracer = debug.create(this.module.GetName());
debug.defaultOptions.args["eclipse"] = this.debugEclipse;
}
private onEnable = () => {
if (this.ovale.playerClass == "DRUID") {
this.module.RegisterEvent(
"PLAYER_ENTERING_WORLD",
this.onUpdateEclipseHandlers
);
this.module.RegisterMessage(
"Ovale_SpecializationChanged",
this.onUpdateEclipseHandlers
);
this.module.RegisterMessage(
"Ovale_TalentsChanged",
this.onUpdateEclipseHandlers
);
this.onUpdateEclipseHandlers("onEnable");
}
};
private onDisable = () => {
if (this.ovale.playerClass == "DRUID") {
this.module.UnregisterEvent("PLAYER_ENTERING_WORLD");
this.module.UnregisterMessage("Ovale_SpecializationChanged");
this.module.UnregisterMessage("Ovale_TalentsChanged");
this.unregisterEclipseHandlers();
}
};
private onUpdateEclipseHandlers = (event: string) => {
const isBalanceDruid = this.paperDoll.isSpecialization("balance");
const hasBalanceAffinity =
this.spellBook.getTalentPoints(balanceAffinitySpellId.talent) > 0;
if (isBalanceDruid || hasBalanceAffinity) {
if (isBalanceDruid) {
this.starfireId = balanceSpellId.starfire;
this.wrathId = balanceSpellId.wrath;
} else if (hasBalanceAffinity) {
this.starfireId = balanceAffinitySpellId.starfire;
this.wrathId = balanceAffinitySpellId.wrath;
} else {
this.starfireId = 0;
this.wrathId = 0;
}
this.registerEclipseHandlers();
this.updateSpellMaxCounts(event);
this.updateSpellCounts(event);
} else {
this.unregisterEclipseHandlers();
}
};
private registerEclipseHandlers = () => {
if (!this.hasEclipseHandlers) {
this.tracer.debug("Installing eclipse event handlers.");
this.module.RegisterEvent(
"UNIT_SPELLCAST_FAILED",
this.onUnitSpellCastStop
);
this.module.RegisterEvent(
"UNIT_SPELLCAST_FAILED_QUIET",
this.onUnitSpellCastStop
);
this.module.RegisterEvent(
"UNIT_SPELLCAST_INTERRUPTED",
this.onUnitSpellCastStop
);
this.module.RegisterEvent(
"UNIT_SPELLCAST_START",
this.onUnitSpellCastStart
);
this.module.RegisterEvent(
"UNIT_SPELLCAST_STOP",
this.onUnitSpellCastStop
);
this.module.RegisterEvent(
"UNIT_SPELLCAST_SUCCEEDED",
this.onUnitSpellCastSucceeded
);
this.module.RegisterEvent(
"UPDATE_SHAPESHIFT_COOLDOWN",
this.onUpdateShapeshiftCooldown
);
this.module.RegisterMessage(
"Ovale_AuraAdded",
this.onOvaleAuraAddedOrRemoved
);
this.module.RegisterMessage(
"Ovale_AuraRemoved",
this.onOvaleAuraAddedOrRemoved
);
this.hasEclipseHandlers = true;
}
};
private unregisterEclipseHandlers = () => {
if (this.hasEclipseHandlers) {
this.tracer.debug("Removing eclipse event handlers.");
this.module.UnregisterEvent("UNIT_SPELLCAST_FAILED");
this.module.UnregisterEvent("UNIT_SPELLCAST_FAILED_QUIET");
this.module.UnregisterEvent("UNIT_SPELLCAST_INTERRUPTED");
this.module.UnregisterEvent("UNIT_SPELLCAST_START");
this.module.UnregisterEvent("UNIT_SPELLCAST_STOP");
this.module.UnregisterEvent("UNIT_SPELLCAST_SUCCEEDED");
this.module.UnregisterEvent("UPDATE_SHAPESHIFT_COOLDOWN");
this.module.UnregisterMessage("Ovale_AuraAdded");
this.module.UnregisterMessage("Ovale_AuraRemoved");
this.hasEclipseHandlers = false;
}
};
private onUnitSpellCastStart = (
event: string,
unit: string,
castGUID: string,
spellId: number
) => {
if (
unit == "player" &&
(spellId == this.starfireId || spellId == this.wrathId)
) {
// Sanity-check that the current spellcast is what was expected.
const [name, , , , , , , , castSpellId] = UnitCastingInfo(unit);
if (name && spellId == castSpellId) {
this.isCasting = true;
}
}
};
private onUnitSpellCastStop = (
event: string,
unit: string,
castGUID: string,
spellId: number
) => {
if (
unit == "player" &&
(spellId == this.starfireId || spellId == this.wrathId)
) {
this.isCasting = false;
this.adjustCount = false;
}
};
private onUnitSpellCastSucceeded = (
event: string,
unit: string,
castGUID: string,
spellId: number
) => {
const current = this.current;
if (
unit == "player" &&
(spellId == celestialAlignmentId ||
spellId == incarnationId ||
spellId == this.starfireId ||
spellId == this.wrathId)
) {
this.tracer.debug(`${event}: ${spellId}`);
this.isCasting = false;
this.updateSpellCounts(event);
if (this.adjustCount) {
if (spellId == this.starfireId && current.starfire > 0) {
current.starfire = current.starfire - 1;
this.tracer.debug(
"%s: adjust starfire: %d",
event,
current.starfire
);
} else if (spellId == this.wrathId && current.wrath > 0) {
current.wrath = current.wrath - 1;
this.tracer.debug(
"%s: adjust wrath: %d",
event,
current.wrath
);
}
this.adjustCount = false;
}
}
};
private onUpdateShapeshiftCooldown = (event: string) => {
/* When out of combat, this event seems to fire regularly
* every few seconds when the spell counts reset.
*/
if (!this.combat.isInCombat(undefined)) {
this.updateSpellCounts(event);
}
};
private onOvaleAuraAddedOrRemoved = (
event: string,
atTime: number,
guid: string,
auraId: number,
caster: string
) => {
if (guid == this.ovale.playerGUID) {
if (auraId == leafOnTheWaterId) {
this.updateSpellMaxCounts(event, atTime);
} else if (auraId == eclipseLunarId || auraId == eclipseSolarId) {
if (event == "Ovale_AuraRemoved" && this.isCasting) {
/*
* GetSpellCounts() does not yet return the correct
* information at UNIT_SPELLCAST_SUCCEEDED time if the
* count changes mid-cast. If the player is mid-cast
* when the Eclipse ends, then we need to adjust the
* count.
*/
this.adjustCount = true;
}
this.updateSpellCounts(event);
}
}
};
private updateSpellMaxCounts = (event: string, atTime?: number) => {
atTime = atTime || GetTime();
const aura = this.aura.getAura(
"player",
leafOnTheWaterId,
atTime,
"HELPFUL"
);
let starfireMax = 2;
let wrathMax = 2;
if (aura) {
starfireMax = 1;
wrathMax = 1;
}
const current = this.current;
if (
current.starfireMax != starfireMax ||
current.wrathMax != wrathMax
) {
current.starfireMax = starfireMax;
current.wrathMax = wrathMax;
this.tracer.debug(
"%s: starfireMax: %d, wrathMax: %d",
event,
starfireMax,
wrathMax
);
this.ovale.needRefresh();
}
};
private updateSpellCounts = (event: string) => {
const current = this.current;
const starfire = GetSpellCount(this.starfireId);
const wrath = GetSpellCount(this.wrathId);
if (current.starfire != starfire || current.wrath != wrath) {
current.starfire = starfire;
current.wrath = wrath;
this.tracer.debug(
"%s: starfire: %d, wrath: %d",
event,
starfire,
wrath
);
this.ovale.needRefresh();
}
};
// State module
initializeState() {}
resetState() {
if (this.hasEclipseHandlers) {
const current = this.current;
const state = this.next;
state.starfire = current.starfire || 0;
state.starfireMax = current.starfireMax;
state.wrath = current.wrath || 0;
state.wrathMax = current.wrathMax;
}
}
cleanState() {}
applySpellAfterCast: SpellCastEventHandler = (
spellId: number,
targetGUID: string,
startCast: number,
endCast: number,
channel: boolean,
spellcast: SpellCast
) => {
if (!this.hasEclipseHandlers) return;
const state = this.next;
const prevStarfire = state.starfire;
const prevWrath = state.wrath;
let starfire = prevStarfire;
let wrath = prevWrath;
// Decrement the counters based on the casted spell.
if (spellId == celestialAlignmentId) {
// Celestial Alignment triggers both Eclipse states.
starfire = 0;
wrath = 0;
this.tracer.log(
"Spell ID '%d' Celestial Alignment resets counts to 0.",
spellId
);
// Celestial Alignment has a default base duration of 20 seconds.
const duration =
this.aura.getBaseDuration(
celestialAlignmentId,
undefined,
endCast
) || 20;
this.triggerEclipse(endCast, "lunar", duration);
this.triggerEclipse(endCast, "solar", duration);
} else if (spellId == incarnationId) {
// Incarnation triggers both Eclipse states.
starfire = 0;
wrath = 0;
this.tracer.log(
"Spell ID '%d' Incarnation: Chosen of Elune resets counts to 0.",
spellId
);
// Incarnation has a default base duration of 20 seconds.
const duration =
this.aura.getBaseDuration(incarnationId, undefined, endCast) ||
30;
this.triggerEclipse(endCast, "lunar", duration);
this.triggerEclipse(endCast, "solar", duration);
} else {
if (spellId == this.starfireId && prevStarfire > 0) {
starfire = prevStarfire - 1;
this.tracer.log(
"Spell ID '%d' Starfire decrements count to %d.",
spellId,
starfire
);
} else if (spellId == this.wrathId && prevWrath > 0) {
wrath = prevWrath - 1;
this.tracer.log(
"Spell ID '%d' Wrath decrements count to %d.",
spellId,
wrath
);
}
if (prevStarfire > 0 && starfire == 0) {
// Eclipse (Solar) has a default base duration of 15 seconds.
const duration =
this.aura.getBaseDuration(
eclipseSolarId,
undefined,
endCast
) || 15;
this.triggerEclipse(endCast, "solar", duration);
wrath = 0;
}
if (prevWrath > 0 && wrath == 0) {
// Eclipse (Lunar) has a default base duration of 15 seconds.
const duration =
this.aura.getBaseDuration(
eclipseLunarId,
undefined,
endCast
) || 15;
this.triggerEclipse(endCast, "lunar", duration);
starfire = 0;
}
}
// Update the counter state.
state.starfire = starfire;
state.wrath = wrath;
};
private triggerEclipse = (
atTime: number,
eclipseType: EclipseType,
duration: number
) => {
if (eclipseType == "lunar" || eclipseType == "solar") {
this.tracer.log("Triggering %s eclipse.", eclipseType);
const auraId =
(eclipseType == "lunar" && eclipseLunarId) || eclipseSolarId;
this.aura.addAuraToGUID(
this.ovale.playerGUID,
auraId,
this.ovale.playerGUID,
"HELPFUL",
undefined,
atTime,
atTime + duration,
atTime
);
}
};
private getEclipseAuras = (atTime: number): (Aura | undefined)[] => {
const lunar = this.aura.getAura(
"player",
eclipseLunarId,
atTime,
"HELPFUL"
);
const solar = this.aura.getAura(
"player",
eclipseSolarId,
atTime,
"HELPFUL"
);
return [lunar, solar];
};
/* this.getSpellCounts() has the same return values as API function
* GetSpellCount(): 0, 1, or 2 for the number of spells needed to
* enter the next eclipse.
*/
private getSpellCounts = (atTime: number): number[] => {
const state = this.next;
let starfire = state.starfire;
let wrath = state.wrath;
if (starfire == 0 && wrath == 0) {
const [lunar, solar] = this.getEclipseAuras(atTime);
const inLunar =
(lunar && this.aura.isActiveAura(lunar, atTime)) || false;
const inSolar =
(solar && this.aura.isActiveAura(solar, atTime)) || false;
if (!inLunar && !inSolar) {
const lunarEnding = (lunar && lunar.ending) || 0;
const solarEnding = (solar && solar.ending) || 0;
if (this.aura.isWithinAuraLag(lunarEnding, solarEnding)) {
// exit both eclipses
starfire = state.starfireMax;
wrath = state.wrathMax;
} else if (lunarEnding < solarEnding) {
// exit solar eclipse
wrath = state.wrathMax;
} else if (lunarEnding > solarEnding) {
// exit lunar eclipse
starfire = state.starfireMax;
}
}
}
this.tracer.log(
"Spell counts at time = %f: starfire = %d, wrath = %d",
atTime,
starfire,
wrath
);
return [starfire, wrath];
};
private getEclipse = (atTime: number): EclipseState => {
let eclipse: EclipseState = "any_next";
const [starfire, wrath] = this.getSpellCounts(atTime);
if (starfire > 0 && wrath > 0) {
eclipse = "any_next";
} else if (starfire > 0 && wrath == 0) {
eclipse = "solar_next";
} else if (starfire == 0 && wrath > 0) {
eclipse = "lunar_next";
} else {
// (starfire == 0 && wrath == 0)
const [lunar, solar] = this.getEclipseAuras(atTime);
const inLunar =
(lunar && this.aura.isActiveAura(lunar, atTime)) || false;
const inSolar =
(solar && this.aura.isActiveAura(solar, atTime)) || false;
if (inLunar && inSolar) {
eclipse = "in_both";
} else if (inLunar) {
eclipse = "in_lunar";
} else if (inSolar) {
eclipse = "in_solar";
}
}
return eclipse;
};
registerConditions(condition: OvaleConditionClass) {
condition.registerCondition(
"eclipseanynext",
false,
this.isNextEclipseAny
);
condition.registerCondition(
"eclipselunarin",
false,
this.enterEclipseLunarIn
);
condition.registerCondition(
"eclipselunarnext",
false,
this.isNextEclipseLunar
);
condition.registerCondition(
"eclipsesolarin",
false,
this.enterEclipseSolarIn
);
condition.registerCondition(
"eclipsesolarnext",
false,
this.isNextEclipseSolar
);
}
private isNextEclipseAny: ConditionFunction = (
positionalParameters,
namedParameters,
atTime
): ConditionResult => {
const eclipse = this.getEclipse(atTime);
const value = eclipse == "any_next";
return returnBoolean(value);
};
private isNextEclipseLunar: ConditionFunction = (
positionalParameters,
namedParameters,
atTime
): ConditionResult => {
const eclipse = this.getEclipse(atTime);
const value = eclipse == "lunar_next";
return returnBoolean(value);
};
private isNextEclipseSolar: ConditionFunction = (
positionalParameters,
namedParameters,
atTime
): ConditionResult => {
const eclipse = this.getEclipse(atTime);
const value = eclipse == "solar_next";
return returnBoolean(value);
};
/* this.enterEclipseLunarIn() returns the number of Wrath casts to
* enter lunar eclipse.
*/
private enterEclipseLunarIn: ConditionFunction = (
positionalParameters,
namedParameters,
atTime
): ConditionResult => {
const [, wrath] = this.getSpellCounts(atTime);
if (wrath > 0) {
return returnConstant(wrath);
}
return returnConstant(infinity);
};
/* this.enterEclipseSolarIn() returns the number of Starfire casts to
* enter solar eclipse.
*/
private enterEclipseSolarIn: ConditionFunction = (
positionalParameters,
namedParameters,
atTime
): ConditionResult => {
const [starfire] = this.getSpellCounts(atTime);
if (starfire > 0) {
return returnConstant(starfire);
}
return returnConstant(infinity);
};
} | the_stack |
import { ThemeCollection } from "./Design/ThemeCollection";
import { FilterStatic } from "./Filtering/FilterStatic";
import { FilterFormatter } from "./Filtering/Formatter/FilterFormatter";
import { ParsedCell } from "./Parsing/ParsedCell";
import { ParsedData } from "./Parsing/ParsedData";
import { Parser } from "./Parsing/Parser";
import { Locale } from "./System/Locale";
import { TablesorterConfiguration } from "./System/TablesorterConfiguration";
import { SortDefinition } from "./Sorting/SortDefinition";
import { TablesorterConfigurationStore } from "./System/TablesorterConfigurationStore";
import { RelativeSortDefinition } from "./Sorting/RelativeSortDefinition";
import { TriggerCallbackHandler } from "./System/TriggerCallbackHandler";
import { Widget } from "./Widgets/Widget";
import { StorageConfiguration } from "./Storage/StorageConfiguration";
import { MappedSettings } from "./System/MappedSettings";
import { TablesorterHeading } from "./System/TablesorterHeading";
import { HeaderResizeOptions } from "./System/HeaderResizeOptions";
import { ParsedOption } from "./Parsing/ParsedOption";
/**
* Represents the tablesorter.
*/
export interface Tablesorter<TElement = HTMLElement> {
/**
* The default settings.
*/
defaults: TablesorterConfiguration<TElement>;
/**
* The settings of the themes.
*/
themes: ThemeCollection;
/**
* The localized text for the tablesorter.
*/
language: Locale;
/**
* The custom instance-methods added to the tablesorter.
*/
instanceMethods: { [name: string]: () => any };
/**
* The parsers of the tablesorter.
*/
parsers: Array<Parser<TElement>>;
/**
* The widgets of the tablesorter.
*/
widgets: Array<Widget<TElement>>;
/**
* Provides methods for the `filter`-widget.
*/
filter: FilterStatic<TElement>;
/**
* Provides methods for creating filter-controls.
*/
filterFormatter: FilterFormatter;
/**
* Fetches all filters from the tablesorter.
*
* @param table
* The table to get the filters from.
*
* @return
* The filters applied to the `table`.
*/
getFilters(table: JQuery<TElement> | TElement, cached?: boolean): string[];
/**
* Sets the filter-text of the tablesorter.
*
* @param table
* The table to set the filter-text for.
*
* @param filter
* The filter-text to set.
*
* @param apply
* A value indicating whether to apply the filter after setting the filter-text.
*/
setFilters(table: JQuery<TElement> | TElement, filter: ReadonlyArray<string>, apply?: boolean): void;
/**
* Adds instance-methods to the tablesorter.
*
* @param methods
* The methods to add.
*/
addInstanceMethods(methods: { [name: string]: () => any }): void;
/**
* Adds a parser to the tablesorter.
*
* @param parser
* The parser to add.
*/
addParser(parser: Parser<TElement>): void;
/**
* Adds a widget to the tablesorter.
*
* @param widget
* The widget to add.
*/
addWidget(widget: Widget<TElement>): void;
/**
* Verifies whether the specified `table` has a widget with the specified `id`.
*
* @param table
* The table to check.
*
* @param id
* The id of the widget to verify.
*
* @return
* A value indicating whether a widget with the specified `id` is loaded for the specified `table`.
*/
hasWidget(table: JQuery<TElement> | TElement, id: string): boolean;
/**
* Gets a parser of the tablesorter.
*
* @param id
* The id of the parser to get.
*
* @return
* The parser with the specified `id`.
*/
getParserById(id: string): Parser<TElement>;
/**
* Gets a widget of the tablesorter.
*
* @param id
* The id of the widget to get.
*
* @return
* The widget with the specified `id`.
*/
getWidgetById(id: string): Widget<TElement>;
/**
* Pins an error-message to the table.
*
* @param table
* The table to pin the error-message to.
*
* @param request
* The request which caused an error.
*
* @param settings
* The ajax-settings of the `request`.
*
* @param message
* A message which describes the error.
*/
showError(table: JQuery<TElement> | TElement, request: string | JQuery.jqXHR, settings: JQueryAjaxSettings, message: string): void;
/**
* Verifies whether the specified `text` is a digit.
*
* @param text
* The text to check.
*
* @return
* A value indicating whether the specified `text` is a digit.
*/
isDigit(text: string): boolean;
/**
* Formats a text containing a number according to the correct format.
*
* @param text
* The text to format.
*
* @param table
* The table which is being processed.
*/
formatFloat(text: string, table: JQuery<TElement> | TElement): void;
/**
* Applies a sort to the table.
*
* @param config
* The configuration of the table-sorter.
*
* @param sort
* The sort to apply.
*
* @param callback
* A callback for post-processing the table.
*/
sortOn(config: TablesorterConfigurationStore<TElement>, sort: ReadonlyArray<(SortDefinition | RelativeSortDefinition)>, callback?: TriggerCallbackHandler<TElement>): void;
/**
* Resets the sorting.
*
* @param config
* The configuration of the table-sorter.
*
* @param callback
* A callback for post-processing the table.
*/
sortReset(config: TablesorterConfigurationStore<TElement>, callback?: TriggerCallbackHandler<TElement>): void;
/**
* Compares two strings and returns a value indicating whether one is less than, equal to or greater than the other.
*
* @param x
* The first string to compare.
*
* @param y
* The second string to compare.
*
* @param ascending
* A value indicating whether an ascending sort is being performed.
*
* @param index
* The index of the column which is being sorted.
*
* @param table
* The table which is being sorted.
*
* @return
* An integer that indicated the relative values of `x` and `y`:
* - If less than 0, `x` is less than `y`.
* - If `0`, `x` equals `y`.
* - If greater than 0, `x` is greater than `y`.
*/
sortNatural(x: string, y: string): number;
/**
* Compares two strings and returns a value indicating whether one is less than, equal to or greater than the other.
*
* @param x
* The first string to compare.
*
* @param y
* The second string to compare.
*
* @param ascending
* A value indicating whether an ascending sort is being performed.
*
* @param index
* The index of the column which is being sorted.
*
* @param table
* The table which is being sorted.
*
* @return
* An integer that indicated the relative values of `x` and `y`:
* - If less than 0, `x` is less than `y`.
* - If `0`, `x` equals `y`.
* - If greater than 0, `x` is greater than `y`.
*/
sortText(x: string, y: string): number;
/**
* Adds rows to the table.
*
* @param config
* The configuration of the table-sorter.
*
* @param rows
* The rows to add.
*
* @param resort
* Either a value indicating whether to resort the table or a new sort-definition to apply.
*
* @param callback
* A callback for post-processing the table.
*/
addRows(config: TablesorterConfigurationStore<TElement>, rows: JQuery | string, resort: boolean | ReadonlyArray<SortDefinition>, callback?: TriggerCallbackHandler<TElement>): void;
/**
* Clears all table-bodies inside the specified `table`.
*
* @param table
* The table which is being processed.
*/
clearTableBody(table: JQuery<TElement> | TElement): void;
/**
* Refreshes all currently loaded widgets.
*
* @param table
* The table which is being processed.
*
* @param initialize
* A value indicating whether the widgets should be initialized.
*
* @param callback
* A callback for post-processing the table.
*/
applyWidget(table: JQuery<TElement> | TElement, initialize?: boolean, callback?: TriggerCallbackHandler<TElement>): void;
/**
* Applies the widget to the specified `table`.
*
* @param table
* The table to apply the widget to.
*
* @param id
* The id of the widget to apply.
*/
applyWidgetId(table: JQuery<TElement> | TElement, id: string): void;
/**
* Removes widgets from the specified `table`.
*
* @param table
* The table to remove the widget from.
*
* @param id
* Either the id of the widget to remove or a value indicating whether to remove all widgets.
*
* @param refreshing
* A value indicating whether to keep the id of the widget in the `widgets`-option.
*/
removeWidget(table: JQuery<TElement> | TElement, id: string | ReadonlyArray<string> | boolean, refreshing?: boolean): void;
/**
* Refreshes the widgets.
*
* @param table
* The table which is being processed.
*
* @param removeAll
* A value indicating whether the widgets should be removed from the table.
*
* @param reapply
* A value indicating whether the widgets should be reapplied after removing them.
*/
refreshWidgets(table: JQuery<TElement> | TElement, removeAll?: boolean, reapply?: boolean): void;
/**
* Adds all cached table-rows back into the table.
*
* @param config
* The configuration of the table-sorter.
*/
appendCache(config: TablesorterConfigurationStore<TElement>): void;
/**
* Updates the data of the table-body.
*
* @param config
* The configuration of the table-sorter.
*
* @param callback
* A callback for post-processing the table.
*/
update(config: TablesorterConfigurationStore<TElement>, sorting?: boolean | ReadonlyArray<SortDefinition>, callback?: TriggerCallbackHandler<TElement>): void;
/**
* Updates the data of the table-body.
*
* @param config
* The configuration of the table-sorter.
*
* @param callback
* A callback for post-processing the table.
*/
updateRows(config: TablesorterConfigurationStore<TElement>, sorting?: boolean | ReadonlyArray<SortDefinition>, callback?: TriggerCallbackHandler<TElement>): void;
/**
* Updates the cache and optionally adds new `tbody`s.
*
* @param config
* The configuration of the table-sorter.
*
* @param callback
* A callback for post-processing the table.
*
* @param tbodies
* The `tbody`s to add.
*/
updateCache(config: TablesorterConfigurationStore<TElement>, callback?: TriggerCallbackHandler<TElement>, tbodies?: JQuery): void;
/**
* Updates the cell of the table.
*
* @param config
* The configuration of the table-sorter.
*
* @param cell
* The cell to update.
*
* @param sorting
* Either a new sorting to apply or a value indicating whether the current sorting should be re-applied.
*
* @param callback
* A callback for post-processing the table.
*/
updateCell(config: TablesorterConfigurationStore<TElement>, cell: JQuery, sorting?: boolean | ReadonlyArray<SortDefinition>, callback?: TriggerCallbackHandler<TElement>): void;
/**
* Updates the table-headers.
*
* @param config
* The configuration of the table-sorter.
*
* @param callback
* A callback for post-processing the table.
*/
updateHeaders(config: TablesorterConfigurationStore<TElement>, callback?: TriggerCallbackHandler<TElement>): void;
/**
* Updates the data of the whole table.
*
* @param config
* The configuration of the table-sorter.
*
* @param sorting
* Either a new sorting to apply or a value indicating whether the current sorting should be re-applied.
*
* @param callback
* A callback for post-processing the table.
*/
updateAll(config: TablesorterConfigurationStore<TElement>, sorting?: boolean | ReadonlyArray<SortDefinition>, callback?: TriggerCallbackHandler<TElement>): void;
/**
* Restores the headers of a table.
*
* @param table
* The table to process.
*/
restoreHeaders(table: JQuery<TElement> | TElement): void;
/**
* Re-calculates the `data-column`-attribute of the cells inside the rows.
*
* If a `config` is passed, the `data-column`-attributes will be removed for cells whose index matches its actual position.
*
* @param rows
* The rows to compute.
*
* @param config
* The tablesorter-configuration.
*/
computeColumnIndex(rows: JQuery, config?: TablesorterConfigurationStore<TElement>): void;
/**
* Adds a `colgroup`-element to the specified `table`.
*
* @param table
* The table to add the fixed columns to.
*/
fixColumnWidth(table: JQuery<TElement> | TElement): void;
/**
* Identifies the correct setting for a header.
*
* @param header
* The header-cell to get the data from.
*
* @param headerConfig
* The configuration of the header to get the data from.
*
* @param option
* The name of the option to get.
*
* @return
* The correct `option` for the specified `header`.
*/
getData<T extends keyof TablesorterHeading>(header: JQuery | HTMLElement, headerConfig: TablesorterHeading, option: T): TablesorterHeading[T];
/**
* Identifies the correct settings for the specified column `key` in the per-column settings `object`.
*
* @param table
* The table which is being processed.
*
* @param object
* The object which contains column-specific values.
*
* @param key
* The column-index or the class-name of the collumn to get the settings from.
*
* @return
* The settings inside the settings-`object` for the column with the specified `key`.
*/
getColumnData<T>(table: JQuery<TElement> | TElement, object: MappedSettings<T>, key: string | number): T;
/**
* Parses the text of a column.
*
* @param table
* The table which is being processed.
*
* @param column
* The index of the column to get the text from.
*
* @param callback
* A callback for processing the cell-text.
*
* @param rowFilter
* An object for filtering the rows to process.
*
* @return
* The parsed data of the column.
*/
getColumnText(
table: JQuery<TElement> | TElement,
column: number | "all",
callback?: (cell: ParsedCell) => void,
rowFilter?: JQuery.Selector | JQuery.TypeOrArray<Element> | JQuery | ((this: HTMLElement, index: number, element: HTMLElement) => boolean)): ParsedData;
/**
* Binds the header-events to the specified `elements`.
*
* @param table
* The table which is being processed.
*
* @param elements
* The jQuery-object containing the elements to bind the header-events to.
*/
bindEvents(table: JQuery<TElement> | TElement, elements: JQuery): void;
/**
* Adds an event-handler to the `resize`-event for the sticky headers.
*
* @param table
* The table to add the event to.
*
* @param disable
* A value indicating whether the event-handler should be disabled.
*
* @param options
* Options for the event-handler.
*/
addHeaderResizeEvent(table: JQuery<TElement> | TElement, disable: boolean, options?: HeaderResizeOptions): void;
/**
* Adds a processing-icon to headers.
*
* @param table
* The table to apply the processing-icons to.
*
* @param state
* A valud indicating whether the headers are processing.
*
* @param headers
* A jQuery-object containing the objects to apply the processing-icons to.
*/
isProcessing(table: JQuery<TElement> | TElement, state: boolean, headers?: JQuery): void;
/**
* Checks whether a `SortDefinition` for the specified `column` exists.
*
* @param column
* The column-index to check.
*
* @param array
* The sort-definitions to browse.
*
* @return
* A value indicating whether a `SortDefinition` for the specified `column` exists.
*/
isValueInArray(value: number, array: ReadonlyArray<[number, any]>): boolean;
/**
* Replaces all accent characters in the `text`.
*
* @param text
* The text to process.
*
* @return
* The processed text.
*/
replaceAccents(text: string): string;
/**
* Saves data to the storage.
*
* @param table
* The table to store data for.
*
* @param key
* The name of the option to save.
*
* @param value
* The value of the option to save.
*
* @param options
* The options for customizing the way to save the data to the storage.
*/
storage(table: JQuery<TElement> | TElement, key: string, value: any, options?: StorageConfiguration): void;
/**
* Saves data to the storage.
*
* @param table
* The table to store data for.
*
* @param key
* The name of the option to save.
*
* @param value
* The value of the option to save.
*
* @param options
* The options for customizing the way to save the data to the storage.
*/
storage(table: JQuery<TElement> | TElement, key: string, value?: null, options?: StorageConfiguration): any;
/**
* Removes the `tablesorter` from a table.
*
* @param table
* The table to destroy.
*
* @param removeClasses
* A value indicating whether the classes added by tablesorter should be removed.
*
* @param callback
* A callback for post-processing the table.
*/
destroy(table: JQuery<TElement> | TElement, removeClasses?: boolean, callback?: TriggerCallbackHandler<TElement>): void;
/**
* Provides the functionality to process the `tbody`.
*
* @param table
* The table the `tbody` belongs to.
*
* @param tbody
* The `tbody` to process.
*
* @param detach
* A value indicating whether the `tbody` should be detached.
*/
processTbody(table: JQuery<TElement> | TElement, tbody: JQuery, detach: true): JQuery;
processTbody(table: JQuery<TElement> | TElement, tbody: JQuery, detach?: false): void;
/**
* Resets the column-widths and optionally clears the locally stored column-widths.
*
* @param table
* The table to reset the resizable settings for.
*
* @param keepLocalSettings
* A value indicating whether local settings should not be cleared.
*/
resizableReset(table: JQuery<TElement> | TElement, keepLocalSettings?: boolean): void;
} | the_stack |
import React, { useCallback, useState } from "react";
import {
TableContainer,
Table,
TableHead,
TableRow,
TableCell,
TableBody,
IconButton,
TextField,
Switch
} from "@material-ui/core";
import { useTheme } from "@material-ui/core/styles";
import KeyboardArrowDownIcon from "@material-ui/icons/KeyboardArrowDown";
import KeyboardArrowUpIcon from "@material-ui/icons/KeyboardArrowUp";
import { makeStyles } from "@material-ui/core/styles";
import Tooltip from "@material-ui/core/Tooltip";
import Collapse from "@material-ui/core/Collapse";
import { Card } from "client/components/Card";
import { Typography } from "client/components/Typography";
import SkeletonBody from "./SkeletonBody";
import { CardContent, CardHeader } from "client/components/Card";
import { Button } from "client/components/Button";
import { Box } from "client/components/Box";
import useCortexConfig, {
useCortexConfigLoaded
} from "state/cortex-config/hooks/useCortexConfig";
import useTenantList from "state/tenant/hooks/useTenantList";
import {
CortexLimits,
CortexLimitsKeys,
CortexLimitsValues,
CortexLimitsSchemaDescription
} from "state/cortex-config/types";
import { HelpCircle, RotateCcw } from "react-feather";
import { ValidationError } from "yup";
import { useDispatch } from "state/provider";
import * as actions from "state/cortex-config/actions";
import ThousandNumberFormat from "client/components/Form/NumberFormatInput";
import { isEqual } from "lodash";
const entries = Object.entries as <T>(
o: T
) => [Extract<keyof T, string>, T[keyof T]][];
const useStyles = makeStyles(theme => ({
tenantHeaderRow: {
borderBottom: `1px solid ${theme.palette.divider}`
},
tenantRow: {
cursor: "pointer",
backgroundColor: theme.palette.action.hover
},
errorContainer: {
borderLeft: `4px solid ${theme.palette.error.main}`,
paddingLeft: theme.spacing(2)
},
borderBottom: {
borderBottom: `1px solid ${theme.palette.divider}`
}
}));
const CortexConfig = () => {
const allTenants = useTenantList();
const loaded = useCortexConfigLoaded();
const cortexConfig = useCortexConfig();
const dispatch = useDispatch();
// Filter out the system tenant. We can provide default overrides in cortex runtime config for this tenant.
const tenants = allTenants.filter(t => t.type !== "SYSTEM");
return (
<>
<Box pt={3} pb={4} display="flex" justifyContent="space-between">
<Typography variant="h5">Cortex Tenant Configuration</Typography>
<Button
variant="contained"
state="primary"
size="medium"
disabled={!cortexConfig.hasUnsavedChanges}
onClick={() => {
cortexConfig.runtimeConfig &&
dispatch(
actions.saveCortexRuntimeConfig(cortexConfig.runtimeConfig)
);
}}
>
{cortexConfig.hasUnsavedChanges ? "Apply Changes" : "No Changes"}
</Button>
</Box>
{cortexConfig.saveRuntimeConfigError && (
<ErrorPanel message={cortexConfig.saveRuntimeConfigError} />
)}
{cortexConfig.loadingError && (
<ErrorPanel message={cortexConfig.loadingError} />
)}
<Box pt={1}>
<TableContainer component={Card}>
<Table aria-label="tenants">
<TableHead></TableHead>
<TableBody>
{tenants.map(tenant => {
const baseLimits: CortexLimits =
cortexConfig.config?.limits || ({} as CortexLimits);
const overrides = cortexConfig.runtimeConfig?.overrides || {};
let limits: CortexLimits = {} as CortexLimits;
if (tenant.name in overrides) {
limits = overrides[tenant.name];
}
if (!loaded) {
return (
<SkeletonBody
key={tenant.name}
numberRows={3}
numberColumns={3}
/>
);
}
return (
<TenantConfigRowMemoized
key={tenant.name}
tenant={tenant.name}
limits={limits}
baseLimits={baseLimits}
/>
);
})}
</TableBody>
</Table>
</TableContainer>
</Box>
</>
);
};
type TenantConfigRowProps = {
tenant: string;
limits: CortexLimits;
baseLimits: CortexLimits;
};
const TenantConfigRow = (props: TenantConfigRowProps) => {
const { tenant, baseLimits, limits } = props;
const classes = useStyles();
const [open, setOpen] = React.useState(false);
return (
<React.Fragment key={tenant}>
<TableRow
hover={true}
className={classes.tenantRow}
onClick={() => setOpen(!open)}
>
<TableCell className={classes.borderBottom}>
<Button aria-label="expand limits" size="small">
{open ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
<Typography variant="h6">{tenant}</Typography>
</Button>
</TableCell>
<TableCell
component="th"
scope="row"
className={classes.borderBottom}
></TableCell>
</TableRow>
<TableRow>
<TableCell style={{ paddingBottom: 0, paddingTop: 0 }} colSpan={6}>
<Collapse in={open} timeout={100} unmountOnExit>
<Box>
<Table size="small" aria-label="config">
<TableHead></TableHead>
<TableBody>
{entries(CortexLimitsSchemaDescription).map(
([limitName, schema]) => {
const baseValue = baseLimits[limitName];
let value = baseValue;
if (limitName in limits) {
value = limits[limitName];
}
return (
<ConfigRow
key={limitName}
tenant={tenant}
limitName={limitName}
baseValue={baseValue}
value={value}
schema={schema}
/>
);
}
)}
</TableBody>
</Table>
</Box>
</Collapse>
</TableCell>
</TableRow>
</React.Fragment>
);
};
const TenantConfigRowMemoized = React.memo(TenantConfigRow, (prev, next) => {
return (
prev.tenant === next.tenant &&
isEqual(prev.baseLimits, next.baseLimits) &&
isEqual(prev.limits, next.limits)
);
});
type ConfigRowProps = {
tenant: string;
limitName: CortexLimitsKeys;
baseValue: string | boolean | number | undefined;
value: string | boolean | number | undefined;
schema: CortexLimitsValues;
};
const ConfigRow = ({
tenant,
limitName,
baseValue,
value,
schema
}: ConfigRowProps) => {
const [val, setVal] = useState(value);
const [error, setError] = useState<null | string>(null);
const dispatch = useDispatch();
const theme = useTheme();
const schemaType = schema.type;
// .meta Object unfortunately cannot be typed so we have to cast it here
const description =
(schema.describe().meta as { description: string }).description! || "-";
const hasOverride = val !== baseValue;
const onChange = useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
let val: string | boolean | number = event.target.value;
if (schema.type === "boolean") {
val = event.target.checked;
}
if (schema.type === "number") {
val = Number(event.target.value.replace(",", ""));
}
setVal(val);
// Run validation
(async () => {
try {
await schema.validate(val);
setError(null);
// If new value is same as the baseValue, delete the override, otherwise update the override
if (val === baseValue) {
dispatch(
actions.deleteCortexRuntimeConfig({
tenant,
configOption: limitName
})
);
} else {
dispatch(
actions.updateCortexRuntimeConfig({
tenant,
configOption: limitName,
value: val
})
);
}
} catch (err: any) {
setError((err as ValidationError).message);
}
})();
},
[schema, dispatch, tenant, limitName, baseValue]
);
return (
<TableRow key={limitName}>
<TableCell component="th" scope="row">
{limitName}{" "}
<Box component="span" marginLeft={2}>
<Tooltip
arrow
title={<Typography variant="caption">{description}</Typography>}
>
<HelpCircle
color={theme.palette.text.disabled}
width={17}
height={17}
/>
</Tooltip>
</Box>
</TableCell>
<TableCell>
{schemaType === "boolean" && (
<Switch
value={Boolean(val)}
checked={Boolean(val)}
onChange={onChange}
/>
)}
{schemaType === "string" && (
<TextField
value={val}
error={!!error}
helperText={error}
type={schemaType}
variant="standard"
onChange={onChange}
/>
)}
{schemaType === "number" && (
<TextField
value={String(val)}
error={!!error}
helperText={error}
variant="standard"
onChange={onChange}
InputProps={{
inputComponent: ThousandNumberFormat as any
}}
/>
)}
</TableCell>
<TableCell align="right">
<Box minWidth={20}>
<Box hidden={!hasOverride}>
<Tooltip
arrow
title={
<Typography variant="caption">{`Reset to default (${baseValue})`}</Typography>
}
>
<IconButton
aria-label="reset limit"
size="small"
onClick={() => {
setVal(baseValue);
dispatch(
actions.deleteCortexRuntimeConfig({
tenant,
configOption: limitName
})
);
}}
>
<RotateCcw width={15} height={15} />
</IconButton>
</Tooltip>
</Box>
</Box>
</TableCell>
</TableRow>
);
};
const ErrorPanel = ({ message }: { message: string }) => {
const classes = useStyles();
return (
<Box className={classes.errorContainer}>
<CardHeader titleTypographyProps={{ variant: "h6" }} title="Error" />
<CardContent>
{message.split("\n").map(message => (
<div key={message}>
{message}
<br />
</div>
))}
</CardContent>
</Box>
);
};
export default CortexConfig; | the_stack |
eslint-disable @typescript-eslint/no-explicit-any
*/
import _, {
isEqual,
forEach,
keyBy,
zip,
unzip,
sum,
isString,
toString,
Dictionary,
padStart,
} from 'lodash'
import pangu from 'pangu'
import path from 'path'
import { readJsonSync } from 'fs-extra'
import url from 'url'
import { Modifiers } from 'popper.js'
/**
* Sums up each position for each position for a 2-dimension array (matrix)
* @param arr 2-d array of numbers
* @returns array of sums
*/
export function arraySum(arr: number[][]): number[] {
return unzip(arr).map(sum)
}
/**
* Mutiply an array at each element
* @param arr 1-d array of numbers
* @param n factor
*/
export function arrayMultiply(arr: number[], n: number): number[] {
return arr.map((i) => i * n)
}
/**
* Adds an array
* @param arr 1-d array of numbers
* @param n number or 1-d array of same size
*/
export function arrayAdd(arr: number[], n: number | number[]): number[] {
if (Array.isArray(n)) {
return zip(arr, n).map(([a, b]) => a! + b!) // eslint-disable-line @typescript-eslint/no-non-null-assertion
} else {
return arr.map((i) => i + n)
}
}
/**
* Substracts an array
* @param arr 1-d array of numbers
* @param n number or 1-d array of same size
*/
export function arraySubstract(arr: number[], n: number): number[]
export function arraySubstract(arr: number[], n: number[]): number[]
export function arraySubstract(arr: number[], n: number | number[]): number[] {
if (Array.isArray(n)) {
return zip(arr, n).map(([a, b]) => a! - b!) // eslint-disable-line @typescript-eslint/no-non-null-assertion
} else {
return arr.map((i) => i - n)
}
}
/**
* Checks a value is between the bounds
* @param n value to check
* @param min lower bound (<=)
* @param max upper bound (<=)
*/
export function between(n: number, min: number, max: number): boolean {
return n >= min && n <= max
}
/**
* a non-ambiguous method to build array, should supersed `buildArray`
* @param idx
* @param values
* @returns
*/
export const constructArray = <T = any>(idx: number[], values: T[]) => {
const ret: T[] = []
idx.forEach((index, i) => {
index = Math.floor(index)
if (isNaN(index) || index < 0) {
return
}
ret[index] = values[i]
})
return ret
}
/**
* @deprecated use constructArray instead
*/
export function buildArray<T = any>(idx: number, value: T): T[]
/**
* Builds an array with the given position and value info
* @param pairs array of [position, value]
* @deprecated use constructArray instead
*/
export function buildArray<T = any>(pairs: [number, T][]): T[]
/**
* @deprecated use constructArray instead
*/
export function buildArray<T = any>(
pairsOrIdx: number | [number, T][],
_value?: T,
): (T | undefined)[] {
let pairs: [number, T][]
if (Array.isArray(pairsOrIdx)) {
pairs = pairsOrIdx
} else {
console.warn(
'buildArray(idx, value) is pending deprecation, please use buildArray([idx, value]) instead',
)
pairs = [[pairsOrIdx, _value!]]
}
const ret: T[] = []
pairs.forEach(([index, value]) => {
index = Math.floor(index)
if (isNaN(index) || index < 0) {
return
}
ret[index] = value
})
return ret
}
/**
* Turns an array into object with given key
* @param array array to build
* @param key value to be key
*/
export function indexify<T = any>(array: any[], key = 'api_id'): Dictionary<T> {
return keyBy(array, key)
}
/**
* returns a new copy for an object or array
* @param obj the source
* @param to another instance to compare
*/
export function copyIfSame<T = any>(obj: T, to: any): T {
// assert(typeof obj === 'object')
if (obj === to) {
return Array.isArray(obj) ? (obj.slice() as unknown as T) : { ...obj }
}
return obj
}
/**
* Mutates the state by remving properties that no longer exist in body, only keys are compared
* @param state the state object
* @param body the incoming new state
*/
export function pickExisting<T extends object>(state: T, body: object): T {
const stateBackup = state
forEach(state, (_, k) => {
if (!(k in body)) {
state = copyIfSame(state, stateBackup)
delete state[k as keyof T]
}
})
return state
}
/**
* Sets a value for a given path with pure operations, for Redux pattern compliance
* Similar to lodash.set, but if the value needs updating, each object along
* its path will be shallow-copied instead of modified in-place
* @param obj object to modify
* @param path data path
* @param val the value to update
*/
export function reduxSet<T = any>(obj: T, path: (string | number)[], val: any): T {
const [prop, ...restPath] = path
if (typeof prop === 'undefined') {
if (!isEqual(obj, val)) {
return val
} else {
return obj
}
}
let before
if (prop in obj) {
before = obj[prop as keyof T]
} else {
before = {}
}
const after = reduxSet(before, restPath, val)
if (after !== before) {
let result
if (Array.isArray(obj)) {
result = obj.slice()
result[prop as number] = after
} else {
result = {
...obj,
[prop]: after,
}
}
return result as T
}
return obj
}
/**
* Updates a state like Object.assign(prevState, newState) until `depth` level, but keeps
* as many parts from previous State as possible. Neither state is modified in-place.
* By default `depth` == 1, and every property of the returned value will be the the same
* previous (in terms of ===) if not mentioned in newState or `isEqual` to the corresponding,
* or o/w the newProperty as a whole. Therefore,
* - If you only provide one leaf of a property, its other siblings will be deleted.
* - If a property is updated, all its children will be new ones, even if they are equal (in terms of isEqual).
* @param prevState previous state
* @param newState the expected state to trigger the modification
* @param depth
* @returns updated result mixed of previous and new state
*/
export function compareUpdate<T = any>(prevState: T, newState: T, depth = 1): T {
if (typeof prevState !== typeof newState) {
return newState
}
if (prevState === newState) {
return prevState
}
if (depth == 0 || typeof depth !== 'number' || typeof prevState !== 'object') {
return isEqual(prevState, newState) ? prevState : newState
}
const prevStateBackup = prevState
// Update existing properties
const nextDepth = depth - 1
forEach(newState as unknown as object, (v, k) => {
const newV = compareUpdate(prevState[k as keyof T], v, nextDepth)
// ATTENTION: Any null properties are ignored
if (newV != null && prevState[k as keyof T] !== newV) {
prevState = copyIfSame(prevState, prevStateBackup)
if (newV != null) {
prevState[k as keyof T] = newV
}
}
})
return prevState
}
/**
* Pads a number by 0 at start
* @param n the number to pad
*/
function pad(n: number): string {
return padStart(n.toString(), 2, '0')
}
/**
* Renders sconds in HH:mm:ss format
* @param seconds time
*/
export function resolveTime(seconds: number): string {
seconds = Math.floor(seconds)
if (seconds >= 0) {
const s = seconds % 60
const m = Math.trunc(seconds / 60) % 60
const h = Math.trunc(seconds / 3600)
return `${pad(h)}:${pad(m)}:${pad(s)}`
} else {
return ''
}
}
/**
* Renders milliseconds in HH:mm:ss format
* @param milliseconds time
*/
export function timeToString(milliseconds: number): string {
const date = new Date(milliseconds)
return date.toTimeString().slice(0, 8) // HH:mm:ss
}
/**
* Reduces an array to fit the length of another array
* @param state original array
* @param comparator the array as reference
*/
export function trimArray<T extends any[]>(state: T, comparator: any[]): T {
if (Array.isArray(state) && Array.isArray(comparator) && comparator.length < state.length)
return state.slice(0, comparator.length) as T
return state
}
/**
* Generates a valid file url for browser file links
* @param str file path
*/
export const fileUrl = (str = ''): string => {
let pathName = path.resolve(str).replace(/\\/g, '/')
if (pathName[0] !== '/') {
pathName = '/' + pathName
}
return url.format({
protocol: 'file',
slashes: true,
pathname: pathName,
})
}
/**
* Escapes the a url with encodeURI
* @param str the url
*/
export const normalizeURL = (str = ''): string => {
const path = str.split('.htm')
path[0] = path[0].replace('#', '%23').replace('?', '%3F')
return path.join('.htm')
}
/**
* Checks if dir is a subdirectory of parent, if parent and dir are the same, also returns true
* @param parent
* @param dir
*/
export const isSubdirectory = (parent: string, dir: string): boolean => {
const relative = path.relative(parent, dir)
return !relative || (!relative.startsWith('..') && !path.isAbsolute(relative))
}
/**
* Executes a function until dom ready
* @param func
*/
export const executeUntilReady = (func: () => any): void => {
if (document.readyState === 'complete') {
func()
} else {
document.addEventListener('DOMContentLoaded', func)
}
}
/**
* Turns a value to string if it is not
* @param str the value
*/
const ensureString = (str: any): string => (isString(str) ? str : toString(str))
/**
* Removes default ns and key separators in a translation key for i18next
* @param str translation key
*/
export const escapeI18nKey = (str: any): string =>
ensureString(str).replace(/\.\W/g, '').replace(/\.$/, '').replace(/:\s/g, '').replace(/:$/g, '')
/**
* Loads the i18n resources
* @param filePath i18n json file path
*/
export const readI18nResources = (filePath: string): object => {
try {
let data = readJsonSync(filePath)
data = _(data)
.entries()
.map(([key, v]) => [escapeI18nKey(key), v])
.fromPairs()
.value()
return data
} catch (e) {
return {}
}
}
/**
* Loads an external script by adding <script> tag
* @param path script path
* @param document document object
*/
export const loadScript = (path: string, document = window.document): void => {
const script = document.createElement('script')
script.setAttribute('src', path)
document.head.appendChild(script)
}
/**
* Default blueprint popover(Popper.js) modifiers used in poi
*/
export const POPOVER_MODIFIERS: Modifiers = {
computeStyle: { gpuAcceleration: false }, // prevent using translat3d since it could make text blurry with zooming
preventOverflow: {
boundariesElement: 'window', // enable display tooltip within small containers
},
}
export const cjkSpacing = (str: string) => (isString(str) ? pangu.spacing(str) : toString(str)) | the_stack |
const MyEdgeStyle = function (Mx: any) {
const {
mxConstants,
mxEdgeStyle,
mxPoint,
mxUtils,
mxStyleRegistry,
mxRectangle
} = Mx;
function outputEdgeInfo (state: any, source: any, target: any, points: any, result: any) {
console.log('state:', state);
console.log('source:', source);
console.log('target:', target);
console.log('points:', points);
console.log('result:', result);
};
return {
/**
* Function: OrthConnector
*
* Implements a local orthogonal router between the given
* cells.
*
* Parameters:
*
* state - <mxCellState> that represents the edge to be updated.
* source - <mxCellState> that represents the source terminal.
* target - <mxCellState> that represents the target terminal.
* points - List of relative control points.
* result - Array of <mxPoints> that represent the actual points of the
* edge.
*
*/
OrthConnector: function (state: any, source: any, target: any, points: any, result: any) {
var graph = state.view.graph;
var sourceEdge =
source == null ? false : graph.getModel().isEdge(source.cell);
var targetEdge =
target == null ? false : graph.getModel().isEdge(target.cell);
var pts = state.absolutePoints;
var p0 = pts[0];
var pe = pts[pts.length - 1];
var sourceX = source != null ? source.x : p0.x;
var sourceY = source != null ? source.y : p0.y;
var sourceWidth = source != null ? source.width : 0;
var sourceHeight = source != null ? source.height : 0;
var targetX = target != null ? target.x : pe.x;
var targetY = target != null ? target.y : pe.y;
var targetWidth = target != null ? target.width : 0;
var targetHeight = target != null ? target.height : 0;
var scaledSourceBuffer =
state.view.scale *
mxEdgeStyle.getJettySize(state, source, target, points, true);
var scaledTargetBuffer =
state.view.scale *
mxEdgeStyle.getJettySize(state, source, target, points, false);
// Workaround for loop routing within buffer zone
if (source != null && target == source) {
scaledTargetBuffer = Math.max(
scaledSourceBuffer,
scaledTargetBuffer
);
scaledSourceBuffer = scaledTargetBuffer;
}
var totalBuffer = scaledTargetBuffer + scaledSourceBuffer;
var tooShort = false;
// Checks minimum distance for fixed points and falls back to segment connector
if (p0 != null && pe != null) {
var dx = pe.x - p0.x;
var dy = pe.y - p0.y;
tooShort = dx * dx + dy * dy < totalBuffer * totalBuffer;
}
if (
tooShort ||
(mxEdgeStyle.orthPointsFallback &&
(points != null && points.length > 0)) ||
sourceEdge ||
targetEdge
) {
mxEdgeStyle.SegmentConnector(state, source, target, points, result);
return;
}
// Determine the side(s) of the source and target vertices
// that the edge may connect to
// portConstraint [source, target]
var portConstraint: any = [
mxConstants.DIRECTION_MASK_ALL,
mxConstants.DIRECTION_MASK_ALL
];
var rotation = 0;
if (source != null) {
portConstraint[0] = mxUtils.getPortConstraints(
source,
state,
true,
mxConstants.DIRECTION_MASK_ALL
);
rotation = mxUtils.getValue(
source.style,
mxConstants.STYLE_ROTATION,
0
);
if (rotation != 0) {
var newRect = mxUtils.getBoundingBox(
new mxRectangle(
sourceX,
sourceY,
sourceWidth,
sourceHeight
),
rotation
);
sourceX = newRect.x;
sourceY = newRect.y;
sourceWidth = newRect.width;
sourceHeight = newRect.height;
}
}
if (target != null) {
portConstraint[1] = mxUtils.getPortConstraints(
target,
state,
false,
mxConstants.DIRECTION_MASK_ALL
);
rotation = mxUtils.getValue(
target.style,
mxConstants.STYLE_ROTATION,
0
);
if (rotation != 0) {
var newRect = mxUtils.getBoundingBox(
new mxRectangle(
targetX,
targetY,
targetWidth,
targetHeight
),
rotation
);
targetX = newRect.x;
targetY = newRect.y;
targetWidth = newRect.width;
targetHeight = newRect.height;
}
}
// Avoids floating point number errors
sourceX = Math.round(sourceX * 10) / 10;
sourceY = Math.round(sourceY * 10) / 10;
sourceWidth = Math.round(sourceWidth * 10) / 10;
sourceHeight = Math.round(sourceHeight * 10) / 10;
targetX = Math.round(targetX * 10) / 10;
targetY = Math.round(targetY * 10) / 10;
targetWidth = Math.round(targetWidth * 10) / 10;
targetHeight = Math.round(targetHeight * 10) / 10;
var dir: any = [0, 0];
// Work out which faces of the vertices present against each other
// in a way that would allow a 3-segment connection if port constraints
// permitted.
// geo -> [source, target] [x, y, width, height]
var geo: any = [
[sourceX, sourceY, sourceWidth, sourceHeight],
[targetX, targetY, targetWidth, targetHeight]
];
var buffer: any = [scaledSourceBuffer, scaledTargetBuffer];
for (var i = 0; i < 2; i++) {
mxEdgeStyle.limits[i][1] = geo[i][0] - buffer[i];
mxEdgeStyle.limits[i][2] = geo[i][1] - buffer[i];
mxEdgeStyle.limits[i][4] = geo[i][0] + geo[i][2] + buffer[i];
mxEdgeStyle.limits[i][8] = geo[i][1] + geo[i][3] + buffer[i];
}
// Work out which quad the target is in
var sourceCenX = geo[0][0] + geo[0][2] / 2.0;
var sourceCenY = geo[0][1] + geo[0][3] / 2.0;
var targetCenX = geo[1][0] + geo[1][2] / 2.0;
var targetCenY = geo[1][1] + geo[1][3] / 2.0;
var dx = sourceCenX - targetCenX;
var dy = sourceCenY - targetCenY;
var quad = 0;
if (dx < 0) {
if (dy < 0) {
quad = 2;
} else {
quad = 1;
}
} else {
if (dy <= 0) {
quad = 3;
// Special case on x = 0 and negative y
if (dx == 0) {
quad = 2;
}
}
}
// Check for connection constraints
var currentTerm = null;
if (source != null) {
currentTerm = p0;
}
var constraint: any = [[0.5, 0.5], [0.5, 0.5]];
for (var i = 0; i < 2; i++) {
if (currentTerm != null) {
constraint[i][0] = (currentTerm.x - geo[i][0]) / geo[i][2];
if (Math.abs(currentTerm.x - geo[i][0]) <= 1) {
dir[i] = mxConstants.DIRECTION_MASK_WEST;
} else if (
Math.abs(currentTerm.x - geo[i][0] - geo[i][2]) <= 1
) {
dir[i] = mxConstants.DIRECTION_MASK_EAST;
}
constraint[i][1] = (currentTerm.y - geo[i][1]) / geo[i][3];
if (Math.abs(currentTerm.y - geo[i][1]) <= 1) {
dir[i] = mxConstants.DIRECTION_MASK_NORTH;
} else if (
Math.abs(currentTerm.y - geo[i][1] - geo[i][3]) <= 1
) {
dir[i] = mxConstants.DIRECTION_MASK_SOUTH;
}
}
currentTerm = null;
if (target != null) {
currentTerm = pe;
}
}
var sourceTopDist = geo[0][1] - (geo[1][1] + geo[1][3]);
var sourceLeftDist = geo[0][0] - (geo[1][0] + geo[1][2]);
var sourceBottomDist = geo[1][1] - (geo[0][1] + geo[0][3]);
var sourceRightDist = geo[1][0] - (geo[0][0] + geo[0][2]);
mxEdgeStyle.vertexSeperations[1] = Math.max(
sourceLeftDist - totalBuffer,
0
);
mxEdgeStyle.vertexSeperations[2] = Math.max(
sourceTopDist - totalBuffer,
0
);
mxEdgeStyle.vertexSeperations[4] = Math.max(
sourceBottomDist - totalBuffer,
0
);
mxEdgeStyle.vertexSeperations[3] = Math.max(
sourceRightDist - totalBuffer,
0
);
// ==============================================================
// Start of source and target direction determination
// Work through the preferred orientations by relative positioning
// of the vertices and list them in preferred and available order
var dirPref: any = [];
var horPref: any = [];
var vertPref: any = [];
horPref[0] =
sourceLeftDist >= sourceRightDist
? mxConstants.DIRECTION_MASK_WEST
: mxConstants.DIRECTION_MASK_EAST;
vertPref[0] =
sourceTopDist >= sourceBottomDist
? mxConstants.DIRECTION_MASK_NORTH
: mxConstants.DIRECTION_MASK_SOUTH;
horPref[1] = mxUtils.reversePortConstraints(horPref[0]);
vertPref[1] = mxUtils.reversePortConstraints(vertPref[0]);
var preferredHorizDist =
sourceLeftDist >= sourceRightDist
? sourceLeftDist
: sourceRightDist;
var preferredVertDist =
sourceTopDist >= sourceBottomDist
? sourceTopDist
: sourceBottomDist;
var prefOrdering: any = [[0, 0], [0, 0]];
var preferredOrderSet = false;
// If the preferred port isn't available, switch it
for (var i = 0; i < 2; i++) {
if (dir[i] != 0x0) {
continue;
}
if ((horPref[i] & portConstraint[i]) == 0) {
horPref[i] = mxUtils.reversePortConstraints(horPref[i]);
}
if ((vertPref[i] & portConstraint[i]) == 0) {
vertPref[i] = mxUtils.reversePortConstraints(vertPref[i]);
}
prefOrdering[i][0] = vertPref[i];
prefOrdering[i][1] = horPref[i];
}
if (preferredVertDist > 0 && preferredHorizDist > 0) {
// Possibility of two segment edge connection
if (
(horPref[0] & portConstraint[0]) > 0 &&
(vertPref[1] & portConstraint[1]) > 0
) {
prefOrdering[0][0] = horPref[0];
prefOrdering[0][1] = vertPref[0];
prefOrdering[1][0] = vertPref[1];
prefOrdering[1][1] = horPref[1];
preferredOrderSet = true;
} else if (
(vertPref[0] & portConstraint[0]) > 0 &&
(horPref[1] & portConstraint[1]) > 0
) {
prefOrdering[0][0] = vertPref[0];
prefOrdering[0][1] = horPref[0];
prefOrdering[1][0] = horPref[1];
prefOrdering[1][1] = vertPref[1];
preferredOrderSet = true;
}
}
if (preferredVertDist > 0 && !preferredOrderSet) {
prefOrdering[0][0] = vertPref[0];
prefOrdering[0][1] = horPref[0];
prefOrdering[1][0] = vertPref[1];
prefOrdering[1][1] = horPref[1];
preferredOrderSet = true;
}
if (preferredHorizDist > 0 && !preferredOrderSet) {
prefOrdering[0][0] = horPref[0];
prefOrdering[0][1] = vertPref[0];
prefOrdering[1][0] = horPref[1];
prefOrdering[1][1] = vertPref[1];
preferredOrderSet = true;
}
// The source and target prefs are now an ordered list of
// the preferred port selections
// It the list can contain gaps, compact it
for (var i = 0; i < 2; i++) {
if (dir[i] != 0x0) {
continue;
}
if ((prefOrdering[i][0] & portConstraint[i]) == 0) {
prefOrdering[i][0] = prefOrdering[i][1];
}
dirPref[i] = prefOrdering[i][0] & portConstraint[i];
dirPref[i] |= (prefOrdering[i][1] & portConstraint[i]) << 8;
dirPref[i] |= (prefOrdering[1 - i][i] & portConstraint[i]) << 16;
dirPref[i] |=
(prefOrdering[1 - i][1 - i] & portConstraint[i]) << 24;
if ((dirPref[i] & 0xf) == 0) {
dirPref[i] = dirPref[i] << 8;
}
if ((dirPref[i] & 0xf00) == 0) {
dirPref[i] = (dirPref[i] & 0xf) | (dirPref[i] >> 8);
}
if ((dirPref[i] & 0xf0000) == 0) {
dirPref[i] =
(dirPref[i] & 0xffff) | ((dirPref[i] & 0xf000000) >> 8);
}
dir[i] = dirPref[i] & 0xf;
if (
portConstraint[i] == mxConstants.DIRECTION_MASK_WEST ||
portConstraint[i] == mxConstants.DIRECTION_MASK_NORTH ||
portConstraint[i] == mxConstants.DIRECTION_MASK_EAST ||
portConstraint[i] == mxConstants.DIRECTION_MASK_SOUTH
) {
dir[i] = portConstraint[i];
}
}
// ==============================================================
// End of source and target direction determination
var sourceIndex =
dir[0] == mxConstants.DIRECTION_MASK_EAST ? 3 : dir[0];
var targetIndex =
dir[1] == mxConstants.DIRECTION_MASK_EAST ? 3 : dir[1];
sourceIndex -= quad;
targetIndex -= quad;
if (sourceIndex < 1) {
sourceIndex += 4;
}
if (targetIndex < 1) {
targetIndex += 4;
}
var routePattern =
mxEdgeStyle.routePatterns[sourceIndex - 1][targetIndex - 1];
mxEdgeStyle.wayPoints1[0][0] = geo[0][0];
mxEdgeStyle.wayPoints1[0][1] = geo[0][1];
switch (dir[0]) {
case mxConstants.DIRECTION_MASK_WEST:
mxEdgeStyle.wayPoints1[0][0] -= scaledSourceBuffer;
mxEdgeStyle.wayPoints1[0][1] += constraint[0][1] * geo[0][3];
break;
case mxConstants.DIRECTION_MASK_SOUTH:
mxEdgeStyle.wayPoints1[0][0] += constraint[0][0] * geo[0][2];
mxEdgeStyle.wayPoints1[0][1] += geo[0][3] + scaledSourceBuffer;
break;
case mxConstants.DIRECTION_MASK_EAST:
mxEdgeStyle.wayPoints1[0][0] += geo[0][2] + scaledSourceBuffer;
mxEdgeStyle.wayPoints1[0][1] += constraint[0][1] * geo[0][3];
break;
case mxConstants.DIRECTION_MASK_NORTH:
mxEdgeStyle.wayPoints1[0][0] += constraint[0][0] * geo[0][2];
mxEdgeStyle.wayPoints1[0][1] -= scaledSourceBuffer;
break;
}
var currentIndex = 0;
// Orientation, 0 horizontal, 1 vertical
var lastOrientation =
(dir[0] &
(mxConstants.DIRECTION_MASK_EAST |
mxConstants.DIRECTION_MASK_WEST)) >
0
? 0
: 1;
var initialOrientation = lastOrientation;
var currentOrientation = 0;
for (var i = 0; i < routePattern.length; i++) {
var nextDirection = routePattern[i] & 0xf;
// Rotate the index of this direction by the quad
// to get the real direction
var directionIndex =
nextDirection == mxConstants.DIRECTION_MASK_EAST
? 3
: nextDirection;
directionIndex += quad;
if (directionIndex > 4) {
directionIndex -= 4;
}
var direction = mxEdgeStyle.dirVectors[directionIndex - 1];
currentOrientation = directionIndex % 2 > 0 ? 0 : 1;
// Only update the current index if the point moved
// in the direction of the current segment move,
// otherwise the same point is moved until there is
// a segment direction change
if (currentOrientation != lastOrientation) {
currentIndex++;
// Copy the previous way point into the new one
// We can't base the new position on index - 1
// because sometime elbows turn out not to exist,
// then we'd have to rewind.
mxEdgeStyle.wayPoints1[currentIndex][0] =
mxEdgeStyle.wayPoints1[currentIndex - 1][0];
mxEdgeStyle.wayPoints1[currentIndex][1] =
mxEdgeStyle.wayPoints1[currentIndex - 1][1];
}
var tar = (routePattern[i] & mxEdgeStyle.TARGET_MASK) > 0;
var sou = (routePattern[i] & mxEdgeStyle.SOURCE_MASK) > 0;
var side = (routePattern[i] & mxEdgeStyle.SIDE_MASK) >> 5;
side = side << quad;
if (side > 0xf) {
side = side >> 4;
}
var center = (routePattern[i] & mxEdgeStyle.CENTER_MASK) > 0;
if ((sou || tar) && side < 9) {
var limit = 0;
var souTar = sou ? 0 : 1;
if (center && currentOrientation == 0) {
limit =
geo[souTar][0] + constraint[souTar][0] * geo[souTar][2];
} else if (center) {
limit =
geo[souTar][1] + constraint[souTar][1] * geo[souTar][3];
} else {
limit = mxEdgeStyle.limits[souTar][side];
}
if (currentOrientation == 0) {
var lastX = mxEdgeStyle.wayPoints1[currentIndex][0];
var deltaX = (limit - lastX) * direction[0];
if (deltaX > 0) {
mxEdgeStyle.wayPoints1[currentIndex][0] +=
direction[0] * deltaX;
}
} else {
var lastY = mxEdgeStyle.wayPoints1[currentIndex][1];
var deltaY = (limit - lastY) * direction[1];
if (deltaY > 0) {
mxEdgeStyle.wayPoints1[currentIndex][1] +=
direction[1] * deltaY;
}
}
} else if (center) {
// Which center we're travelling to depend on the current direction
mxEdgeStyle.wayPoints1[currentIndex][0] +=
direction[0] *
Math.abs(mxEdgeStyle.vertexSeperations[directionIndex] / 2);
mxEdgeStyle.wayPoints1[currentIndex][1] +=
direction[1] *
Math.abs(mxEdgeStyle.vertexSeperations[directionIndex] / 2);
}
if (
currentIndex > 0 &&
mxEdgeStyle.wayPoints1[currentIndex][currentOrientation] ==
mxEdgeStyle.wayPoints1[currentIndex - 1][currentOrientation]
) {
currentIndex--;
} else {
lastOrientation = currentOrientation;
}
}
for (var i = 0; i <= currentIndex; i++) {
if (i == currentIndex) {
// Last point can cause last segment to be in
// same direction as jetty/approach. If so,
// check the number of points is consistent
// with the relative orientation of source and target
// jx. Same orientation requires an even
// number of turns (points), different requires
// odd.
var targetOrientation =
(dir[1] &
(mxConstants.DIRECTION_MASK_EAST |
mxConstants.DIRECTION_MASK_WEST)) >
0
? 0
: 1;
var sameOrient =
targetOrientation == initialOrientation ? 0 : 1;
// (currentIndex + 1) % 2 is 0 for even number of points,
// 1 for odd
if (sameOrient != (currentIndex + 1) % 2) {
// The last point isn't required
break;
}
}
result.push(
new mxPoint(
Math.round(mxEdgeStyle.wayPoints1[i][0]),
Math.round(mxEdgeStyle.wayPoints1[i][1])
)
);
}
// Removes duplicates
var index = 1;
while (index < result.length) {
if (
result[index - 1] == null ||
result[index] == null ||
result[index - 1].x != result[index].x ||
result[index - 1].y != result[index].y
) {
index++;
} else {
result.splice(index, 1);
}
}
// Special hand first and last pointX;
// 源代码的算法还没有完全搞清楚,这里只是细微的调整了一下坐标值
const resultLen = result.length;
if (resultLen > 2) {
let firstPoint = result[1].y;
let lastSecondPointY = result[resultLen - 2].y;
const differenceValue = (target ? target.y : NaN) - source.y;
// console.log('differenceValue:', target.y, source.y, differenceValue)
if (differenceValue < 60) {
result[1].y = firstPoint + 20;
result[resultLen - 1].y = lastSecondPointY - 20;
}
}
// outputEdgeInfo(state, source, target, points, result);
},
myStyle: function (state: any, source: any, target: any, points: any, result: any) {
if (source != null && target != null) {
var pt = new mxPoint(target.getCenterX(), source.getCenterY());
if (mxUtils.contains(source, pt.x, pt.y)) {
pt.y = source.y + source.height;
}
result.push(pt);
}
outputEdgeInfo(state, source, target, points, result);
mxStyleRegistry.putValue('myEdgeStyle', mxEdgeStyle.MyStyle);
}
};
}
export default MyEdgeStyle; | the_stack |
import {Container, inject, transient, singleton, Lazy, All, Optional, Parent} from 'aurelia-dependency-injection';
import {decorators} from 'aurelia-metadata';
export var run = () => {
describe('container', () => {
describe('injection', () => {
it('01: instantiates class without injected services', function () {
var container = new Container();
var app = container.get(App_01);
expect(app).toEqual(jasmine.any(App_01));
});
it('02: uses static inject method (ES6)', function () {
var container = new Container();
var app = container.get(App_02);
expect(app.logger).toEqual(jasmine.any(Logger_02));
});
it('03: uses static inject property (TypeScript,CoffeeScript,ES5)', function () {
App_03.inject = [Logger_03];
var container = new Container();
var app = container.get(App_03);
expect(app.logger).toEqual(jasmine.any(Logger_03));
});
});
describe('registration', () => {
it('04: asserts keys are defined', () => {
var container = new Container();
expect(() => container.get(null)).toThrow();
expect(() => container.get(undefined)).toThrow();
expect(() => container.get(null)).toThrow();
expect(() => container.get(undefined)).toThrow();
expect(() => container.registerInstance(null, {})).toThrow();
expect(() => container.registerInstance(undefined, {})).toThrow();
expect(() => container.registerSingleton(null)).toThrow();
expect(() => container.registerSingleton(undefined)).toThrow();
expect(() => container.registerTransient(null)).toThrow();
expect(() => container.registerTransient(undefined)).toThrow();
expect(() => container.autoRegister(null)).toThrow();
expect(() => container.autoRegister(undefined)).toThrow();
expect(() => container.autoRegisterAll([null])).toThrow();
expect(() => container.autoRegisterAll([undefined])).toThrow();
expect(() => container.registerHandler(null, null)).toThrow();
expect(() => container.registerHandler(undefined, null)).toThrow();
expect(() => (<any>container).hasHandler(null)).toThrow();
expect(() => (<any>container).hasHandler(undefined)).toThrow();
});
it('05: automatically configures as singleton', () => {
inject(Logger_05)(App1_05);
inject(Logger_05)(App2_05);
var container = new Container();
var app1 = container.get(App1_05);
var app2 = container.get(App2_05);
expect(app1.logger).toBe(app2.logger);
});
it('06: configures singleton via api', () => {
inject(Logger_06)(App1_06);
inject(Logger_06)(App2_06);
var container = new Container();
container.registerSingleton(Logger_06, Logger_06);
var app1 = container.get(App1_06);
var app2 = container.get(App2_06);
expect(app1.logger).toBe(app2.logger);
});
it('08: configures singleton via metadata property (ES5, AtScript, TypeScript, CoffeeScript)', () => {
var container = new Container();
var app1 = container.get(App1_08);
var app2 = container.get(App2_08);
expect(app1.logger).toBe(app2.logger);
});
it('09: configures transient (non singleton) via api', () => {
var container = new Container();
container.registerTransient(Logger_09, Logger_09);
var app1 = container.get(App1_09);
var app2 = container.get(App2_09);
expect(app1.logger).not.toBe(app2.logger);
});
it('10: configures transient (non singleton) via metadata method (ES6)', () => {
var container = new Container();
var app1 = container.get(App1_10);
var app2 = container.get(App2_10);
expect(app1.logger).not.toBe(app2.logger);
});
it('12: configures instance via api', () => {
var container = new Container();
var instance = new Logger_12();
container.registerInstance(Logger_12, instance);
var app1 = container.get(App1_12);
var app2 = container.get(App2_12);
expect(app1.logger).toBe(instance);
expect(app2.logger).toBe(instance);
});
it('13: configures custom via api', () => {
var container = new Container();
container.registerHandler(Logger_13, c => "something strange");
var app1 = container.get(App1_13);
var app2 = container.get(App2_13);
expect(app1.logger).toEqual("something strange");
expect(app2.logger).toEqual("something strange");
});
// typescript wont let a class extend a property
//it('14: uses base metadata method (ES6) when derived does not specify', () => {
// var container = new Container();
// var app1 = container.get(App1_14);
// var app2 = container.get(App2_14);
// expect(app1.logger).not.toBe(app2.logger);
//});
it('16: overrides base metadata method (ES6) with derived configuration', () => {
var container = new Container();
var app1 = container.get(App1_16);
var app2 = container.get(App2_16);
expect(app1.logger).not.toBe(app2.logger);
});
it('18: configures key as service when transient api only provided with key', () => {
var container = new Container();
container.registerTransient(Logger_18);
var logger1 = container.get(Logger_18),
logger2 = container.get(Logger_18);
expect(logger1).toEqual(jasmine.any(Logger_18));
expect(logger2).toEqual(jasmine.any(Logger_18));
expect(logger2).not.toBe(logger1);
});
it('19: configures key as service when singleton api only provided with key', () => {
var container = new Container();
container.registerSingleton(Logger_19);
var logger1 = container.get(Logger_19),
logger2 = container.get(Logger_19);
expect(logger1).toEqual(jasmine.any(Logger_19));
expect(logger2).toEqual(jasmine.any(Logger_19));
expect(logger2).toBe(logger1);
});
it('20: configures concrete singelton via api for abstract dependency', () => {
var container = new Container();
container.registerSingleton(LoggerBase_20, Logger_20);
var app = container.get(App_20);
expect(app.logger).toEqual(jasmine.any(Logger_20));
});
it('21: configures concrete transient via api for abstract dependency', () => {
var container = new Container();
container.registerTransient(LoggerBase_21, Logger_21);
var app = container.get(App_21);
expect(app.logger).toEqual(jasmine.any(Logger_21));
});
// typescript wont let a class extend a property
//it('22: doesn\'t get hidden when a super class adds metadata which doesn\'t include the base registration type', () => {
// Reflect.defineMetadata('something', 'test', Logger_22);
// var container = new Container();
// var app1 = container.get(App1_22);
// var app2 = container.get(App2_22);
// expect(app1.logger).not.toBe(app2.logger);
//});
describe('Custom resolvers', () => {
describe('Lazy', () => {
it('23: provides a function which, when called, will return the instance', () => {
var container = new Container();
var app1 = container.get(App1_23);
var logger = app1.getLogger;
expect(logger()).toEqual(jasmine.any(Logger_23));
});
});
describe('All', () => {
it('24: resolves all matching dependencies as an array of instances', () => {
var container = new Container();
container.registerSingleton(LoggerBase_24, VerboseLogger_24);
container.registerTransient(LoggerBase_24, Logger_24);
var app = container.get(App_24);
expect(app.loggers).toEqual(jasmine.any(Array));
expect(app.loggers.length).toBe(2);
expect(app.loggers[0]).toEqual(jasmine.any(VerboseLogger_24));
expect(app.loggers[1]).toEqual(jasmine.any(Logger_24));
});
});
describe('Optional', () => {
it('25: injects the instance if its registered in the container', () => {
var container = new Container();
container.registerSingleton(Logger_25, Logger_25);
var app = container.get(App_25);
expect(app.logger).toEqual(jasmine.any(Logger_25));
});
it('26: injects null if key is not registered in the container', () => {
var container = new Container();
container.registerSingleton(VerboseLogger_26, Logger_26);
var app = container.get(App_26);
expect(app.logger).toBe(null);
});
it('27: injects null if key nor function is registered in the container', () => {
var container = new Container();
var app = container.get(App_27);
expect(app.logger).toBe(null);
});
it('28: doesn\'t check the parent container hierarchy when checkParent is false or default', () => {
var parentContainer = new Container();
parentContainer.registerSingleton(Logger_28, Logger_28);
var childContainer = parentContainer.createChild();
childContainer.registerSingleton(App_28, App_28);
var app = childContainer.get(App_28);
expect(app.logger).toBe(null);
});
it('29: checks the parent container hierarchy when checkParent is true', () => {
var parentContainer = new Container();
parentContainer.registerSingleton(Logger_29, Logger_29);
var childContainer = parentContainer.createChild();
childContainer.registerSingleton(App_29, App_29);
var app = childContainer.get(App_29);
expect(app.logger).toEqual(jasmine.any(Logger_29));
});
});
describe('Parent', () => {
it('30: bypasses the current container and injects instance from parent container', () => {
var parentContainer = new Container();
var parentInstance = new Logger_30();
parentContainer.registerInstance(Logger_30, parentInstance);
var childContainer = parentContainer.createChild();
var childInstance = new Logger_30();
childContainer.registerInstance(Logger_30, childInstance);
childContainer.registerSingleton(App_30, App_30);
var app = childContainer.get(App_30);
expect(app.logger).toBe(parentInstance);
});
it('31: returns null when no parent container exists', () => {
var container = new Container();
var instance = new Logger_31();
container.registerInstance(Logger_31, instance);
var app = container.get(App_31);
expect(app.logger).toBe(null);
});
});
});
});
});
}
// 01 ------------------------------------------------------------------
class App_01 { }
// 02 ------------------------------------------------------------------
class Logger_02 { }
class App_02 {
static inject() { return [Logger_02]; };
logger;
constructor(logger) {
this.logger = logger;
}
}
// 03 ------------------------------------------------------------------
class Logger_03 { }
class App_03 {
static inject;
logger;
constructor(logger) {
this.logger = logger;
}
}
// 04 ------------------------------------------------------------------
// 05 ------------------------------------------------------------------
class Logger_05 { }
class App1_05 {
logger;
constructor(logger) {
this.logger = logger;
}
}
class App2_05 {
logger;
constructor(logger) {
this.logger = logger;
}
}
// 06 ------------------------------------------------------------------
class Logger_06 { }
class App1_06 {
logger;
constructor(logger) {
this.logger = logger;
}
}
class App2_06 {
logger;
constructor(logger) {
this.logger = logger;
}
}
// 07 ------------------------------------------------------------------
// (removed)
// 08 ------------------------------------------------------------------
class Logger_08_Class { };
let Logger_08 = decorators(singleton()).on(Logger_08_Class);
class App1_08 {
static inject() { return [Logger_08]; };
logger;
constructor(logger) {
this.logger = logger;
}
}
class App2_08 {
static inject() { return [Logger_08]; };
logger;
constructor(logger) {
this.logger = logger;
}
}
// 09 ------------------------------------------------------------------
class Logger_09 { }
class App1_09 {
static inject() { return [Logger_09]; };
logger;
constructor(logger) {
this.logger = logger;
}
}
class App2_09 {
static inject() { return [Logger_09]; };
logger;
constructor(logger) {
this.logger = logger;
}
}
// 10 ------------------------------------------------------------------
class Logger_10_Class { }
let Logger_10 = decorators(transient()).on(Logger_10_Class);
class App1_10 {
static inject() { return [Logger_10]; };
logger;
constructor(logger) {
this.logger = logger;
}
}
class App2_10 {
static inject() { return [Logger_10]; };
logger;
constructor(logger) {
this.logger = logger;
}
}
// 11 ------------------------------------------------------------------
// (removed)
// 12 ------------------------------------------------------------------
class Logger_12 { }
class App1_12 {
static inject() { return [Logger_12]; };
logger;
constructor(logger) {
this.logger = logger;
}
}
class App2_12 {
static inject() { return [Logger_12]; };
logger;
constructor(logger) {
this.logger = logger;
}
}
// 13 ------------------------------------------------------------------
class Logger_13 { }
class App1_13 {
static inject() { return [Logger_13]; };
logger;
constructor(logger) {
this.logger = logger;
}
}
class App2_13 {
static inject() { return [Logger_13]; };
logger;
constructor(logger) {
this.logger = logger;
}
}
// 14 ------------------------------------------------------------------
//class LoggerBase_14_Class { }
//let LoggerBase_14 = decorators(transient()).on(LoggerBase_14_Class);
//class Logger_14 extends LoggerBase_14;
//class Logger_14 extends LoggerBase_14 { }
//class App1_14 {
// static inject() { return [Logger_14]; };
// logger;
// constructor(logger) {
// this.logger = logger;
// }
//}
//class App2_14 {
// static inject() { return [Logger_14]; };
// logger;
// constructor(logger) {
// this.logger = logger;
// }
//}
// 15 ------------------------------------------------------------------
// (removed)
// 16 ------------------------------------------------------------------
class LoggerBase_16_Class { };
class Logger_16_Class extends LoggerBase_16_Class { };
let LoggerBase_16 = decorators(singleton()).on(LoggerBase_16_Class);
let Logger_16 = decorators(transient()).on(Logger_16_Class);
class App1_16 {
static inject() { return [Logger_16]; };
logger;
constructor(logger) {
this.logger = logger;
}
}
class App2_16 {
static inject() { return [Logger_16]; };
logger;
constructor(logger) {
this.logger = logger;
}
}
// 17 ------------------------------------------------------------------
// (removed)
// 18 ------------------------------------------------------------------
class Logger_18 { }
// 19 ------------------------------------------------------------------
class Logger_19 { }
// 20 ------------------------------------------------------------------
class LoggerBase_20 { }
class Logger_20 extends LoggerBase_20 { }
class App_20 {
static inject() { return [LoggerBase_20]; };
logger;
constructor(logger) {
this.logger = logger;
}
}
// 21 ------------------------------------------------------------------
class LoggerBase_21 { }
class Logger_21 extends LoggerBase_21 { }
class App_21 {
static inject() { return [LoggerBase_21]; };
logger;
constructor(logger) {
this.logger = logger;
}
}
// 22 ------------------------------------------------------------------
//class LoggerBase_22_Class { }
//let LoggerBase_22 = decorators(transient()).on(LoggerBase_22_Class);
//class Logger_22 extends LoggerBase_22 { }
//class App1_22 {
// static inject() { return [Logger_22]; };
// logger;
// constructor(logger) {
// this.logger = logger;
// }
//}
//class App2_22 {
// static inject() { return [Logger_22]; };
// logger;
// constructor(logger) {
// this.logger = logger;
// }
//}
// 23 ------------------------------------------------------------------
class Logger_23 { }
class App1_23 {
static inject() { return [Lazy.of(Logger_23)]; };
getLogger;
constructor(getLogger) {
this.getLogger = getLogger;
}
}
// 24 ------------------------------------------------------------------
class LoggerBase_24 { }
class VerboseLogger_24 extends LoggerBase_24 { }
class Logger_24 extends LoggerBase_24 { }
class App_24 {
static inject() { return [All.of(LoggerBase_24)]; };
loggers;
constructor(loggers) {
this.loggers = loggers;
}
}
// 25 ------------------------------------------------------------------
class Logger_25 { }
class App_25 {
static inject() { return [Optional.of(Logger_25)]; };
logger;
constructor(logger) {
this.logger = logger;
}
}
// 26 ------------------------------------------------------------------
class VerboseLogger_26 { }
class Logger_26 { }
class App_26 {
static inject() { return [Optional.of(Logger_26)]; };
logger;
constructor(logger) {
this.logger = logger;
}
}
// 27 ------------------------------------------------------------------
class VerboseLogger_27 { }
class Logger_27 { }
class App_27 {
static inject() { return [Optional.of(Logger_27)]; };
logger;
constructor(logger) {
this.logger = logger;
}
}
// 28 ------------------------------------------------------------------
class Logger_28 { }
class App_28 {
static inject() { return [Optional.of(Logger_28)]; };
logger;
constructor(logger) {
this.logger = logger;
}
}
// 29 ------------------------------------------------------------------
class Logger_29 { }
class App_29 {
static inject() { return [Optional.of(Logger_29, true)]; };
logger;
constructor(logger) {
this.logger = logger;
}
}
// 30 ------------------------------------------------------------------
class Logger_30 { }
class App_30 {
static inject() { return [Parent.of(Logger_30)]; };
logger;
constructor(logger) {
this.logger = logger;
}
}
// 31 ------------------------------------------------------------------
class Logger_31 { }
class App_31 {
static inject() { return [Parent.of(Logger_31)]; };
logger;
constructor(logger) {
this.logger = logger;
}
} | the_stack |
import { newURL, getHashedPath, equal } from "./url";
import { newState, newCoords } from "./history";
import { Service } from "./service";
import { ignoreURLs } from "./page";
import { toAttr } from "./config";
import type { TypeTrigger, IHistoryItem, IHistoryManager } from "./history";
import type { IPage, IPageManager } from "./page";
import type { ITransitionManager } from "./transition";
export type TypeLinkEvent = MouseEvent | TouchEvent;
export type TypeStateEvent = TypeLinkEvent | PopStateEvent;
export type TypeIgnoreURLsList = Array<RegExp | string>;
/**
* Creates a barbajs based PJAX Service, for the native framework
* Based on barbajs and StartingBlocks
*/
export class PJAX extends Service {
/** URLs to disable PJAX for */
public preventURLs: boolean | TypeIgnoreURLsList;
/** URLs to ignore when prefetching / Whether or not to disable prefetching */
public prefetchIgnore: boolean | TypeIgnoreURLsList;
/** Current state of transitions */
public isTransitioning: boolean;
/** Ignore extra clicks of an anchor element if a transition has already started */
public onTransitionPreventClick: boolean;
/** On page change (excluding popstate events) keep current scroll position */
public stickyScroll: boolean;
/** Force load a page if an error occurs */
public forceOnError: boolean;
/** Ignore hash action if set to true */
public ignoreHashAction: boolean;
public install() {
super.install();
this.preventURLs = this.config.preventURLs;
this.prefetchIgnore = this.config.prefetchIgnore;
this.onTransitionPreventClick = this.config.onTransitionPreventClick;
this.stickyScroll = this.config.stickyScroll;
this.forceOnError = this.config.forceOnError;
this.ignoreHashAction = this.config.ignoreHashAction;
}
/** Sets the transition state to either true or false */
public transitionStart() {
this.isTransitioning = true;
}
public transitionStop() {
this.isTransitioning = false;
}
public init() {
/**
* Bind the event listeners to the PJAX class
*
* @memberof PJAX
*/
this.onHover = this.onHover.bind(this);
this.onClick = this.onClick.bind(this);
this.onStateChange = this.onStateChange.bind(this);
}
/** Starts the PJAX Service */
public boot() {
super.boot();
}
/** Gets the transition to use for a certain anchor */
public getTransitionName(el: HTMLAnchorElement): string | null {
if (!el || !el.getAttribute) return null;
let transitionAttr = el.getAttribute(
toAttr(this.config, "transitionAttr", false)
);
if (typeof transitionAttr === "string") return transitionAttr;
return null;
}
/** Checks to see if the anchor is valid */
public validLink(
el: HTMLAnchorElement,
event: TypeLinkEvent | KeyboardEvent,
href: string
): boolean {
let pushStateSupport = !window.history.pushState;
let exists = !el || !href;
let eventMutate =
(event as KeyboardEvent).metaKey ||
(event as KeyboardEvent).ctrlKey ||
(event as KeyboardEvent).shiftKey ||
(event as KeyboardEvent).altKey;
let newTab =
el.hasAttribute("target") &&
(el as HTMLAnchorElement).target === "_blank";
let crossOrigin =
(el as HTMLAnchorElement).protocol !== location.protocol ||
(el as HTMLAnchorElement).hostname !== location.hostname;
let download = typeof el.getAttribute("download") === "string";
let preventSelf = el.matches(toAttr(this.config, "preventSelfAttr"));
let preventAll = Boolean(
el.closest(toAttr(this.config, "preventAllAttr"))
);
let preventURL = ignoreURLs(newURL(href).pathname, this.preventURLs);
let sameURL = getHashedPath(newURL()) === getHashedPath(newURL(href));
return !(
exists ||
pushStateSupport ||
eventMutate ||
newTab ||
crossOrigin ||
download ||
preventSelf ||
preventAll ||
preventURL ||
sameURL
);
}
/** Returns the href of an Anchor element */
public getHref(el: HTMLAnchorElement): string | null {
if (
el &&
el.tagName &&
el.tagName.toLowerCase() === "a" &&
typeof el.href === "string"
)
return el.href;
return null;
}
/** Check if event target is a valid anchor with an href, if so, return the anchor */
public getLink(event: TypeLinkEvent): HTMLAnchorElement {
let el = event.target as HTMLAnchorElement;
let href: string = this.getHref(el);
while (el && !href) {
el = (el as HTMLElement).parentNode as HTMLAnchorElement;
href = this.getHref(el);
}
// Check for a valid link
if (!el || !this.validLink(el, event, href)) return;
return el;
}
/** When an element is clicked, get valid anchor element, go for a transition */
public onClick(event: TypeLinkEvent) {
let el = this.getLink(event);
if (!el) return;
if (this.isTransitioning && this.onTransitionPreventClick) {
event.preventDefault();
event.stopPropagation();
return;
}
let href = this.getHref(el);
this.emitter.emit("ANCHOR_CLICK CLICK", event);
this.go({ href, trigger: el, event });
}
/** Returns the direction of the State change as a String, either the Back button or the Forward button */
public getDirection(value: number): TypeTrigger {
if (Math.abs(value) > 1) {
// Ex 6-0 > 0 -> forward, 0-6 < 0 -> back
return value > 0 ? "forward" : "back";
} else {
if (value === 0) return "popstate";
else {
// Ex 6-5 > 0 -> back, 5-6 < 0 -> forward
return value > 0 ? "back" : "forward";
}
}
}
/** Force a page to go to a certain URL */
public force(href: string): void {
window.location.assign(href);
}
/**
* If transition is running force load page.
* Stop if currentURL is the same as new url.
* On state change, change the current state history, to reflect the direction of said state change
* Load page and page transition.
*/
public go({ href, trigger = "HistoryManager", event }: {
href: string;
trigger?: TypeTrigger;
event?: TypeStateEvent;
}): Promise<void> {
// If transition is already running and the go method is called again, force load page
if (this.isTransitioning && !this.onTransitionPreventClick || !(
this.manager.has("TransitionManager") &&
this.manager.has("HistoryManager") &&
this.manager.has("PageManager")
)) {
this.force(href);
return;
}
const history = this.manager.get("HistoryManager") as IHistoryManager;
let scroll = newCoords(0, 0);
let currentState = history.current;
let currentURL = currentState.url;
if (equal(currentURL, href)) return;
let transitionName: string;
if (event && (event as PopStateEvent).state) {
this.emitter.emit("POPSTATE", event);
// If popstate, get back/forward direction.
let { state }: { state: IHistoryItem } = event as PopStateEvent;
let { index } = state;
let currentIndex = currentState.index;
let difference = currentIndex - index;
history.replace(state.states);
history.pointer = index;
let _state = history.get(index);
transitionName = _state.transition;
scroll = _state.data.scroll;
trigger = this.getDirection(difference);
// Based on the direction of the state change either remove or add a state
this.emitter.emit(trigger === "back" ? `POPSTATE_BACK` : `POPSTATE_FORWARD`, event);
} else {
// Add new state
transitionName = this.getTransitionName(trigger as HTMLAnchorElement);
scroll = newCoords();
let state = newState({
url: href,
transition: transitionName,
data: { scroll },
});
!this.stickyScroll && (scroll = newCoords(0, 0));
history.add(state);
this.emitter.emit("HISTORY_NEW_ITEM", event);
}
if (event) {
event.stopPropagation();
event.preventDefault();
}
this.emitter.emit("GO", event);
return this.load({ oldHref: currentURL, href, trigger, transitionName, scroll });
}
/** Load the new Page as well as a Transition; starts the Transition */
public async load({
oldHref, href, trigger,
transitionName = "default",
scroll = { x: 0, y: 0 },
}: {
oldHref: string;
href: string;
trigger?: TypeTrigger;
transitionName?: string;
scroll?: { x: number; y: number };
}): Promise<any> {
try {
const transitions = this.manager.get("TransitionManager") as ITransitionManager;
const pages = this.manager.get("PageManager") as IPageManager;
let ignoreHashAction = this.ignoreHashAction;
let newPage: IPage, oldPage: IPage;
this.emitter.emit("NAVIGATION_START", { oldHref, href, trigger, transitionName, scroll });
if (!transitions.has(transitionName)) {
console.log(`[PJAX] transition name "${transitionName}" doesn't exist, switching to the "default" transition`);
transitionName = "default";
}
// Load & Build both the old and new pages
try {
this.transitionStart();
this.emitter.emit("PAGE_LOADING", { href, oldHref, trigger, scroll });
oldPage = await pages.load(oldHref);
newPage = await pages.load(href);
this.emitter.emit("PAGE_LOAD_COMPLETE", { newPage, oldPage, trigger, scroll });
// If you reload the page, the previous page may not have been built
// this is to ensure no errors occur
if (!(oldPage.dom instanceof Element)) oldPage.build();
newPage.build();
} catch (err) {
console.warn(`[PJAX] Page load error`, err);
}
// Transition Between Pages
try {
let data = await transitions.start(transitionName, { oldPage, newPage, trigger, scroll, ignoreHashAction });
scroll = data.scroll;
} catch (err) {
console.warn(`[PJAX] Transition error`, err);
}
// Navigation is over
this.emitter.emit("NAVIGATION_END", { oldPage, newPage, trigger, transitionName, scroll });
} catch (err) {
if (this.forceOnError) this.force(href);
else console.warn(err);
} finally {
this.transitionStop(); // Sets isTransitioning to false
}
}
/** When you hover over an anchor, prefetch the event target's href */
public onHover(event: TypeLinkEvent): Promise<void> {
let el = this.getLink(event);
if (!el || !this.manager.has("PageManager")) return;
const pages = this.manager.get("PageManager") as IPageManager;
let url = newURL(this.getHref(el));
let urlString: string = url.pathname;
this.emitter.emit("ANCHOR_HOVER HOVER", event);
// If Url is ignored or already in cache, don't prefetch
if (ignoreURLs(url.pathname, this.prefetchIgnore)) return;
if (pages.has(urlString) && !ignoreURLs(urlString, pages.cacheIgnore)) return;
try {
pages.load(url);
this.emitter.emit("PREFETCH", event);
} catch (err) {
console.warn("[PJAX] Prefetch error", err);
}
}
/** When History state changes, get url from State, go for a Transition. */
public onStateChange(event: PopStateEvent): void {
this.go({ href: window.location.href, trigger: "popstate", event });
}
/** Initialize DOM Events */
public initEvents() {
if (this.prefetchIgnore !== true) {
document.addEventListener("mouseover", this.onHover);
document.addEventListener("touchstart", this.onHover);
}
document.addEventListener("click", this.onClick);
window.addEventListener("popstate", this.onStateChange);
}
/** Stop DOM Events */
public stopEvents() {
if (this.prefetchIgnore !== true) {
document.removeEventListener("mouseover", this.onHover);
document.removeEventListener("touchstart", this.onHover);
}
document.removeEventListener("click", this.onClick);
window.removeEventListener("popstate", this.onStateChange);
}
} | the_stack |
namespace Bootstrap
{
export class Helper
{
/**
* Finds tags decorated with data-bsu attributes and uses those to flesh out
* the HTML that Bootstrap needs for different elements.
*/
static decorateBootstrapElements()
{
Helper.decorateValidationElements();
Helper.decorateCollapsiblePanels();
Helper.decorateModals();
}
/**
* Finds tags decorated with various validation tags and fleshes out the
* Bootstrap and knockout tags required.
*/
static decorateValidationElements()
{
Helper.decorateValidationFieldValidate();
Helper.decorateValidationIcons();
}
/**
* Adds validation displays to input elements. Apply the tag in a parent of the input,
* set data-bsu-field to the full path to the ValidationFieldModel element.
*/
static decorateValidationFieldValidate()
{
var fieldValidates = $('[data-bsu="field-validate"]');
$.each(fieldValidates, function() {
var fieldValidate = $(this);
var fieldName = Helper.getFieldName(fieldValidate);
var fieldValidateBinding = VRS.stringUtility.format(
"css: {{ 'has-feedback': !{0}.IsValid(), 'has-warning': {0}.IsWarning, 'has-error': {0}.IsError }}",
fieldName
);
var visibleIfInvalidBinding = VRS.stringUtility.format(
'visible: !{0}.IsValid()',
fieldName
);
var visibleIfErrorBinding = VRS.stringUtility.format(
'visible: {0}.IsError',
fieldName
);
var visibleIfWarningBinding = VRS.stringUtility.format(
'visible: {0}.IsWarning',
fieldName
);
var messageBinding = VRS.stringUtility.format(
'text: {0}.Message',
fieldName
);
fieldValidate.attr('data-bind', fieldValidateBinding);
var helpBlockControl = $('input,textarea,select,:checkbox,table', fieldValidate).first();
var parentInputGroup = helpBlockControl.parent('.input-group');
if(parentInputGroup.length > 0) {
helpBlockControl = parentInputGroup;
}
var isListControl = helpBlockControl.is('table');
var helpBlock = $('<span />')
.addClass('help-block')
.attr('data-bind', visibleIfInvalidBinding);
if(isListControl) {
helpBlock.insertBefore(helpBlockControl);
} else {
helpBlock.insertAfter(helpBlockControl);
}
$('<span />')
.attr('data-bind', messageBinding)
.appendTo(helpBlock);
$('<span />')
.attr('data-bind', visibleIfErrorBinding)
.addClass('help-block-icon error glyphicon glyphicon-minus-sign')
.attr('aria-hidden', 'true')
.attr('title', VRS.Server.$$.Error)
.prependTo(helpBlock);
$('<span />')
.attr('data-bind', visibleIfWarningBinding)
.addClass('help-block-icon warning glyphicon glyphicon-exclamation-sign')
.attr('aria-hidden', 'true')
.attr('title', VRS.Server.$$.Warning)
.prependTo(helpBlock);
});
}
/**
* Adds span elements to show the warning and error states. Usually associated with wrap-up validation elements.
*/
static decorateValidationIcons()
{
var validateIcons = $('[data-bsu="validate-icons"]');
$.each(validateIcons, function() {
var validateIcon = $(this);
var fieldName = Helper.getFieldName(validateIcon);
var visibleIfErrorBinding = VRS.stringUtility.format(
'visible: {0}.IsError',
fieldName
);
var visibleIfWarningBinding = VRS.stringUtility.format(
'visible: {0}.IsWarning',
fieldName
);
$('<span />')
.attr('data-bind', visibleIfErrorBinding)
.addClass('glyphicon glyphicon-minus-sign')
.appendTo(validateIcon);
$('<span />')
.attr('data-bind', visibleIfWarningBinding)
.addClass('glyphicon glyphicon-exclamation-sign')
.appendTo(validateIcon);
});
}
/**
* Finds tags decorated with collapsible-panel data-bsu attributes and fleshes
* out the HTML required for a collapsible panel.
*/
static decorateCollapsiblePanels()
{
var collapsiblePanels = $('[data-bsu="collapsible-panel"]');
$.each(collapsiblePanels, function() {
var panel = $(this);
var panelId = Helper.applyUniqueId(panel);
var children = panel.children();
if(children.length !== 2) throw 'The panel should have exactly two children';
var options = Helper.getOptions(panel);
var startCollapsed = VRS.arrayHelper.indexOf(options, 'expanded') === -1;
var usePanelTitle = VRS.arrayHelper.indexOf(options, 'use-title') !== -1;
var context = 'default';
if(VRS.arrayHelper.indexOf(options, 'danger') !== -1) context = 'danger';
if(VRS.arrayHelper.indexOf(options, 'default') !== -1) context = 'default';
if(VRS.arrayHelper.indexOf(options, 'info') !== -1) context = 'info';
if(VRS.arrayHelper.indexOf(options, 'primary') !== -1) context = 'primary';
if(VRS.arrayHelper.indexOf(options, 'success') !== -1) context = 'success';
if(VRS.arrayHelper.indexOf(options, 'warning') !== -1) context = 'warning';
var isInAccordion = panel.parent().hasClass('panel-group') || VRS.arrayHelper.indexOf(options, 'accordion') !== -1;
var accordion = !isInAccordion ? null : panel.closest('.panel-group');
if(!accordion) {
isInAccordion = false;
}
var accordionId = isInAccordion ? Helper.applyUniqueId(accordion) : null;
var heading = $(children[0]);
var headingId = Helper.applyUniqueId(heading);
var body = $(children[1]);
var bodyId = Helper.applyUniqueId(body);
panel.addClass('panel panel-' + context);
var headerLink = $('<div />')
.attr('class', startCollapsed ? 'collapsed' : '')
.attr('data-toggle', 'collapse')
.attr('role', 'button')
.attr('href', '#' + bodyId)
.attr('aria-expanded', startCollapsed ? 'false' : 'true')
.attr('aria-controls', '#' + bodyId);
if(!isInAccordion) {
headerLink.attr('data-target', '#' + bodyId);
} else {
headerLink.attr('data-parent', '#' + accordionId);
}
heading.wrapInner(
$('<h4 />').addClass(usePanelTitle ? 'panel-title' : '').append(headerLink)
)
.addClass('panel-heading')
.attr('role', 'tab');
body.wrapInner($('<div />').addClass('panel-body'))
.addClass('panel-collapse collapse' + (startCollapsed ? '' : ' in'))
.attr('role', 'tabpanel')
.attr('aria-labelledby', '#' + headingId);
});
}
/**
* Finds tags decorated with modal data-bsu attributes and fleshes out the HTML required
* for a modal.
*/
static decorateModals()
{
var modals = $('[data-bsu="modal"]');
$.each(modals, function() {
var modal = $(this);
var modalId = Helper.applyUniqueId(modal);
var children = modal.children();
if(children.length < 2 || children.length > 3) throw 'The modal should have two or three children';
var options = Helper.getOptions(modal);
var addHeaderCloseButton = VRS.arrayHelper.indexOf(options, 'header-close') !== -1;
var largeModal = VRS.arrayHelper.indexOf(options, 'large') !== -1;
var smallModal = VRS.arrayHelper.indexOf(options, 'small') !== -1;
var heading = $(children[0]);
var body = $(children[1]);
var footer = children.length === 3 ? $(children[2]) : null;
var headingTitle = $('<h4 />').addClass('modal-title');
heading.wrapInner(headingTitle).addClass('modal-header bg-primary');
var headingId = Helper.applyUniqueId(headingTitle);
if(addHeaderCloseButton) {
heading.prepend($('<button />')
.attr('type', 'button')
.attr('data-dismiss', 'modal')
.attr('aria-label', 'Close')
.addClass('close')
.append($('<span />')
.attr('aria-hidden', 'true')
.html('×')
)
);
}
body.addClass('modal-body');
if(footer != null) {
footer.addClass('modal-footer');
}
var modalDialogClass = 'modal-dialog';
if(largeModal) modalDialogClass += ' modal-lg';
else if(smallModal) modalDialogClass += ' modal-sm';
modal.addClass('modal fade')
.attr('tabindex', '-1')
.attr('role', 'dialog')
.attr('aria-labelledby', headingId)
.attr('aria-hidden', 'true')
.wrapInner($('<div />').addClass('modal-content'))
.wrapInner($('<div />').addClass(modalDialogClass));
modal.detach();
$('body').append(modal);
});
}
private static getOptions(element: JQuery) : string[]
{
var result: string[] = [];
var options = element.data('bsu-options');
if(options !== undefined && options !== null) {
$.each(options.split(' '), function(idx, option) {
option = option.trim();
if(option.length) {
result.push(option);
}
});
}
return result;
}
private static getFieldName(element: JQuery) : string
{
return element.data('bsu-field');
}
private static _UniqueId = 0;
private static applyUniqueId(element: JQuery) : string
{
var result = element.attr('id');
if(!result) {
result = '_bsu_unique_id_' + ++Helper._UniqueId;
element.attr('id', result);
}
return result;
}
}
} | the_stack |
import { UAProperty } from "node-opcua-address-space-base"
import { DataType } from "node-opcua-variant"
import { UInt32 } from "node-opcua-basic-types"
import { UATransition } from "node-opcua-nodeset-ua/source/ua_transition"
import { UAFiniteStateMachine, UAFiniteStateMachine_Base } from "node-opcua-nodeset-ua/source/ua_finite_state_machine"
import { UAInitialState } from "node-opcua-nodeset-ua/source/ua_initial_state"
import { UAState } from "node-opcua-nodeset-ua/source/ua_state"
import { UAAnalyserChannel_OperatingModeExecuteSubStateMachine } from "./ua_analyser_channel_operating_mode_execute_sub_state_machine"
import { UAAnalyserChannelOperatingExecuteState } from "./ua_analyser_channel_operating_execute_state"
export interface UAAnalyserChannel_OperatingModeSubStateMachine_stoppedToResettingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_resettingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_resettingToIdleTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_idleToStartingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_startingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_startingToExecuteTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_executeToCompletingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_completingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_completingToCompleteTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_completeToStoppedTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_executeToHoldingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_holdingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_holdingToHeldTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_heldToUnholdingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_unholdingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_unholdingToHoldingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_unholdingToExecuteTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_executeToSuspendingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_suspendingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_suspendingToSuspendedTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_suspendedToUnsuspendingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_unsuspendingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_unsuspendingToSuspendingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_unsuspendingToExecuteTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_stoppingToStoppedTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_abortingToAbortedTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_abortedToClearingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_clearingToStoppedTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_resettingToStoppingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_idleToStoppingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_startingToStoppingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_executeToStoppingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_completingToStoppingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_completeToStoppingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_suspendingToStoppingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_suspendedToStoppingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_unsuspendingToStoppingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_holdingToStoppingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_heldToStoppingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_unholdingToStoppingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_stoppedToAbortingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_resettingToAbortingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_idleToAbortingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_startingToAbortingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_executeToAbortingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_completingToAbortingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_completeToAbortingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_suspendingToAbortingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_suspendedToAbortingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_unsuspendingToAbortingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_holdingToAbortingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_heldToAbortingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_unholdingToAbortingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine_stoppingToAbortingTransition extends Omit<UATransition, "transitionNumber"> { // Object
transitionNumber: UAProperty<UInt32, /*z*/DataType.UInt32>;
}
/**
* AnalyserChannel OperatingMode SubStateMachine
*
* | | |
* |----------------|--------------------------------------------------|
* |namespace |http://opcfoundation.org/UA/ADI/ |
* |nodeClass |ObjectType |
* |typedDefinition |2:AnalyserChannel_OperatingModeSubStateMachineType ns=2;i=1008|
* |isAbstract |false |
*/
export interface UAAnalyserChannel_OperatingModeSubStateMachine_Base extends UAFiniteStateMachine_Base {
operatingExecuteSubStateMachine: UAAnalyserChannel_OperatingModeExecuteSubStateMachine;
/**
* stopped
* This is the initial state after
* AnalyserDeviceStateMachine state Powerup
*/
stopped: UAInitialState;
/**
* resetting
* This state is the result of a Reset or
* SetConfiguration Method call from the Stopped
* state.
*/
resetting: UAState;
/**
* idle
* The Resetting state is completed, all parameters
* have been committed and ready to start acquisition
*/
idle: UAState;
/**
* starting
* The analyser has received the Start or
* SingleAcquisitionStart Method call and it is
* preparing to enter in Execute state.
*/
starting: UAState;
/**
* execute
* All repetitive acquisition cycles are done in
* this state:
*/
execute: UAAnalyserChannelOperatingExecuteState;
/**
* completing
* This state is an automatic or commanded exit from
* the Execute state.
*/
completing: UAState;
/**
* complete
* At this point, the Completing state is done and
* it transitions automatically to Stopped state to
* wait.
*/
complete: UAState;
/**
* suspending
* This state is a result of a change in monitored
* conditions due to process conditions or factors.
*/
suspending: UAState;
/**
* suspended
* The analyser or channel may be running but no
* results are being generated while the analyser or
* channel is waiting for external process
* conditions to return to normal.
*/
suspended: UAState;
/**
* unsuspending
* This state is a result of a device request from
* Suspended state to transition back to the Execute
* state by calling the Unsuspend Method.
*/
unsuspending: UAState;
/**
* holding
* Brings the analyser or channel to a controlled
* stop or to a state which represents Held for the
* particular unit control mode
*/
holding: UAState;
/**
* held
* The Held state holds the analyser or channel's
* operation. At this state, no acquisition cycle is
* performed.
*/
held: UAState;
/**
* unholding
* The Unholding state is a response to an operator
* command to resume the Execute state.
*/
unholding: UAState;
/**
* stopping
* Initiated by a Stop Method call, this state:
*/
stopping: UAState;
/**
* aborting
* The Aborting state can be entered at any time in
* response to the Abort command or on the
* occurrence of a machine fault.
*/
aborting: UAState;
/**
* aborted
* This state maintains machine status information
* relevant to the Abort condition.
*/
aborted: UAState;
/**
* clearing
* Clears faults that may have occurred when
* Aborting and are present in the Aborted state
* before proceeding to a Stopped state
*/
clearing: UAState;
stoppedToResettingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_stoppedToResettingTransition;
resettingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_resettingTransition;
resettingToIdleTransition: UAAnalyserChannel_OperatingModeSubStateMachine_resettingToIdleTransition;
idleToStartingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_idleToStartingTransition;
startingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_startingTransition;
startingToExecuteTransition: UAAnalyserChannel_OperatingModeSubStateMachine_startingToExecuteTransition;
executeToCompletingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_executeToCompletingTransition;
completingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_completingTransition;
completingToCompleteTransition: UAAnalyserChannel_OperatingModeSubStateMachine_completingToCompleteTransition;
completeToStoppedTransition: UAAnalyserChannel_OperatingModeSubStateMachine_completeToStoppedTransition;
executeToHoldingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_executeToHoldingTransition;
holdingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_holdingTransition;
holdingToHeldTransition: UAAnalyserChannel_OperatingModeSubStateMachine_holdingToHeldTransition;
heldToUnholdingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_heldToUnholdingTransition;
unholdingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_unholdingTransition;
unholdingToHoldingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_unholdingToHoldingTransition;
unholdingToExecuteTransition: UAAnalyserChannel_OperatingModeSubStateMachine_unholdingToExecuteTransition;
executeToSuspendingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_executeToSuspendingTransition;
suspendingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_suspendingTransition;
suspendingToSuspendedTransition: UAAnalyserChannel_OperatingModeSubStateMachine_suspendingToSuspendedTransition;
suspendedToUnsuspendingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_suspendedToUnsuspendingTransition;
unsuspendingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_unsuspendingTransition;
unsuspendingToSuspendingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_unsuspendingToSuspendingTransition;
unsuspendingToExecuteTransition: UAAnalyserChannel_OperatingModeSubStateMachine_unsuspendingToExecuteTransition;
stoppingToStoppedTransition: UAAnalyserChannel_OperatingModeSubStateMachine_stoppingToStoppedTransition;
abortingToAbortedTransition: UAAnalyserChannel_OperatingModeSubStateMachine_abortingToAbortedTransition;
abortedToClearingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_abortedToClearingTransition;
clearingToStoppedTransition: UAAnalyserChannel_OperatingModeSubStateMachine_clearingToStoppedTransition;
resettingToStoppingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_resettingToStoppingTransition;
idleToStoppingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_idleToStoppingTransition;
startingToStoppingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_startingToStoppingTransition;
executeToStoppingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_executeToStoppingTransition;
completingToStoppingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_completingToStoppingTransition;
completeToStoppingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_completeToStoppingTransition;
suspendingToStoppingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_suspendingToStoppingTransition;
suspendedToStoppingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_suspendedToStoppingTransition;
unsuspendingToStoppingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_unsuspendingToStoppingTransition;
holdingToStoppingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_holdingToStoppingTransition;
heldToStoppingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_heldToStoppingTransition;
unholdingToStoppingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_unholdingToStoppingTransition;
stoppedToAbortingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_stoppedToAbortingTransition;
resettingToAbortingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_resettingToAbortingTransition;
idleToAbortingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_idleToAbortingTransition;
startingToAbortingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_startingToAbortingTransition;
executeToAbortingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_executeToAbortingTransition;
completingToAbortingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_completingToAbortingTransition;
completeToAbortingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_completeToAbortingTransition;
suspendingToAbortingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_suspendingToAbortingTransition;
suspendedToAbortingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_suspendedToAbortingTransition;
unsuspendingToAbortingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_unsuspendingToAbortingTransition;
holdingToAbortingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_holdingToAbortingTransition;
heldToAbortingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_heldToAbortingTransition;
unholdingToAbortingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_unholdingToAbortingTransition;
stoppingToAbortingTransition: UAAnalyserChannel_OperatingModeSubStateMachine_stoppingToAbortingTransition;
}
export interface UAAnalyserChannel_OperatingModeSubStateMachine extends UAFiniteStateMachine, UAAnalyserChannel_OperatingModeSubStateMachine_Base {
} | the_stack |
import { act, fireEvent, render, screen } from '@testing-library/react'
import React from 'react'
import useSWR from 'swr'
import useSWRMutation from 'swr/mutation'
import { createKey, sleep, nextTick } from './utils'
const waitForNextTick = () => act(() => sleep(1))
describe('useSWR - remote mutation', () => {
it('should return data after triggering', async () => {
const key = createKey()
function Page() {
const { data, trigger } = useSWRMutation(key, () => 'data')
return <button onClick={() => trigger()}>{data || 'pending'}</button>
}
render(<Page />)
// mount
await screen.findByText('pending')
fireEvent.click(screen.getByText('pending'))
await waitForNextTick()
screen.getByText('data')
})
it('should return data from `trigger`', async () => {
const key = createKey()
function Page() {
const [data, setData] = React.useState(null)
const { trigger } = useSWRMutation(key, () => 'data')
return (
<button
onClick={async () => {
setData(await trigger())
}}
>
{data || 'pending'}
</button>
)
}
render(<Page />)
// mount
await screen.findByText('pending')
fireEvent.click(screen.getByText('pending'))
await waitForNextTick()
screen.getByText('data')
})
it('should trigger request with the correct argument signature', async () => {
const key = createKey()
const fetcher = jest.fn(() => 'data')
function Page() {
const { data, trigger } = useSWRMutation([key, 'arg0'], fetcher)
return (
<button onClick={() => trigger('arg1')}>{data || 'pending'}</button>
)
}
render(<Page />)
// mount
await screen.findByText('pending')
expect(fetcher).not.toHaveBeenCalled()
fireEvent.click(screen.getByText('pending'))
await waitForNextTick()
screen.getByText('data')
expect(fetcher).toHaveBeenCalled()
expect(fetcher.mock.calls.length).toBe(1)
expect(fetcher.mock.calls[0]).toEqual([[key, 'arg0'], { arg: 'arg1' }])
})
it('should call `onSuccess` event', async () => {
const key = createKey()
const onSuccess = jest.fn()
function Page() {
const { data, trigger } = useSWRMutation(key, () => 'data', {
onSuccess
})
return <button onClick={() => trigger()}>{data || 'pending'}</button>
}
render(<Page />)
// mount
await screen.findByText('pending')
fireEvent.click(screen.getByText('pending'))
await waitForNextTick()
screen.getByText('data')
expect(onSuccess).toHaveBeenCalled()
})
it('should support configuring `onSuccess` with trigger', async () => {
const key = createKey()
const onSuccess = jest.fn()
function Page() {
const { data, trigger } = useSWRMutation(key, () => 'data')
return (
<button onClick={() => trigger(undefined, { onSuccess })}>
{data || 'pending'}
</button>
)
}
render(<Page />)
// mount
await screen.findByText('pending')
fireEvent.click(screen.getByText('pending'))
await waitForNextTick()
screen.getByText('data')
expect(onSuccess).toHaveBeenCalled()
})
it('should call `onError` event', async () => {
const key = createKey()
const onError = jest.fn()
const onInplaceError = jest.fn()
function Page() {
const { data, error, trigger } = useSWRMutation(
key,
async () => {
await sleep(10)
throw new Error('error!')
},
{
onError
}
)
return (
<button onClick={() => trigger().catch(onInplaceError)}>
{data || (error ? error.message : 'pending')}
</button>
)
}
render(<Page />)
// mount
await screen.findByText('pending')
fireEvent.click(screen.getByText('pending'))
await screen.findByText('error!')
expect(onError).toHaveBeenCalled()
expect(onInplaceError).toHaveBeenCalled()
})
it('should return `isMutating` state correctly', async () => {
const key = createKey()
function Page() {
const { data, trigger, isMutating } = useSWRMutation(key, async () => {
await sleep(10)
return 'data'
})
return (
<button onClick={trigger}>
state:{(isMutating ? 'pending' : data) || ''}
</button>
)
}
render(<Page />)
// mount
await screen.findByText('state:')
fireEvent.click(screen.getByText('state:'))
await screen.findByText('state:pending')
await screen.findByText('state:data')
})
it('should send `onError` and `onSuccess` events', async () => {
const key = createKey()
const onSuccess = jest.fn()
const onError = jest.fn()
let arg = false
function Page() {
const { data, error, trigger } = useSWRMutation(
key,
async (_, { arg: shouldReturnValue }) => {
await sleep(10)
if (shouldReturnValue) return 'data'
throw new Error('error')
},
{
onSuccess,
onError
}
)
return (
<button onClick={() => trigger(arg).catch(() => {})}>
{data || (error ? error.message : 'pending')}
</button>
)
}
render(<Page />)
// mount
await screen.findByText('pending')
fireEvent.click(screen.getByText('pending'))
await screen.findByText('error')
expect(onError).toHaveBeenCalled()
expect(onSuccess).not.toHaveBeenCalled()
arg = true
fireEvent.click(screen.getByText('error'))
await screen.findByText('data')
expect(onSuccess).toHaveBeenCalled()
})
it('should not dedupe trigger requests', async () => {
const key = createKey()
const fn = jest.fn()
function Page() {
const { trigger } = useSWRMutation(key, async () => {
fn()
await sleep(10)
return 'data'
})
return <button onClick={trigger}>trigger</button>
}
render(<Page />)
// mount
await screen.findByText('trigger')
expect(fn).not.toHaveBeenCalled()
fireEvent.click(screen.getByText('trigger'))
expect(fn).toHaveBeenCalledTimes(1)
fireEvent.click(screen.getByText('trigger'))
fireEvent.click(screen.getByText('trigger'))
fireEvent.click(screen.getByText('trigger'))
expect(fn).toHaveBeenCalledTimes(4)
})
it('should share the cache with `useSWR` when `populateCache` is enabled', async () => {
const key = createKey()
function Page() {
const { data } = useSWR(key)
const { trigger } = useSWRMutation(key, async () => {
await sleep(10)
return 'data'
})
return (
<div>
<button onClick={() => trigger(undefined, { populateCache: true })}>
trigger
</button>
<div>data:{data || 'none'}</div>
</div>
)
}
render(<Page />)
// mount
await screen.findByText('data:none')
fireEvent.click(screen.getByText('trigger'))
await screen.findByText('data:data')
})
it('should not read the cache from `useSWR`', async () => {
const key = createKey()
function Page() {
useSWR(key, () => 'data')
const { data } = useSWRMutation(key, () => 'wrong!')
return <div>data:{data || 'none'}</div>
}
render(<Page />)
// mount
await screen.findByText('data:none')
})
it('should be able to populate the cache for `useSWR`', async () => {
const key = createKey()
function Page() {
const { data } = useSWR(key, () => 'data')
const { trigger } = useSWRMutation(key, (_, { arg }) => arg)
return (
<div onClick={() => trigger('updated!', { populateCache: true })}>
data:{data || 'none'}
</div>
)
}
render(<Page />)
await screen.findByText('data:none')
// mount
await screen.findByText('data:data')
// mutate
fireEvent.click(screen.getByText('data:data'))
await screen.findByText('data:updated!')
})
it('should be able to populate the cache with a transformer', async () => {
const key = createKey()
function Page() {
const { data } = useSWR(key, () => 'data')
const { trigger } = useSWRMutation(key, (_, { arg }) => arg)
return (
<div
onClick={() =>
trigger('updated!', {
populateCache: (v, current) => v + ':' + current
})
}
>
data:{data || 'none'}
</div>
)
}
render(<Page />)
await screen.findByText('data:none')
// mount
await screen.findByText('data:data')
// mutate
fireEvent.click(screen.getByText('data:data'))
await screen.findByText('data:updated!:data')
})
it('should not trigger request when mutating from shared hooks', async () => {
const key = createKey()
const fn = jest.fn(() => 'data')
function Page() {
useSWRMutation(key, fn)
const { mutate } = useSWR(key)
return (
<div>
<button onClick={() => mutate()}>mutate</button>
</div>
)
}
render(<Page />)
// mount
await screen.findByText('mutate')
fireEvent.click(screen.getByText('mutate'))
await act(() => sleep(50))
expect(fn).not.toHaveBeenCalled()
})
it('should not trigger request when key changes', async () => {
const key = createKey()
const fn = jest.fn(() => 'data')
function Page() {
const [k, setK] = React.useState(key)
useSWRMutation(k, fn)
return (
<div>
<button onClick={() => setK(key + '_new')}>update key</button>
</div>
)
}
render(<Page />)
// mount
await screen.findByText('update key')
fireEvent.click(screen.getByText('update key'))
await act(() => sleep(50))
expect(fn).not.toHaveBeenCalled()
})
it('should prevent race conditions with `useSWR`', async () => {
const key = createKey()
const logger = jest.fn()
function Page() {
const { data } = useSWR(key, async () => {
await sleep(10)
return 'foo'
})
const { trigger } = useSWRMutation(key, async () => {
await sleep(20)
return 'bar'
})
logger(data)
return (
<div>
<button
onClick={() =>
trigger(undefined, { revalidate: false, populateCache: true })
}
>
trigger
</button>
<div>data:{data || 'none'}</div>
</div>
)
}
render(<Page />)
// mount
await screen.findByText('data:none')
fireEvent.click(screen.getByText('trigger'))
await act(() => sleep(50))
await screen.findByText('data:bar')
// It should never render `foo`.
expect(logger).not.toHaveBeenCalledWith('foo')
})
it('should revalidate after mutating by default', async () => {
const key = createKey()
const logger = jest.fn()
function Page() {
const { data } = useSWR(
key,
async () => {
await sleep(10)
return 'foo'
},
{ revalidateOnMount: false }
)
const { trigger } = useSWRMutation(key, async () => {
await sleep(20)
return 'bar'
})
logger(data)
return (
<div>
<button onClick={() => trigger(undefined)}>trigger</button>
<div>data:{data || 'none'}</div>
</div>
)
}
render(<Page />)
// mount
await screen.findByText('data:none')
fireEvent.click(screen.getByText('trigger'))
await act(() => sleep(50))
// It triggers revalidation
await screen.findByText('data:foo')
// It should never render `bar` since we never populate the cache.
expect(logger).not.toHaveBeenCalledWith('bar')
})
it('should revalidate after populating the cache', async () => {
const key = createKey()
const logger = jest.fn()
function Page() {
const { data } = useSWR(
key,
async () => {
await sleep(20)
return 'foo'
},
{ revalidateOnMount: false }
)
const { trigger } = useSWRMutation(key, async () => {
await sleep(20)
return 'bar'
})
logger(data)
return (
<div>
<button onClick={() => trigger(undefined, { populateCache: true })}>
trigger
</button>
<div>data:{data || 'none'}</div>
</div>
)
}
render(<Page />)
// mount
await screen.findByText('data:none')
fireEvent.click(screen.getByText('trigger'))
// Cache is updated
await screen.findByText('data:bar')
// A revalidation is triggered
await screen.findByText('data:foo')
})
it('should be able to turn off auto revalidation', async () => {
const key = createKey()
const logger = jest.fn()
function Page() {
const { data } = useSWR(
key,
async () => {
await sleep(10)
return 'foo'
},
{ revalidateOnMount: false }
)
const { trigger } = useSWRMutation(
key,
async () => {
await sleep(20)
return 'bar'
},
{ revalidate: false, populateCache: true }
)
logger(data)
return (
<div>
<button onClick={() => trigger(undefined)}>trigger</button>
<div>data:{data || 'none'}</div>
</div>
)
}
render(<Page />)
// mount
await screen.findByText('data:none')
fireEvent.click(screen.getByText('trigger'))
await act(() => sleep(50))
// It should not trigger revalidation
await screen.findByText('data:bar')
// It should never render `foo`.
expect(logger).not.toHaveBeenCalledWith('foo')
})
it('should be able to configure auto revalidation from trigger', async () => {
const key = createKey()
const logger = jest.fn()
function Page() {
const { data } = useSWR(
key,
async () => {
await sleep(10)
return 'foo'
},
{ revalidateOnMount: false }
)
const { trigger } = useSWRMutation(
key,
async () => {
await sleep(20)
return 'bar'
},
{ populateCache: true }
)
logger(data)
return (
<div>
<button onClick={() => trigger(undefined, { revalidate: false })}>
trigger1
</button>
<button onClick={() => trigger(undefined, { revalidate: true })}>
trigger2
</button>
<div>data:{data || 'none'}</div>
</div>
)
}
render(<Page />)
// mount
await screen.findByText('data:none')
fireEvent.click(screen.getByText('trigger1'))
await act(() => sleep(50))
// It should not trigger revalidation
await screen.findByText('data:bar')
// It should never render `foo`.
expect(logger).not.toHaveBeenCalledWith('foo')
fireEvent.click(screen.getByText('trigger2'))
await act(() => sleep(50))
// It should trigger revalidation
await screen.findByText('data:foo')
})
it('should be able to reset the state', async () => {
const key = createKey()
function Page() {
const { data, trigger, reset } = useSWRMutation(key, async () => {
return 'data'
})
return (
<div>
<button onClick={trigger}>trigger</button>
<button onClick={reset}>reset</button>
<div>data:{data || 'none'}</div>
</div>
)
}
render(<Page />)
// mount
await screen.findByText('data:none')
fireEvent.click(screen.getByText('trigger'))
// Cache is updated
await screen.findByText('data:data')
// reset
fireEvent.click(screen.getByText('reset'))
await screen.findByText('data:none')
})
it('should prevent race condition if reset the state', async () => {
const key = createKey()
const onSuccess = jest.fn()
function Page() {
const { data, trigger, reset } = useSWRMutation(key, async () => {
await sleep(10)
return 'data'
})
return (
<div>
<button onClick={() => trigger(undefined, { onSuccess })}>
trigger
</button>
<button onClick={reset}>reset</button>
<div>data:{data || 'none'}</div>
</div>
)
}
render(<Page />)
// mount
await screen.findByText('data:none')
// start mutation
fireEvent.click(screen.getByText('trigger'))
// reset, before it ends
fireEvent.click(screen.getByText('reset'))
await act(() => sleep(30))
await screen.findByText('data:none')
})
it('should prevent race condition if triggered multiple times', async () => {
const key = createKey()
const logger = []
let id = 0
function Page() {
const { data, trigger } = useSWRMutation(key, async () => {
await sleep(10)
return id++
})
logger.push(data)
return <button onClick={trigger}>trigger</button>
}
render(<Page />)
// Mount
await screen.findByText('trigger')
// Start mutation multiple times, to break the previous one
fireEvent.click(screen.getByText('trigger')) // 0
await act(() => sleep(5))
fireEvent.click(screen.getByText('trigger')) // 1
await act(() => sleep(5))
fireEvent.click(screen.getByText('trigger')) // 2
await act(() => sleep(20))
// Shouldn't have intermediate states
expect(logger).toEqual([undefined, 2])
})
it('should error if no mutator is given', async () => {
const key = createKey()
const catchError = jest.fn()
function Page() {
const { trigger } = useSWRMutation(key, null)
return (
<div>
<button onClick={() => trigger().catch(catchError)}>trigger</button>
</div>
)
}
render(<Page />)
fireEvent.click(screen.getByText('trigger'))
await nextTick()
expect(catchError).toBeCalled()
})
it('should support optimistic updates', async () => {
const key = createKey()
function Page() {
const { data } = useSWR(key, async () => {
await sleep(10)
return ['foo']
})
const { trigger } = useSWRMutation(key, async (_, { arg }) => {
await sleep(20)
return arg.toUpperCase()
})
return (
<div>
<button
onClick={() =>
trigger('bar', {
optimisticData: current => [...current, 'bar'],
populateCache: (added, current) => [...current, added],
revalidate: false
})
}
>
trigger
</button>
<div>data:{JSON.stringify(data)}</div>
</div>
)
}
render(<Page />)
// mount
await screen.findByText('data:["foo"]')
// optimistic update
fireEvent.click(screen.getByText('trigger'))
await screen.findByText('data:["foo","bar"]')
await act(() => sleep(50))
await screen.findByText('data:["foo","BAR"]')
// 2nd check
fireEvent.click(screen.getByText('trigger'))
await screen.findByText('data:["foo","BAR","bar"]')
await act(() => sleep(50))
await screen.findByText('data:["foo","BAR","BAR"]')
})
}) | the_stack |
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
IWebPartContext,
PropertyPaneToggle,
PropertyPaneSlider
} from '@microsoft/sp-webpart-base';
import { Version } from '@microsoft/sp-core-library';
import * as strings from 'carousel3DStrings';
import { ICarousel3DWebPartProps } from './ICarousel3DWebPartProps';
//Imports property pane custom fields
import { PropertyFieldCustomList, CustomListFieldType } from 'sp-client-custom-fields/lib/PropertyFieldCustomList';
import { PropertyFieldFontPicker } from 'sp-client-custom-fields/lib/PropertyFieldFontPicker';
import { PropertyFieldFontSizePicker } from 'sp-client-custom-fields/lib/PropertyFieldFontSizePicker';
import { PropertyFieldColorPickerMini } from 'sp-client-custom-fields/lib/PropertyFieldColorPickerMini';
//Loads external JS libs
import * as $ from 'jquery';
require('jqueryreflection');
require('cloud9carousel');
export default class Carousel3DWebPart extends BaseClientSideWebPart<ICarousel3DWebPartProps> {
private guid: string;
/**
* @function
* Web part contructor.
*/
public constructor(context?: IWebPartContext) {
super();
//Generates the unique ID
this.guid = this.getGuid();
//Hack: to invoke correctly the onPropertyChange function outside this class
//we need to bind this object on it first
this.onPropertyPaneFieldChanged = this.onPropertyPaneFieldChanged.bind(this);
//Binds the async method
this.rendered = this.rendered.bind(this);
this.onLoaded = this.onLoaded.bind(this);
}
/**
* @function
* Gets WP data version
*/
protected get dataVersion(): Version {
return Version.parse('1.0');
}
/**
* @function
* Renders HTML code
*/
public render(): void {
//Checks if the carousel is already loaded. If yes, desacrivate it
if (($ as any)('#' + this.guid + '-carousel').data("carousel") != null) {
($ as any)('#' + this.guid + '-carousel').data("carousel").deactivate();
($ as any)('#' + this.guid + '-carousel').data("carousel").onRendered = null;
}
//Defines the main DIV container
var html = '<div id="' + this.guid + '-bigCarousel" style="height:0px; visibility: hidden"><div id="' + this.guid + '-carousel"> ';
if (this.properties.items != null) {
//Browse the items collection
this.properties.items.map(item => {
if (item != null && item.Enabled != "false") {
//Adds a new Carousel entry
html += '<img class="cloud9-item" style="cursor: pointer" dataText="'+ item['Link Text'] + '" dataUrl="'+ item['Link Url'] + '" src="' + item.Picture + '" height="' + this.properties.itemHeight + '" alt="' + item.Title + '" />';
}
});
}
html += `
</div>
`;
if (this.properties.showTitle === true) {
//Shows the title
html += '<div style=\'font-size: ' + this.properties.fontSize + '; color: ' + this.properties.fontColor + '; font-family:'
+ this.properties.font + '\'><div id="' + this.guid + '-item-title" style="position: absolute; bottom:0; width: 100%; text-align: center;"> </div></div>';
}
if (this.properties.showButton === true) {
//Shows the button to navigate
html += '<div id="' + this.guid + '-buttons" style="height: 100%">';
html += `
<button class="left" style="float:left; height: 60px; position: absolute; top: 45%; cursor: pointer;">
<i class='ms-Icon ms-Icon--ChevronLeft' aria-hidden="true" style="font-size:large"></i>
</button>
<button class="right" style="float:right; height: 60px; position: absolute; top: 45%; margin-right: 10px; right: 0; cursor: pointer;">
<i class='ms-Icon ms-Icon--ChevronRight' aria-hidden="true" style="font-size:large"></i>
</button>
</div>
`;
}
html += `
</div>
`;
this.domElement.innerHTML = html;
this.renderContents();
}
/**
* @function
* Renders JavaScript JQuery plugin
*/
private renderContents(): void {
if (($ as any)('#' + this.guid + '-carousel') != null) {
//Calls the jquery carousel init method
($ as any)('#' + this.guid + '-carousel').Cloud9Carousel({
buttonLeft: $("#" + this.guid + "-buttons > .left"),
buttonRight: $("#" + this.guid + "-buttons > .right"),
autoPlay: this.properties.autoPlay === true ? 1 : 0,
autoPlayDelay: this.properties.autoPlayDelay,
bringToFront: this.properties.bringToFront,
speed: this.properties.speed,
yOrigin: this.properties.yOrigin,
yRadius: this.properties.yRadius,
xOrigin: this.properties.xOrigin,
xRadius: this.properties.xRadius,
mirror: {
gap: this.properties.mirrorGap,
height: this.properties.mirrorHeight,
opacity: this.properties.mirrorOpacity
},
onRendered: this.rendered,
onLoaded: this.onLoaded,
});
}
}
/**
* @function
* Occurs when the carousel jquery plugin is loaded. So, change the visiblity
*/
private onLoaded(): void {
$("#" + this.guid + "-bigCarousel").css( 'visibility', 'visible' );
$("#" + this.guid + "-bigCarousel").css( 'height', this.properties.height);
$("#" + this.guid + "-carousel").css( 'visibility', 'visible' );
$("#" + this.guid + "-carousel").css( 'display', 'block' );
$("#" + this.guid + "-carousel").css( 'overflow', 'visible' );
$("#" + this.guid + "-carousel").fadeIn( 1500 );
}
/**
* @function
* Occurs when the carousel is rendered. So, display the item
*/
private rendered(carousel: any) {
if ($('#' + this.guid + '-item-title') != null) {
var subTitle: string = '';
subTitle += carousel.nearestItem().element.alt;
if (carousel.nearestItem().element.children[0].attributes.dataurl) {
var linkUrl = carousel.nearestItem().element.children[0].attributes.dataurl.value;
if (linkUrl && linkUrl != '' && linkUrl != 'undefined') {
subTitle += " <a href='" + linkUrl + "'>";
var dataText = carousel.nearestItem().element.children[0].attributes.datatext.value;
if (dataText == null || dataText == '')
dataText = strings.ReadMore;
subTitle += dataText;
subTitle += "</a>";
}
}
$('#' + this.guid + '-item-title').html( subTitle );
// Fade in based on proximity of the item
var c = Math.cos((carousel.floatIndex() % 1) * 2 * Math.PI);
$('#' + this.guid + '-item-title').css('opacity', 0.5 + (0.5 * c));
}
}
/**
* @function
* Generates a GUID
*/
private getGuid(): string {
return this.s4() + this.s4() + '-' + this.s4() + '-' + this.s4() + '-' +
this.s4() + '-' + this.s4() + this.s4() + this.s4();
}
/**
* @function
* Generates a GUID part
*/
private s4(): string {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
/**
* @function
* PropertyPanel settings definition
*/
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
displayGroupsAsAccordion: true,
groups: [
{
groupName: strings.DataGroupName,
groupFields: [
PropertyFieldCustomList('items', {
label: strings.DataFieldLabel,
value: this.properties.items,
headerText: "Manage Items",
fields: [
{ id: 'Title', title: 'Title', required: true, type: CustomListFieldType.string },
{ id: 'Enabled', title: 'Enabled', required: true, type: CustomListFieldType.boolean },
{ id: 'Picture', title: 'Picture', required: true, type: CustomListFieldType.picture },
//{ title: 'Picture', required: true, type: CustomListFieldType.picture },
{ id: 'Link Url', title: 'Link Url', required: false, type: CustomListFieldType.string, hidden: true },
{ id: 'Link Text', title: 'Link Text', required: false, type: CustomListFieldType.string, hidden: true }
],
onPropertyChange: this.onPropertyPaneFieldChanged,
render: this.render.bind(this),
disableReactivePropertyChanges: this.disableReactivePropertyChanges,
context: this.context,
properties: this.properties,
key: "carousel3DListField"
}),
PropertyPaneSlider('itemHeight', {
label: strings.ItemHeightFieldLabel,
min: 10,
max: 400,
step: 1,
showValue: true
}),
]
},
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneSlider('speed', {
label: strings.SpeedFieldLabel,
min: 1,
max: 10,
step: 1,
showValue: true
}),
PropertyPaneToggle('autoPlay', {
label: strings.AutoplayFieldLabel
}),
PropertyPaneSlider('autoPlayDelay', {
label: strings.AutoplayDelayFieldLabel,
min: 0,
max: 10000,
step: 100,
showValue: true
})
]
},
{
groupName: strings.GeneralGroupName,
groupFields: [
PropertyPaneSlider('height', {
label: strings.HeightFieldLabel,
min: 0,
max: 800,
step: 5,
showValue: true
}),
PropertyPaneToggle('showTitle', {
label: strings.ShowTitleFieldLabel
}),
PropertyPaneToggle('showButton', {
label: strings.ShowButtonsFieldLabel
}),
PropertyPaneToggle('bringToFront', {
label: strings.BringtoFrontFieldLabel
})
]
},
{
groupName: strings.MirrorGroupName,
groupFields: [
PropertyPaneSlider('mirrorGap', {
label: strings.MirrorGapFieldLabel,
min: 0,
max: 20,
step: 1,
showValue: true
}),
PropertyPaneSlider('mirrorHeight', {
label: strings.MirrorHeightFieldLabel,
min: 0,
max: 1,
step: 0.1,
showValue: true
}),
PropertyPaneSlider('mirrorOpacity', {
label: strings.MirrorOpacityFieldLabel,
min: 0,
max: 1,
step: 0.1,
showValue: true
})
]
},
{
groupName: strings.OriginGroupName,
groupFields: [
PropertyPaneSlider('yOrigin', {
label: strings.YOriginFieldLabel,
min: 0,
max: 200,
step: 1,
showValue: true
}),
PropertyPaneSlider('yRadius', {
label: strings.YRadiusFieldLabel,
min: 0,
max: 200,
step: 1,
showValue: true
}),
PropertyPaneSlider('xOrigin', {
label: strings.XOriginFieldLabel,
min: 0,
max: 700,
step: 1,
showValue: true
}),
PropertyPaneSlider('xRadius', {
label: strings.XRadiusFieldLabel,
min: 0,
max: 700,
step: 1,
showValue: true
})
]
},
{
groupName: strings.TitleGroupName,
groupFields: [
PropertyFieldFontPicker('font', {
label: strings.FontFieldLabel,
useSafeFont: true,
previewFonts: true,
initialValue: this.properties.font,
onPropertyChange: this.onPropertyPaneFieldChanged,
render: this.render.bind(this),
disableReactivePropertyChanges: this.disableReactivePropertyChanges,
properties: this.properties,
key: "carousel3DFontField"
}),
PropertyFieldFontSizePicker('fontSize', {
label: strings.FontSizeFieldLabel,
usePixels: true,
preview: true,
initialValue: this.properties.fontSize,
onPropertyChange: this.onPropertyPaneFieldChanged,
render: this.render.bind(this),
disableReactivePropertyChanges: this.disableReactivePropertyChanges,
properties: this.properties,
key: "carousel3DFontSizeField"
}),
PropertyFieldColorPickerMini('fontColor', {
label: strings.ColorFieldLabel,
initialColor: this.properties.fontColor,
onPropertyChange: this.onPropertyPaneFieldChanged,
render: this.render.bind(this),
disableReactivePropertyChanges: this.disableReactivePropertyChanges,
properties: this.properties,
key: "carousel3DFontColorField"
})
]
}
]
}
]
};
}
} | the_stack |
import SteamID from 'steamid';
import { promises as fsp } from 'fs';
import sleepasync from 'sleep-async';
import { removeLinkProtocol } from '../functions/utils';
import Bot from '../../Bot';
import Inventory from '../../Inventory';
import CommandParser from '../../CommandParser';
import { getOptionsPath, JsonOptions, removeCliOptions } from '../../Options';
import validator from '../../../lib/validator';
import log from '../../../lib/logger';
import { deepMerge } from '../../../lib/tools/deep-merge';
export type OptionsKeys =
| 'miscSettings'
| 'sendAlert'
| 'pricelist'
| 'bypass'
| 'tradeSummary'
| 'steamChat'
| 'highValue'
| 'normalize'
| 'details'
| 'statistics'
| 'autokeys'
| 'crafting'
| 'offerReceived'
| 'manualReview'
| 'discordWebhook'
| 'customMessage'
| 'commands'
| 'detailsExtra';
let isSending = false;
export default class OptionsCommands {
constructor(private readonly bot: Bot) {
this.bot = bot;
}
async optionsCommand(steamID: SteamID, message: string): Promise<void> {
if (isSending) {
return this.bot.sendMessage(steamID, '❌ Please wait.');
}
const liveOptions = deepMerge({}, this.bot.options) as JsonOptions;
// remove any CLI stuff
removeCliOptions(liveOptions);
const optKey = CommandParser.removeCommand(message);
const optionsKeys = Object.keys(liveOptions);
if (!optKey) {
return this.bot.sendMessage(
steamID,
'❌ Wrong syntax. Please include any valid options parent key.\nExample: "!options miscSettings"' +
'\n\nValid options parent keys:\n• ' +
optionsKeys.join('\n• ')
);
} else {
if (!optionsKeys.includes(optKey)) {
isSending = false;
return this.bot.sendMessage(
steamID,
`❌ "${optKey}" parent key does not exist in options.` +
`\n\nValid parent keys:\n• ` +
optionsKeys.join('\n• ')
);
}
// hard-coding bad 🙄
isSending = true;
if (optKey === 'tradeSummary') {
const webhook = liveOptions['tradeSummary'];
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
tradeSummary: {
declinedTrade: webhook.declinedTrade,
showStockChanges: webhook.showStockChanges,
showTimeTakenInMS: webhook.showTimeTakenInMS,
showDetailedTimeTaken: webhook.showDetailedTimeTaken,
showItemPrices: webhook.showItemPrices,
showPureInEmoji: webhook.showPureInEmoji,
showProperName: webhook.showProperName
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
const ct = webhook.customText;
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
tradeSummary: {
customText: {
summary: ct.summary,
asked: ct.asked,
offered: ct.offered
}
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
tradeSummary: {
customText: {
profitFromOverpay: ct.profitFromOverpay,
lossFromUnderpay: ct.lossFromUnderpay
}
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
tradeSummary: {
customText: {
timeTaken: ct.timeTaken,
keyRate: ct.keyRate,
pureStock: ct.pureStock,
totalItems: ct.totalItems
}
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
tradeSummary: {
customText: {
spells: ct.spells,
strangeParts: ct.strangeParts,
killstreaker: ct.killstreaker,
sheen: ct.sheen,
painted: ct.painted
}
}
},
null,
2
)}`
);
} else if (optKey === 'offerReceived') {
const webhook = liveOptions['offerReceived'];
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
offerReceived: {
sendPreAcceptMessage: webhook.sendPreAcceptMessage,
alwaysDeclineNonTF2Items: webhook.alwaysDeclineNonTF2Items,
invalidValue: webhook.invalidValue
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
offerReceived: {
invalidItems: webhook.invalidItems,
disabledItems: webhook.disabledItems
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
offerReceived: {
overstocked: webhook.overstocked,
understocked: webhook.understocked
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
offerReceived: {
duped: webhook.duped,
escrowCheckFailed: webhook.escrowCheckFailed,
bannedCheckFailed: webhook.bannedCheckFailed
}
},
null,
2
)}`
);
} else if (optKey === 'manualReview') {
const webhook = liveOptions['manualReview'];
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
manualReview: {
enable: webhook.enable,
showOfferSummary: webhook.showOfferSummary,
showReviewOfferNote: webhook.showReviewOfferNote,
showOwnerCurrentTime: webhook.showOwnerCurrentTime,
showItemPrices: webhook.showItemPrices
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
manualReview: {
invalidValue: webhook.invalidValue,
invalidItems: webhook.invalidItems,
disabledItems: webhook.disabledItems
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
manualReview: {
overstocked: webhook.overstocked,
understocked: webhook.understocked,
duped: webhook.duped,
dupedCheckFailed: webhook.dupedCheckFailed
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
manualReview: {
escrowCheckFailed: webhook.escrowCheckFailed,
bannedCheckFailed: webhook.bannedCheckFailed,
additionalNotes: webhook.additionalNotes
}
},
null,
2
)}`
);
} else if (optKey === 'discordWebhook') {
/*
const webhook = liveOptions['discordWebhook'];
const webhookKeys = Object.keys(webhook);
const webhookCount = webhookKeys.length;
for (let j = 0; j < webhookCount; j++) {
const obj = {};
obj[webhookKeys[j]] = webhook[webhookKeys[j] as DiscordWebhookKeys];
this.bot.sendMessage(steamID, `/code ${JSON.stringify({ discordWebhook: obj }, null, 2)}`);
await sleepasync().Promise.sleep(2000);
}
*/
const webhook = liveOptions['discordWebhook'];
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
discordWebhook: {
ownerID: webhook.ownerID,
displayName: webhook.displayName,
avatarURL: webhook.avatarURL,
embedColor: webhook.embedColor
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
discordWebhook: {
tradeSummary: webhook.tradeSummary
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
discordWebhook: {
declinedTrade: webhook.declinedTrade,
offerReview: webhook.offerReview
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
discordWebhook: {
messages: webhook.messages,
priceUpdate: webhook.priceUpdate
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
discordWebhook: {
sendAlert: webhook.sendAlert,
sendStats: webhook.sendStats
}
},
null,
2
)}`
);
} else if (optKey === 'customMessage') {
const webhook = liveOptions['customMessage'];
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
customMessage: {
sendOffer: webhook.sendOffer,
welcome: webhook.welcome,
iDontKnowWhatYouMean: webhook.iDontKnowWhatYouMean,
success: webhook.success,
successEscrow: webhook.successEscrow
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
customMessage: {
decline: webhook.decline
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
customMessage: {
accepted: webhook.accepted
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
customMessage: {
tradedAway: webhook.tradedAway,
failedMobileConfirmation: webhook.failedMobileConfirmation,
cancelledActiveForAwhile: webhook.cancelledActiveForAwhile,
clearFriends: webhook.clearFriends
}
},
null,
2
)}`
);
} else if (optKey === 'commands') {
const webhook = liveOptions['commands'];
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
commands: {
enable: webhook.enable,
customDisableReply: webhook.customDisableReply,
how2trade: webhook.how2trade,
price: webhook.price
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
commands: {
buy: webhook.buy,
sell: webhook.sell
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
commands: {
buycart: webhook.buycart,
sellcart: webhook.sellcart
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
commands: {
cart: webhook.cart,
clearcart: webhook.clearcart
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
commands: {
checkout: webhook.checkout
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
commands: {
addToQueue: webhook.addToQueue
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
commands: {
cancel: webhook.cancel
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
commands: {
queue: webhook.queue
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
commands: {
owner: webhook.owner,
discord: webhook.discord
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
commands: {
more: webhook.more,
autokeys: webhook.autokeys
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
commands: {
message: webhook.message,
time: webhook.time
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
commands: {
uptime: webhook.uptime,
pure: webhook.pure
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
commands: {
rate: webhook.rate,
stock: webhook.stock
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
commands: {
craftweapon: webhook.craftweapon,
uncraftweapon: webhook.uncraftweapon
}
},
null,
2
)}`
);
} else if (optKey === 'detailsExtra') {
const webhook = liveOptions['detailsExtra'];
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
detailsExtra: {
spells: webhook.spells
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
detailsExtra: {
sheens: webhook.sheens
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
detailsExtra: {
killstreakers: webhook.killstreakers
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
const paints = webhook.painted;
const paintedKeys = Object.keys(paints);
const paintedKeysCount = paintedKeys.length;
const iteratePaint = Math.ceil(paintedKeysCount / 3);
let keysIndexPaint = 0;
for (let i = 0; i < iteratePaint; i++) {
const obj = {};
const max = keysIndexPaint + 3;
for (let j = keysIndexPaint; j < max; j++) {
const paintKey = paintedKeys[j];
if (paintKey !== undefined) {
obj[paintKey] = paints[paintKey as 'A Color Similar to Slate' | 'Legacy Paint'];
}
}
keysIndexPaint += 3;
if (Object.keys(obj).length > 0) {
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
detailsExtra: {
painted: obj
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
}
}
const strangeParts = webhook.strangeParts;
const strangePartsKeys = Object.keys(strangeParts);
const strangePartsKeysCount = strangePartsKeys.length;
const iterateSP = Math.ceil(strangePartsKeysCount / 6);
let keysIndex = 0;
for (let i = 0; i < iterateSP; i++) {
const obj = {};
const max = keysIndex + 7;
for (let j = keysIndex; j < max; j++) {
const spKey = strangePartsKeys[j];
if (spKey !== undefined) {
obj[spKey] = strangeParts[spKey as 'Robots Destroyed' | 'Projectiles Reflected'];
}
}
keysIndex += 7;
if (Object.keys(obj).length > 0) {
this.bot.sendMessage(
steamID,
`/code ${JSON.stringify(
{
detailsExtra: {
strangeParts: obj
}
},
null,
2
)}`
);
await sleepasync().Promise.sleep(3000);
}
}
} else {
const show = {};
show[optKey] = liveOptions[optKey as OptionsKeys];
this.bot.sendMessage(steamID, `/code ${JSON.stringify(show, null, 2)}`);
}
isSending = false;
}
}
updateOptionsCommand(steamID: SteamID, message: string): void {
const opt = this.bot.options;
if (
message.includes('painted.An Extraordinary Abundance of Tinge') ||
message.includes('painted.Ye Olde Rustic Colour') ||
message.includes('painted.An Air of Debonair')
) {
message = removeLinkProtocol(message);
}
const params = CommandParser.parseParams(CommandParser.removeCommand(message)) as unknown;
const optionsPath = getOptionsPath(opt.steamAccountName);
const saveOptions = deepMerge({}, opt) as JsonOptions;
removeCliOptions(saveOptions);
if (Object.keys(params).length === 0) {
const msg = '⚠️ Missing properties to update.';
if (steamID) {
this.bot.sendMessage(steamID, msg);
} else {
log.warn(msg);
}
return;
}
const knownParams = params as JsonOptions;
if (knownParams.discordWebhook?.ownerID !== undefined) {
// Stringify numbers
if (Array.isArray(knownParams.discordWebhook.ownerID)) {
knownParams.discordWebhook.ownerID.map(id => String(id));
}
}
if (knownParams.discordWebhook?.embedColor !== undefined) {
// Stringify numbers
knownParams.discordWebhook.embedColor = String(knownParams.discordWebhook.embedColor);
}
const result: JsonOptions = deepMerge(saveOptions, knownParams);
const errors = validator(result, 'options');
if (errors !== null) {
const msg = '❌ Error updating options: ' + errors.join(', ');
if (steamID) {
this.bot.sendMessage(steamID, msg);
} else {
log.error(msg);
}
return;
}
fsp.writeFile(optionsPath, JSON.stringify(saveOptions, null, 4), { encoding: 'utf8' })
.then(() => {
deepMerge(opt, saveOptions);
const msg = '✅ Updated options!';
if (knownParams.miscSettings?.game?.playOnlyTF2 === true) {
this.bot.client.gamesPlayed([]);
this.bot.client.gamesPlayed(440);
}
if (typeof knownParams.miscSettings?.game?.customName === 'string') {
this.bot.client.gamesPlayed([]);
this.bot.client.gamesPlayed(
(
knownParams.miscSettings?.game?.playOnlyTF2 !== undefined
? knownParams.miscSettings.game.playOnlyTF2
: opt.miscSettings.game.playOnlyTF2
)
? 440
: [knownParams.miscSettings.game.customName, 440]
);
}
if (knownParams.miscSettings?.autobump?.enable === true) {
this.bot.listings.setupAutorelist();
this.bot.handler.disableAutoRefreshListings();
} else if (knownParams.miscSettings?.autobump?.enable === false) {
this.bot.listings.disableAutorelistOption();
this.bot.handler.enableAutoRefreshListings();
}
if (knownParams.statistics?.sendStats?.enable === true) {
this.bot.handler.sendStats();
} else if (knownParams.statistics?.sendStats?.enable === false) {
this.bot.handler.disableSendStats();
}
if (knownParams.statistics?.sendStats?.time !== undefined) {
this.bot.handler.sendStats();
}
if (knownParams.highValue !== undefined) {
void this.bot.inventoryManager.getInventory.fetch();
Inventory.setOptions(this.bot.paints, this.bot.strangeParts, opt.highValue);
}
if (typeof knownParams.normalize === 'object') {
void this.bot.inventoryManager.getInventory.fetch();
}
if (typeof knownParams.autokeys === 'object') {
if (knownParams.autokeys.enable !== undefined && !knownParams.autokeys.enable) {
void this.bot.handler.autokeys.disable(this.bot.pricelist.getKeyPrices);
}
this.bot.handler.autokeys.check();
}
if (steamID) {
return this.bot.sendMessage(steamID, msg);
} else {
return log.info(msg);
}
})
.catch(err => {
const errStringify = JSON.stringify(err);
const errMessage = errStringify === '' ? (err as Error)?.message : errStringify;
const msg = `❌ Error saving options file to disk: ${errMessage}`;
if (steamID) {
this.bot.sendMessage(steamID, msg);
} else {
log.error(msg);
}
return;
});
}
clearArrayCommand(steamID: SteamID, message: string): void {
const params = CommandParser.parseParams(CommandParser.removeCommand(message)) as unknown;
if (Object.keys(params).length === 0) {
const msg = '⚠️ Missing properties to update.';
if (steamID) {
this.bot.sendMessage(steamID, msg);
} else {
log.warn(msg);
}
return;
}
const knownParams = params as JsonOptions;
if (
knownParams.pricelist === undefined &&
knownParams.highValue === undefined &&
knownParams.statistics === undefined &&
knownParams.offerReceived === undefined &&
knownParams.discordWebhook === undefined &&
knownParams.commands === undefined
) {
return this.bot.sendMessage(steamID, '❌ Parent parameter does not have any value with array type.');
}
const opt = this.bot.options;
if (knownParams.pricelist?.partialPriceUpdate?.excludeSKU !== undefined) {
opt.pricelist.partialPriceUpdate.excludeSKU.length = 0;
}
if (knownParams.highValue !== undefined) {
let isChanged = false;
if (knownParams.highValue.spells?.names !== undefined) {
isChanged = true;
opt.highValue.spells.names.length = 0;
}
if (knownParams.highValue.spells?.exceptionSkus !== undefined) {
isChanged = true;
opt.highValue.spells.exceptionSkus.length = 0;
}
if (knownParams.highValue.sheens?.names !== undefined) {
isChanged = true;
opt.highValue.sheens.names.length = 0;
}
if (knownParams.highValue.sheens?.exceptionSkus !== undefined) {
isChanged = true;
opt.highValue.sheens.exceptionSkus.length = 0;
}
if (knownParams.highValue.killstreakers?.names !== undefined) {
isChanged = true;
opt.highValue.killstreakers.names.length = 0;
}
if (knownParams.highValue.killstreakers?.exceptionSkus !== undefined) {
isChanged = true;
opt.highValue.killstreakers.exceptionSkus.length = 0;
}
if (knownParams.highValue.strangeParts?.names !== undefined) {
isChanged = true;
opt.highValue.strangeParts.names.length = 0;
}
if (knownParams.highValue.strangeParts?.exceptionSkus !== undefined) {
isChanged = true;
opt.highValue.strangeParts.exceptionSkus.length = 0;
}
if (knownParams.highValue.painted?.names !== undefined) {
isChanged = true;
opt.highValue.painted.names.length = 0;
}
if (knownParams.highValue.painted?.exceptionSkus !== undefined) {
isChanged = true;
opt.highValue.painted.exceptionSkus.length = 0;
}
if (isChanged) Inventory.setOptions(this.bot.paints, this.bot.strangeParts, opt.highValue);
}
if (knownParams.statistics?.sendStats?.time !== undefined) {
opt.statistics.sendStats.time.length = 0;
}
if (knownParams.offerReceived?.invalidValue?.exceptionValue?.skus !== undefined) {
opt.offerReceived.invalidValue.exceptionValue.skus.length = 0;
}
if (knownParams.discordWebhook?.ownerID !== undefined) {
opt.discordWebhook.ownerID.length = 0;
}
if (knownParams.discordWebhook?.tradeSummary?.url !== undefined) {
opt.discordWebhook.tradeSummary.url.length = 0;
}
if (knownParams.discordWebhook?.tradeSummary?.mentionOwner?.itemSkus !== undefined) {
opt.discordWebhook.tradeSummary.mentionOwner.itemSkus.length = 0;
}
if (knownParams.discordWebhook?.declinedTrade?.url !== undefined) {
opt.discordWebhook.declinedTrade.url.length = 0;
}
if (knownParams.commands?.buy?.disableForSKU !== undefined) {
opt.commands.buy.disableForSKU.length = 0;
}
if (knownParams.commands?.sell?.disableForSKU !== undefined) {
opt.commands.sell.disableForSKU.length = 0;
}
if (knownParams.commands?.buycart?.disableForSKU !== undefined) {
opt.commands.buycart.disableForSKU.length = 0;
}
if (knownParams.commands?.sellcart?.disableForSKU !== undefined) {
opt.commands.sellcart.disableForSKU.length = 0;
}
const optionsPath = getOptionsPath(opt.steamAccountName);
const saveOptions = deepMerge({}, opt) as JsonOptions;
removeCliOptions(saveOptions);
const errors = validator(saveOptions, 'options');
if (errors !== null) {
const msg = '❌ Error updating options: ' + errors.join(', ');
if (steamID) {
this.bot.sendMessage(steamID, msg);
} else {
log.error(msg);
}
return;
}
fsp.writeFile(optionsPath, JSON.stringify(saveOptions, null, 4), { encoding: 'utf8' })
.then(() => {
deepMerge({}, saveOptions);
const msg = '✅ Updated options!';
if (steamID) {
return this.bot.sendMessage(steamID, msg);
} else {
return log.info(msg);
}
})
.catch(err => {
const errStringify = JSON.stringify(err);
const errMessage = errStringify === '' ? (err as Error)?.message : errStringify;
const msg = `❌ Error saving options file to disk: ${errMessage}`;
if (steamID) {
this.bot.sendMessage(steamID, msg);
} else {
log.error(msg);
}
return;
});
}
} | the_stack |
import { namedTypes as t, visit } from 'ast-types';
import { uniqBy } from 'lodash';
import checkIsIIFE from './checkIsIIFE';
import resolveHOC from './resolveHOC';
import resolveIIFE from './resolveIIFE';
import resolveImport from './resolveImport';
import resolveTranspiledClass from './resolveTranspiledClass';
import isStaticMethod from './isStaticMethod';
import findAssignedMethods from './findAssignedMethods';
import resolveExportDeclaration from './resolveExportDeclaration';
import makeProxy from '../utils/makeProxy';
import { get, set, has, ICache } from '../utils/cache';
import getName from '../utils/getName';
import getRoot from '../utils/getRoot';
const expressionTo = require('react-docgen/dist/utils/expressionTo');
const {
isExportsOrModuleAssignment,
isReactComponentClass,
isReactCreateClassCall,
isReactForwardRefCall,
isStatelessComponent,
normalizeClassDefinition,
resolveToValue,
getMemberValuePath,
} = require('react-docgen').utils;
function ignore() {
return false;
}
function isComponentDefinition(path: any) {
return (
isReactCreateClassCall(path) ||
isReactComponentClass(path) ||
isStatelessComponent(path) ||
isReactForwardRefCall(path)
);
}
function resolveDefinition(definition: any) {
if (isReactCreateClassCall(definition)) {
// return argument
const resolvedPath = resolveToValue(definition.get('arguments', 0));
if (t.ObjectExpression.check(resolvedPath.node)) {
return resolvedPath;
}
} else if (isReactComponentClass(definition)) {
normalizeClassDefinition(definition);
return definition;
} else if (isStatelessComponent(definition) || isReactForwardRefCall(definition)) {
return definition;
}
return null;
}
function getDefinition(definition: any, cache: ICache = {}): any {
const { __meta: exportMeta = {} } = definition;
if (checkIsIIFE(definition)) {
definition = resolveToValue(resolveIIFE(definition));
if (!isComponentDefinition(definition)) {
definition = resolveTranspiledClass(definition);
}
} else {
definition = resolveToValue(resolveHOC(definition));
if (isComponentDefinition(definition)) {
definition = makeProxy(definition, {
__meta: exportMeta,
});
return definition;
}
if (checkIsIIFE(definition)) {
definition = resolveToValue(resolveIIFE(definition));
if (!isComponentDefinition(definition)) {
definition = resolveTranspiledClass(definition);
}
} else if (t.SequenceExpression.check(definition.node)) {
const classNameNode = definition.parent.get('id').node;
const localNames: string[] = [];
let { node } = definition.get('expressions', 0);
while (t.AssignmentExpression.check(node)) {
// @ts-ignore
const { name } = node.left;
if (name) {
localNames.push(name);
}
node = node.right;
}
definition.get('expressions').each((x: any) => {
if (!x.name) return;
if (t.AssignmentExpression.check(x.node) && t.MemberExpression.check(x.node.left)) {
const objectName = x.node.left.object.name;
if (localNames.includes(objectName)) {
x.get('left', 'object').replace(classNameNode);
}
}
});
definition = getDefinition(resolveToValue(definition.get('expressions').get(0)), cache);
} else {
return resolveImport(definition, (ast: any, sourcePath: string, importMeta, mode) => {
let result;
if (has('ast-export', ast.__path)) {
result = get('ast-export', ast.__path);
} else {
result = findAllExportedComponentDefinition(ast);
set('ast-export', ast.__path, result);
}
const exportList: any[] = [];
const importList: any[] = [];
result.forEach((def: any) => {
const { __meta: meta = {} } = def;
let { exportName } = meta;
for (const item of importMeta) {
if (exportName === item.importedName) {
exportName = item.localName;
break;
}
}
if (exportName) {
importList.push(makeProxy(def, { __meta: { exportName } }));
}
const nextMeta: any = {
exportName,
};
if (exportName === exportMeta.localName) {
nextMeta.exportName = exportMeta.exportName;
} else if (mode === 'import') {
// } else {
return;
}
if (exportMeta.subName) {
nextMeta.subName = exportMeta.subName;
} else if (meta.subName) {
nextMeta.subName = meta.subName;
}
exportList.push(makeProxy(def, { __meta: nextMeta }));
});
cache[sourcePath] = importList;
// result = result.filter((x) => !x.__shouldDelete);
return exportList;
});
}
}
if (definition && (!definition.__meta || Object.keys(definition.__meta).length === 0)) {
definition.__meta = exportMeta;
}
return definition;
}
export interface IMethodsPath {
subName: string;
localName: string;
value: any;
}
/**
* Extract all flow types for the methods of a react component. Doesn't
* return any react specific lifecycle methods.
*/
function getSubComponents(path: any, scope: any, cache: ICache) {
// Extract all methods from the class or object.
let methodPaths = [];
if (isReactComponentClass(path)) {
methodPaths = path.get('body', 'body').filter(isStaticMethod);
methodPaths = [...methodPaths, ...findAssignedMethods(scope || path.scope, path.get('id'))];
} else if (t.ObjectExpression.check(path.node)) {
methodPaths = path.get('properties').filter(isStaticMethod);
methodPaths = [...methodPaths, ...findAssignedMethods(scope || path.scope, path.get('id'))];
// Add the statics object properties.
const statics = getMemberValuePath(path, 'statics');
if (statics) {
statics.get('properties').each((p: any) => {
if (isStaticMethod(p)) {
p.node.static = true;
methodPaths.push(p);
}
});
}
} else if (
t.VariableDeclarator.check(path.parent.node) &&
path.parent.node.init === path.node &&
t.Identifier.check(path.parent.node.id)
) {
methodPaths = findAssignedMethods(scope || path.parent.scope, path.parent.get('id'));
} else if (
t.AssignmentExpression.check(path.parent.node) &&
path.parent.node.right === path.node &&
t.Identifier.check(path.parent.node.left)
) {
methodPaths = findAssignedMethods(scope || path.parent.scope, path.parent.get('left'));
} else if (t.FunctionDeclaration.check(path.node)) {
methodPaths = findAssignedMethods(scope || path.parent.scope, path.get('id'));
} else if (t.ArrowFunctionExpression.check(path.node)) {
methodPaths = findAssignedMethods(scope || path.parent.scope, path.parent.get('id'));
}
return (
methodPaths
.map((x: any) => {
if (t.ClassProperty.check(x.node)) {
return {
value: x.get('value'),
subName: x.node.key.name,
localName: getName(x.get('value')),
};
}
return {
value: x,
subName: x.node.left.property.name,
localName: getName(x.get('right')),
};
})
.map(({ subName, localName, value }: IMethodsPath) => ({
subName,
localName,
value: resolveToValue(value),
}))
.map(({ subName, localName, value }: IMethodsPath) => {
let def = getDefinition(
makeProxy(value, {
__meta: {
localName,
subName,
exportName: path.__meta && path.__meta.exportName,
},
}),
cache,
);
if (!Array.isArray(def)) {
def = [def];
}
return {
subName,
localName,
value: def.flatMap((x: any) => x).filter((x: any) => isComponentDefinition(x)),
};
})
.map(({ subName, localName, value }: IMethodsPath) => {
return value.map((x: any) => ({
subName,
localName,
value: x,
}));
})
// @ts-ignore
.flatMap((x: any) => x)
.map(({ subName, value }: IMethodsPath) => {
const __meta = {
subName,
exportName: path.__meta && path.__meta.exportName,
};
return makeProxy(value, { __meta });
})
);
}
/**
* Given an AST, this function tries to find the exported component definition.
*
* The component definition is either the ObjectExpression passed to
* `React.createClass` or a `class` definition extending `React.Component` or
* having a `render()` method.
*
* If a definition is part of the following statements, it is considered to be
* exported:
*
* modules.exports = Definition;
* exports.foo = Definition;
* export default Definition;
* export var Definition = ...;
*/
export default function findAllExportedComponentDefinition(ast: any) {
const components: any[] = [];
const cache: ICache = {};
let programScope: any;
function exportDeclaration(path: any) {
const definitions = resolveExportDeclaration(path)
.reduce((acc: any[], definition: any) => {
if (isComponentDefinition(definition)) {
acc.push(definition);
} else {
definition = getDefinition(definition, cache);
if (!Array.isArray(definition)) {
definition = [definition];
}
definition.forEach((def: any) => {
if (isComponentDefinition(def)) {
acc.push(def);
}
});
}
return acc;
}, [])
.map((definition: any) => {
const { __meta: meta } = definition;
const def = resolveDefinition(definition);
return makeProxy(def, { __meta: meta });
});
if (definitions.length === 0) {
return false;
}
definitions.forEach((definition: any) => {
if (definition && components.indexOf(definition) === -1) {
components.push(definition);
}
});
return false;
}
visit(ast, {
visitProgram(path) {
programScope = path.scope;
return this.traverse(path);
},
visitFunctionDeclaration: ignore,
visitFunctionExpression: ignore,
visitClassDeclaration: ignore,
visitClassExpression: ignore,
visitIfStatement: ignore,
visitWithStatement: ignore,
visitSwitchStatement: ignore,
visitWhileStatement: ignore,
visitDoWhileStatement: ignore,
visitForStatement: ignore,
visitForInStatement: ignore,
visitForOfStatement: ignore,
visitImportDeclaration: ignore,
visitExportNamedDeclaration: exportDeclaration,
visitExportDefaultDeclaration: exportDeclaration,
visitExportAllDeclaration(path) {
components.push(...resolveImport(path, findAllExportedComponentDefinition));
return false;
},
visitAssignmentExpression(path: any) {
// Ignore anything that is not `exports.X = ...;` or
// `module.exports = ...;`
if (!isExportsOrModuleAssignment(path)) {
return false;
}
const arr = expressionTo.Array(path.get('left'));
const meta: any = {
exportName: arr[1] === 'exports' ? 'default' : arr[1],
};
// Resolve the value of the right hand side. It should resolve to a call
// expression, something like React.createClass
path = resolveToValue(path.get('right'));
if (!isComponentDefinition(path)) {
path = getDefinition(path, cache);
}
if (!Array.isArray(path)) {
path = [path];
}
const definitions = path.map(resolveDefinition);
definitions.forEach((definition: any) => {
if (definition && components.indexOf(definition) === -1) {
// if (definition.__meta) {
definition = makeProxy(definition, {
__meta: meta,
});
// }
components.push(definition);
}
});
return false;
},
});
const result = components.reduce((acc, item) => {
let subModuleDefinitions = [];
subModuleDefinitions = getSubComponents(item, programScope, cache);
return [...acc, item, ...subModuleDefinitions];
}, []);
const res = uniqBy(result, (x: any) => {
return `${getRoot(x)?.node?.__path}/${x.__meta.exportName}/${x.__meta.subName}`;
});
return res;
} | the_stack |
/// <reference types="node" />
type SteamID = import('steamid');
import { Request } from 'request';
import CMarketItem = require('./classes/CMarketItem');
import CSteamGroup = require('./classes/CSteamGroup');
import CSteamUser = require('./classes/CSteamUser');
import CMarketSearchResult = require('./classes/CMarketSearchResult');
import { Chat } from './components/chat';
import { Confirmations } from './components/confirmations';
import { Groups } from './components/groups';
import { Help } from './components/help';
import { Helpers } from './components/helpers';
import { Http } from './components/http';
import { InventoryHistory } from './components/inventoryhistory';
import { Market } from './components/market';
import { Profile } from './components/profile';
import { TwoFactor } from './components/twofactor';
import { Users } from './components/users';
import { WebApi } from './components/webapi';
interface SteamCommunity extends Chat, Confirmations, Groups, Help, Helpers, Http, InventoryHistory, Market, Profile, TwoFactor, Users, WebApi {}
declare class SteamCommunity {
constructor(options?: SteamCommunity.Options);
/**
* Invalidates your account's existing trade URL and generates a new token, which is returned in the callback.
*
* @param callback
*/
changeTradeURL(callback: (
err: SteamCommunity.CallbackError,
/** Your new full trade URL, e.g. https://steamcommunity.com/tradeoffer/new/?partner=46143802&token=xxxxxxxx. */
url: string,
/** Just the token parameter from your new trade URL. */
token: string,
) => any): void;
/**
* Clears your Steam profile name history (aliases).
* @param callback
*/
clearPersonaNameHistory(callback: SteamCommunity.Callback): any;
/**
* Retrieves a token that can be used to log on via node-steam-user.
*
* @param callback
*/
getClientLogonToken(callback: (
err: SteamCommunity.CallbackError,
details: SteamCommunity.TokenDetails,
) => any): void;
/**
* Retrieves a list of your friend relationships. Includes friends, invited friends, users who invited us to be friends, and blocked users.
*
* @param callback A function to be called when the request completes
*/
getFriendsList(callback: (
err: SteamCommunity.CallbackError,
/** An object whose keys are 64-bit SteamIDs, and values are EFriendRelationship values. */
users: any,
) => any): void;
/**
* Creates and returns a CMarketItem object for a particular item.
*
* @param appid The ID of the app to which this item belongs.
* @param hashName The item's market_hash_name.
* @param currency
* @param callback Called when the item data is loaded and ready.
*/
getMarketItem(appid: any, hashName: any, currency: any, callback: (
err: SteamCommunity.CallbackError,
/** A CMarketItem instance. */
item: CMarketItem,
) => any): void;
/**
* Gets your account's notifications (the things under the green envelope button on the top-right.
*
* @param callback Fired when the requested data is available.
*/
getNotifications(callback: (
err: SteamCommunity.CallbackError,
/** An object containing properties for each notification type. The values of each property are the number of your notifications of that type. */
notifications: SteamCommunity.Notifications,
) => any): void;
/**
* Returns the session ID of your current session, or generates a new one if you don't have a session yet. You probably won't need to use this.
*
* @param host
*/
getSessionID(host: any): any;
/**
* Creates and returns a `CSteamGroup` object for a particular group.
*
* @param id Either a `SteamID` object or a group's URL (the part after /groups/)
* @param callback
*/
getSteamGroup(id: SteamID | string, callback: (
err: SteamCommunity.CallbackError,
/** A `CSteamGroup` instance. */
group: CSteamGroup,
) => any): void;
/**
* Creates and returns a CSteamUser object for a particular user.
*
* @param id Either a SteamID object or a user's URL (the part after /id/).
* @param callback
*/
getSteamUser(id: SteamID | string, callback: (
err: SteamCommunity.CallbackError,
/** A `CSteamUser` instance. */
group: CSteamUser,
) => any): void;
/**
* Gets your account's trade URL, which can be used by people who aren't your friends on Steam to send you trade offers.
*
* @param callback A callback to be invoked on completion.
*/
getTradeURL(callback: (
err: SteamCommunity.CallbackError,
/** Your full trade URL, e.g. https://steamcommunity.com/tradeoffer/new/?partner=46143802&token=xxxxxxxx. */
url: string,
/** Just the token parameter from your trade URL. */
token: string,
) => any): void;
/**
* Use this method to check whether or not you're currently logged into Steam and what your Family View status is.
*
* @param callback Called when the result is available.
*/
loggedIn(callback: (
err: SteamCommunity.CallbackError,
/** `true` if you're currently logged in, `false` otherwise. */
loggedIn: boolean,
/** `true` if you're currently in family view, `false` otherwise. If `true`, you'll need to call parentalUnlock with the correct PIN before you can do anything.. */
familyView: boolean,
) => any): void;
/**
* @param details An object containing our login details.
* @param callback A function which will be called once we're logged in.
*/
login(details: SteamCommunity.LoginOptions, callback: (
err: SteamCommunity.CallbackError,
/** Your session ID value. If you're using an external library, it'll know what to do with this. Otherwise, you can ignore it. */
sessionID: string,
/** An array containing your cookies. If you're using an external library, you'll need these. Otherwise, you can ignore them. */
cookies: [],
/**
* If your account is protected by Steam Guard, this is a string which can be passed to login as the steamguard property of details.
* You should treat it as an opaque string, but currently it's YourSteamID||YourCookieValue.
* You can pull YourCookieValue from the value of the steamMachineAuthYourSteamID cookie on an authorized browser if you wish.
*/
steamguard: string,
/** An oAuth token. You can use this value along with the steamguard value with oAuthLogin for subsequent passwordless logins.. */
oAuthToken: string,
) => any): any;
/**
* Searches the market for a particular query. If you provide an appid to options, you can also search for tags.
* Simply add your search tags with the tag's name being the key and the tag's internal value being the value.
*
* @param options Provide a string to just search for that string, otherwise an object.
* @param callback Called when results are available.
*/
marketSearch(options: string | {
/** The query string to search for. */
query: string,
/** The AppID of the game you're searching for. */
appid: SteamCommunity.appid,
/** `true` to also search in the descriptions of items (takes longer to search), `false` or omitted otherwise. */
searchDescriptions: boolean,
}, callback: (
/**
* If an error occurred, this will be an Error object.
* If the item is not on the market or doesn't exist, the message property will be "There were no items matching your search. Try again with different keywords."
*/
err: SteamCommunity.CallbackError,
/** An array of `CMarketSearchResult` instances. */
items: CMarketSearchResult[],
) => any): void;
/**
* Facilitates passwordless login using details received from a previous login request.
*
* @param steamguard The steamguard value from the callback of login.
* @param token The oAuthToken value from the callback of login.
* @param callback Called when the login request completes
*/
oAuthLogin(steamguard: string, token: string, callback: (
/** If an error occurred, this is an Error object. Otherwise, null. */
err: SteamCommunity.CallbackError,
/** true if you're currently logged in, false otherwise. */
loggedIn: boolean,
/** true if you're currently in family view, false otherwise. If true, you'll need to call parentalUnlock with the correct PIN before you can do anything. */
familyView: boolean,
) => any): void;
/**
* If your account has Family View enabled, calling this will disable it for your current session.
*
* @param pin Your 4-digit Family View PIN.
* @param callback An optional callback to be invoked on completion.
*/
parentalUnlock(pin: number, callback: SteamCommunity.Callback): void;
/**
* Loads your inventory page, which resets your new items notification to 0.
*
* @param callback An optional callback to be invoked on completion.
*/
resetItemNotifications(callback?: SteamCommunity.Callback): void;
/**
* Use this to resume a previous session or to use a session that was negotiated elsewhere (using node-steam-user, for instance).
*
* @param cookies An array of cookies (as name=value pair strings).
*/
setCookies(cookies: string[]): void;
steamID: SteamID;
}
declare namespace SteamCommunity {
interface Options {
/**
* An instance of {@link https://www.npmjs.com/package/request|request} v2.x.x which will be used by `SteamCommunity` for its HTTP requests.
* SteamCommunity` will create its own if omitted.
*/
request: Request;
/**
* The time in milliseconds that `SteamCommunity` will wait for HTTP requests to complete.
* Defaults to `50000` (50 seconds). Overrides any `timeout` option that was set on the passed-in `request` object.
*/
timeout: number;
/**
* The user-agent value that `SteamCommunity` will use for its HTTP requests. Defaults to Chrome v47's user-agent.
* Overrides any `headers['User-Agent']` option that was set on the passed-in `request` object.
*/
userAgent: string;
/** The local IP address that `SteamCommunity` will use for its HTTP requests. Overrides an `localAddress` option that was set on the passed-in `request` object. */
localAddress: string;
}
interface TokenDetails {
/** Your account's SteamID, as a SteamID object. */
steamID: SteamID;
/** Your account's logon name. */
accountName: any;
/** Your logon token. */
webLogonToken: any;
}
interface Notifications {
comments: number;
items: number;
invites: number;
gifts: number;
chat: number;
trades: number;
gameTurns: number;
moderatorMessages: number;
helpRequestReplies: number;
accountAlerts: number;
}
interface LoginOptions {
/** Your Steam account name. */
accountName: string;
/** Your Steam password. */
password: string;
/** Your Steam Guard value (only required if logging in with a Steam Guard authorization). */
steamguard?: string;
/** Your Steam Guard email code (only required if logging in with a new email auth code). */
authCode?: string;
/** Your Steam Guard app code (only required if logging in with a Steam Guard app code). */
twoFactorCode?: string;
/** Value of prompted captcha (only required if you have been prompted with a CAPTCHA). */
captcha?: string;
/** Pass `true` here to have node-steamcommunity not use the mobile login flow. This might help keep your login session alive longer, but you won't get an oAuth token in the login response. */
disableMobile?: boolean;
}
interface EditProfileSettings {
/** Your new profile name. */
name: any;
/** Your new profile "real name", or empty string to remove it. */
realName: any;
/** Your new profile summary. */
summary: any;
/** A country code, like US, or empty string to remove it. */
country: string;
/** A state code, like FL, or empty string to remove it. */
state: string;
/** A numeric city code, or empty string to remove it. */
city: number | string;
/** Your new profile custom URL. */
customURL: any;
/** The assetid of an owned profile background which you want to equip, or empty string to remove it. */
background: any;
/** The ID of your new featured badge, or empty string to remove it. Currently game badges aren't supported, only badges whose pages end in /badge/<id>. */
featuredBadge: any;
/** A SteamID object for your new primary Steam group, or a string which can parse into a SteamID. */
primaryGroup: SteamID | string;
}
interface ProfileSetting {
/** A value from SteamCommunity.PrivacyState for your desired profile privacy state. */
profile: any;
/** A value from SteamCommunity.PrivacyState for your desired profile comments privacy state. */
comments: any;
/** A value from SteamCommunity.PrivacyState for your desired inventory privacy state. */
inventory: any;
/** true to keep your Steam gift inventory private, false otherwise. */
inventoryGifts: any;
/** A value from SteamCommunity.PrivacyState for your desired privacy level required to view games you own and what game you're currently playing. */
gameDetails: any;
/** `true` to keep your game playtime private, `false` otherwise. */
playtime: boolean;
/** A value from SteamCommunity.PrivacyState for your desired privacy level required to view your friends list. */
friendsList: any;
}
interface GroupItemHistory {
/** A string containing the item history type. This is the type displayed on the history page, without spaces. For example, NewMember, InviteSent, etc.. */
'type': string;
/** A Date object containing the date and time when this action took place. Since the history page doesn't display any years, the year could possibly be incorrect.. */
date: Date;
/**
* A SteamID object containing the SteamID of the user who either performed or received this action.
* For example, on NewMember this is the new group member, on InviteSent this is the invite recipient, on NewAnnouncement, this is the author.
*/
user: SteamID;
/** Not present on all history types. This is the user who performed the action if user is the receipient of the action. */
actor: any;
}
interface GroupHistory {
/** The index of the first history item on this page, starting at 1. */
first: number;
/** The index of the last history item on this page. */
last: number;
/** How many total history items there are. */
total: number;
/** An array of group history objects. */
items: GroupItemHistory[];
}
interface GroupComment {
/** The comment author's persona name. */
authorName: string;
/** Either the comment author's 64-bit Steam ID, or their vanity URL. */
authorId: string;
/** A Date object of when this comment was submitted. */
date: Date;
/** The ID of this comment. */
commentId: string;
/** The HTML content of this comment. */
text: string;
}
interface UserComment {
/** The ID of the comment. */
id: any;
author: {
/** A SteamID object. */
steamID: SteamID;
/** The commenter's name. */
name: any;
/** A URL to the commenter's avatar. */
avatar: string;
/** offline/online/in-game. */
state: 'offline' | 'online' | 'in-game'
};
/** A Date object. */
date: Date;
/** The text of the comment. May contain special characters like newlines or tabs. */
text: any;
/** The rendered HTML of the comment. */
html: any;
}
interface Announcement {
/** The announcement's title. */
headline: string;
/** The content of the announcement. */
content: string;
/** A Date object for when this was posted. */
date: Date;
/** The Steam profile name of the author. */
author: string;
/** The ID of the announcement. */
aid: string;
}
type GroupEventType =
| 'ChatEvent'
| 'OtherEvent'
| 'PartyEvent'
| 'MeetingEvent'
| 'SpecialCauseEvent'
| 'MusicAndArtsEvent'
| 'SportsEvent'
| 'TripEvent';
/**
* @param err `null` on success, an `Error` object on failure.
*/
type Callback = (err: CallbackError) => any;
/** `null` on success, an `Error` object on failure. */
type CallbackError = Error & { [key: string]: any } | null;
/** Unique and can change after a trade. */
type assetid = number | string;
type userid = SteamID | string;
type appid = number;
/** 2 for csgo... */
type contextid = number;
/**
* In a nutshell, a classid "owns" an instanceid. The classid is all you need to get a general overview of an item.
* For example, items with the same classid will pretty much always have the same name and image.
*/
type classid = number;
/** An ID that describes an item instance that inherits properties from a class with the class id being noted in the instance (totally not unique). */
type instanceid = number;
type packageid = number | string;
type cid = number | string;
type gid = SteamID | string;
// region Static enums
enum PrivacyState {
'Private' = 1,
'FriendsOnly' = 2,
'Public' = 3
}
/** The current state of our chat connection. One of the following values. */
enum ChatState {
'Offline' = 0,
'LoggingOn' = 1,
'LogOnFailed' = 2,
'LoggedOn' = 3
}
/**
* 1 is unknown, possibly "Invalid".
* 4 is opt-out or other like account confirmation?
*/
enum ConfirmationType {
'Trade' = 2,
'MarketListing' = 3,
}
enum EFriendRelationship {
'None' = 0,
'Blocked' = 1,
'RequestRecipient' = 2,
'Friend' = 3,
'RequestInitiator' = 4,
'Ignored' = 5,
'IgnoredFriend' = 6,
'SuggestedFriend' = 7, // removed "was used by the original implementation of the facebook linking feature; but now unused."
}
enum PersonaState {
'Offline' = 0,
'Online' = 1,
'Busy' = 2,
'Away' = 3,
'Snooze' = 4,
'LookingToTrade' = 5,
'LookingToPlay' = 6,
'Invisible' = 7
}
enum PersonaStateFlag {
'HasRichPresence' = 1,
'InJoinableGame' = 2,
'Golden' = 4,
'RemotePlayTogether' = 8,
'OnlineUsingWeb' = 256,
'ClientTypeWeb' = 256,
'OnlineUsingMobile' = 512,
'ClientTypeMobile' = 512,
'OnlineUsingBigPicture' = 1024,
'ClientTypeTenfoot' = 1024,
'OnlineUsingVR' = 2048,
'ClientTypeVR' = 2048,
'LaunchTypeGamepad' = 4096,
'LaunchTypeCompatTool' = 8192
}
enum EResult {
'Invalid' = 0,
'OK' = 1,
'Fail' = 2,
'NoConnection' = 3,
'InvalidPassword' = 5,
'LoggedInElsewhere' = 6,
'InvalidProtocolVer' = 7,
'InvalidParam' = 8,
'FileNotFound' = 9,
'Busy' = 10,
'InvalidState' = 11,
'InvalidName' = 12,
'InvalidEmail' = 13,
'DuplicateName' = 14,
'AccessDenied' = 15,
'Timeout' = 16,
'Banned' = 17,
'AccountNotFound' = 18,
'InvalidSteamID' = 19,
'ServiceUnavailable' = 20,
'NotLoggedOn' = 21,
'Pending' = 22,
'EncryptionFailure' = 23,
'InsufficientPrivilege' = 24,
'LimitExceeded' = 25,
'Revoked' = 26,
'Expired' = 27,
'AlreadyRedeemed' = 28,
'DuplicateRequest' = 29,
'AlreadyOwned' = 30,
'IPNotFound' = 31,
'PersistFailed' = 32,
'LockingFailed' = 33,
'LogonSessionReplaced' = 34,
'ConnectFailed' = 35,
'HandshakeFailed' = 36,
'IOFailure' = 37,
'RemoteDisconnect' = 38,
'ShoppingCartNotFound' = 39,
'Blocked' = 40,
'Ignored' = 41,
'NoMatch' = 42,
'AccountDisabled' = 43,
'ServiceReadOnly' = 44,
'AccountNotFeatured' = 45,
'AdministratorOK' = 46,
'ContentVersion' = 47,
'TryAnotherCM' = 48,
'PasswordRequiredToKickSession' = 49,
'AlreadyLoggedInElsewhere' = 50,
'Suspended' = 51,
'Cancelled' = 52,
'DataCorruption' = 53,
'DiskFull' = 54,
'RemoteCallFailed' = 55,
'PasswordNotSet' = 56, // removed "renamed to PasswordUnset
'PasswordUnset' = 56,
'ExternalAccountUnlinked' = 57,
'PSNTicketInvalid' = 58,
'ExternalAccountAlreadyLinked' = 59,
'RemoteFileConflict' = 60,
'IllegalPassword' = 61,
'SameAsPreviousValue' = 62,
'AccountLogonDenied' = 63,
'CannotUseOldPassword' = 64,
'InvalidLoginAuthCode' = 65,
'AccountLogonDeniedNoMailSent' = 66, // removed "renamed to AccountLogonDeniedNoMail
'AccountLogonDeniedNoMail' = 66,
'HardwareNotCapableOfIPT' = 67,
'IPTInitError' = 68,
'ParentalControlRestricted' = 69,
'FacebookQueryError' = 70,
'ExpiredLoginAuthCode' = 71,
'IPLoginRestrictionFailed' = 72,
'AccountLocked' = 73, // removed "renamed to AccountLockedDown
'AccountLockedDown' = 73,
'AccountLogonDeniedVerifiedEmailRequired' = 74,
'NoMatchingURL' = 75,
'BadResponse' = 76,
'RequirePasswordReEntry' = 77,
'ValueOutOfRange' = 78,
'UnexpectedError' = 79,
'Disabled' = 80,
'InvalidCEGSubmission' = 81,
'RestrictedDevice' = 82,
'RegionLocked' = 83,
'RateLimitExceeded' = 84,
'AccountLogonDeniedNeedTwoFactorCode' = 85, // removed "renamed to AccountLoginDeniedNeedTwoFactor
'AccountLoginDeniedNeedTwoFactor' = 85,
'ItemOrEntryHasBeenDeleted' = 86, // removed "renamed to ItemDeleted
'ItemDeleted' = 86,
'AccountLoginDeniedThrottle' = 87,
'TwoFactorCodeMismatch' = 88,
'TwoFactorActivationCodeMismatch' = 89,
'AccountAssociatedToMultiplePlayers' = 90, // removed "renamed to AccountAssociatedToMultiplePartners
'AccountAssociatedToMultiplePartners' = 90,
'NotModified' = 91,
'NoMobileDeviceAvailable' = 92, // removed "renamed to NoMobileDevice
'NoMobileDevice' = 92,
'TimeIsOutOfSync' = 93, // removed "renamed to TimeNotSynced
'TimeNotSynced' = 93,
'SMSCodeFailed' = 94,
'TooManyAccountsAccessThisResource' = 95, // removed "renamed to AccountLimitExceeded
'AccountLimitExceeded' = 95,
'AccountActivityLimitExceeded' = 96,
'PhoneActivityLimitExceeded' = 97,
'RefundToWallet' = 98,
'EmailSendFailure' = 99,
'NotSettled' = 100,
'NeedCaptcha' = 101,
'GSLTDenied' = 102,
'GSOwnerDenied' = 103,
'InvalidItemType' = 104,
'IPBanned' = 105,
'GSLTExpired' = 106,
'InsufficientFunds' = 107,
'TooManyPending' = 108,
'NoSiteLicensesFound' = 109,
'WGNetworkSendExceeded' = 110,
'AccountNotFriends' = 111,
'LimitedUserAccount' = 112,
'CantRemoveItem' = 113,
'AccountHasBeenDeleted' = 114,
'AccountHasAnExistingUserCancelledLicense' = 115,
'DeniedDueToCommunityCooldown' = 116,
'NoLauncherSpecified' = 117,
'MustAgreeToSSA' = 118,
'ClientNoLongerSupported' = 119
}
// endregion Enums
}
export = SteamCommunity; | the_stack |
import * as React from "react";
import { useSpring, animated, config } from "react-spring";
import { usePrevious } from "./use-previous";
import { useGestureResponder, StateType } from "react-gesture-responder";
import useScrollLock from "use-scroll-lock";
interface PositionType {
x: number;
y: number;
w: number;
h: number;
}
export interface ImageEnlargerProps extends React.HTMLAttributes<any> {
zoomed: boolean;
onClick: () => void;
enlargedSrc?: string;
overlayColor?: string;
renderLoading?: React.ReactNode;
onRequestClose: () => void;
src: string;
}
const initialTransform = "translateX(0px) translateY(0px) scale(1)";
const getScale = linearConversion([0, 400], [1, 0.4]);
const scaleClamp = clamp(0.4, 1);
/**
* Image component
* @param param0
*/
const ImageEnlarger: React.FunctionComponent<ImageEnlargerProps> = ({
zoomed = false,
renderLoading,
overlayColor = "rgba(255,255,255,0.8)",
enlargedSrc,
onRequestClose,
style = {},
src,
...other
}) => {
const ref = React.useRef<HTMLImageElement>(null);
const prevZoom = usePrevious(zoomed);
const [animating, setAnimating] = React.useState(false);
const cloneRef = React.useRef<any>(null);
const [cloneLoaded, setCloneLoaded] = React.useState(false);
const prevCloneLoaded = usePrevious(cloneLoaded);
const [hasRequestedZoom, setHasRequestedZoom] = React.useState(zoomed);
// this allows us to lazily load our cloned image
React.useEffect(() => {
if (!hasRequestedZoom && zoomed) {
setHasRequestedZoom(true);
}
}, [hasRequestedZoom, zoomed]);
// disable scrolling while zooming is taking place
useScrollLock(zoomed || animating);
/**
* We basically only use this to imperatively set the
* visibility of the thumbnail
*/
const [thumbProps, setThumbProps] = useSpring(() => ({
opacity: 1,
immediate: true
}));
// set overlay opacity
const [overlay, setOverlay] = useSpring(() => ({
opacity: zoomed ? 1 : 0
}));
// our cloned image spring
const [props, set] = useSpring(() => ({
opacity: 0,
transform: initialTransform,
left: 0,
top: 0,
width: 0,
height: 0,
immediate: true,
config: config.stiff
}));
/**
* Handle drag movement
*/
function onMove({ delta }: StateType) {
const scale = scaleClamp(getScale(Math.abs(delta[1])));
// we use this to alter the y-position to ensure the image
// scales under our cursor / pointer
const diffHeight = ((1 - scale) * cloneRef.current!.height) / 2;
const ty = delta[1] - diffHeight * (delta[1] > 0 ? 1 : -1);
set({
transform: `translateX(${delta[0] *
0.8}px) translateY(${ty}px) scale(${scale})`,
immediate: true
});
setOverlay({ opacity: scale, immediate: true });
}
/**
* Handle release - we almost always close
* @param param0
*/
function onEnd({ delta }: StateType) {
if (Math.abs(delta[1]) > 20 && onRequestClose) {
onRequestClose();
} else {
// reset
set({ transform: initialTransform, immediate: false });
setOverlay({ opacity: 1, immediate: false });
}
}
// our gesture binding helper
const { bind } = useGestureResponder({
onStartShouldSet: () => false,
onMoveShouldSet: () => {
if (!zoomed) {
return false;
}
return true;
},
onMove: onMove,
onRelease: onEnd,
onTerminate: onEnd
});
/**
* Basic logic for determining positions. A bit of a mess tbh,
* but that often comes when mixing imperative logic w/
* react's declarative nature.
*/
const generatePositions = React.useCallback(
(immediate: boolean = false) => {
// any time this prop changes, we update our position
if (ref.current && cloneLoaded) {
const rect = ref.current.getBoundingClientRect();
const cloneSize = {
width: cloneRef.current!.naturalWidth,
height: cloneRef.current!.naturalHeight
};
const thumbDimensions = {
x: rect.left,
y: rect.top,
w: rect.width,
h: rect.height
};
const clonedDimensions = getTargetDimensions(
cloneSize.width,
cloneSize.height
);
const initialSize = getInitialClonedDimensions(
thumbDimensions,
clonedDimensions
);
const zoomingIn =
(!prevZoom && zoomed) || (!prevCloneLoaded && cloneLoaded);
const zoomingOut = prevZoom && !zoomed;
// handle zooming in
if (zoomingIn && !immediate) {
setThumbProps({ opacity: 0, immediate: true });
set({
opacity: 1,
immediate: true,
transform: `translateX(${initialSize.translateX}px) translateY(${
initialSize.translateY
}px) scale(${initialSize.scale})`,
left: clonedDimensions.x,
top: clonedDimensions.y,
width: clonedDimensions.w,
height: clonedDimensions.h,
onRest: () => {}
});
set({
transform: initialTransform,
immediate: false
});
// handle zooming out
} else if (zoomingOut) {
setAnimating(true);
set({
transform: `translateX(${initialSize.translateX}px) translateY(${
initialSize.translateY
}px) scale(${initialSize.scale})`,
immediate: false,
onRest: () => {
setThumbProps({ opacity: 1, immediate: true });
set({ opacity: 0, immediate: true });
setAnimating(false);
}
});
// handle resizing
} else if (immediate) {
set({
immediate: true,
transform: initialTransform,
left: clonedDimensions.x,
top: clonedDimensions.y,
width: clonedDimensions.w,
height: clonedDimensions.h,
onRest: () => {}
});
}
setOverlay({ opacity: zoomed ? 1 : 0 });
}
},
[
zoomed,
cloneLoaded,
ref,
cloneRef,
prevCloneLoaded,
hasRequestedZoom,
prevZoom
]
);
// we need to update our fixed positioning when resizing
// this should probably be debounced
const onResize = React.useCallback(() => {
generatePositions(true);
}, [zoomed, cloneLoaded, ref, prevCloneLoaded, prevZoom]);
// update our various positions
React.useEffect(() => {
generatePositions();
if (zoomed) window.addEventListener("resize", onResize);
return () => {
window.removeEventListener("resize", onResize);
};
}, [zoomed, cloneLoaded, ref, prevCloneLoaded, prevZoom]);
return (
<React.Fragment>
<div className="EnlargedImage">
<div
className="EnlargedImage__container"
style={{ position: "relative", display: "inline-block" }}
>
<animated.img
className="EnlargedImage__Image"
src={src}
style={{
cursor: "zoom-in",
maxWidth: "100%",
height: "auto",
opacity: thumbProps.opacity,
...style
}}
ref={ref}
{...other}
/>
{!cloneLoaded && zoomed && renderLoading}
</div>
</div>
{hasRequestedZoom && (
<div
className="EnlargedImage__enlarged-container"
{...bind}
aria-hidden={!zoomed}
onClick={onRequestClose}
style={{
pointerEvents: zoomed ? "auto" : "none",
position: "fixed",
top: 0,
left: 0,
bottom: 0,
right: 0,
zIndex: 90,
cursor: "zoom-out"
}}
>
<animated.div
className="EnlargedImage__overlay"
style={{
opacity: overlay.opacity,
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: overlayColor
}}
/>
<animated.img
className="EnlargedImage__clone"
onLoad={() => {
setCloneLoaded(true);
}}
style={{
pointerEvents: "none",
zIndex: 100,
position: "absolute",
opacity: props.opacity,
transform: props.transform,
left: props.left,
top: props.top,
width: props.width,
height: props.height
}}
ref={cloneRef}
src={enlargedSrc || src}
/>
</div>
)}
</React.Fragment>
);
};
/**
* Get the original dimensions of the clone so that it appears
* in the same place as the original image
* @param o origin
* @param t target
*/
function getInitialClonedDimensions(o: PositionType, t: PositionType) {
const scale = o.w / t.w;
const translateX = o.x + o.w / 2 - (t.x + t.w / 2);
const translateY = o.y + o.h / 2 - (t.y + t.h / 2);
return {
scale,
translateX,
translateY
};
}
/**
* Get the target dimensions / position of the image when
* it's zoomed in
*
* @param iw (image width)
* @param ih (image height)
* @param padding
*/
function getTargetDimensions(iw: number, ih: number, padding = 0) {
const vp = getViewport();
const target = scaleToBounds(iw, ih, vp.width - padding, vp.height - padding);
const left = vp.width / 2 - target.width / 2;
const top = vp.height / 2 - target.height / 2;
return {
x: left,
y: top,
w: target.width,
h: target.height
};
}
/**
* Scale numbers to bounds given max dimensions while
* maintaining the original aspect ratio
*
* @param ow
* @param oh
* @param mw
* @param mh
*/
function scaleToBounds(ow: number, oh: number, mw: number, mh: number) {
let scale = Math.min(mw / ow, mh / oh);
if (scale > 1) scale = 1;
return {
width: ow * scale,
height: oh * scale
};
}
/**
* Server-safe measurement of the viewport size
*/
function getViewport() {
if (typeof window !== "undefined") {
return { width: window.innerWidth, height: window.innerHeight };
}
return { width: 0, height: 0 };
}
/**
* Create a basic linear conversion fn
*/
function linearConversion(a: [number, number], b: [number, number]) {
const o = a[1] - a[0];
const n = b[1] - b[0];
return function(x: number) {
return ((x - a[0]) * n) / o + b[0];
};
}
/**
* Create a clamp
* @param max
* @param min
*/
function clamp(min: number, max: number) {
return function(x: number) {
if (x > max) return max;
if (x < min) return min;
return x;
};
}
export default ImageEnlarger; | the_stack |
let eventSynthesizerFunction:(uievent:UIEvent)=>void;
function getEventSynthesizier() {
if (eventSynthesizerFunction) return eventSynthesizerFunction;
let currentMouseTarget:Element|Window|undefined;
const fireMouseLeaveEvents = (target:Element|Window|undefined, relatedTarget:Element|Window|undefined, uievent:MouseEvent) => {
if (!target) return;
const eventInit:MouseEventInit = {
view: uievent.view,
clientX: uievent.clientX,
clientY: uievent.clientY,
screenX: uievent.screenX,
screenY: uievent.screenY,
relatedTarget: relatedTarget
};
// fire mouseout
eventInit.bubbles = true;
target.dispatchEvent(new MouseEvent('mouseout',eventInit));
// fire mouseleave events
eventInit.bubbles = false;
let el = target;
do {
el.dispatchEvent(new MouseEvent('mouseleave',eventInit));
el = el['parentElement'];
} while (el)
}
const fireMouseEnterEvents = (target:Element|Window, relatedTarget:Element|Window|undefined, uievent:MouseEvent) => {
const eventInit:MouseEventInit = {
view: uievent.view,
clientX: uievent.clientX,
clientY: uievent.clientY,
screenX: uievent.screenX,
screenY: uievent.screenY,
relatedTarget: relatedTarget
};
// fire mouseover
eventInit.bubbles = true;
target.dispatchEvent(new MouseEvent('mouseover',eventInit));
// fire mouseenter events
eventInit.bubbles = false;
let el = target;
do {
el.dispatchEvent(new MouseEvent('mouseenter',eventInit));
el = el['parentElement'];
} while (el)
}
const firePointerEnterEvents = (target:Element|Window, relatedTarget:any, uievent:PointerEvent) => {
const bubbles = uievent.bubbles;
// fire pointerover event
(<any>uievent).bubbles = true;
target.dispatchEvent(new PointerEvent('pointerover',uievent));
// fire pointerenter events
(<any>uievent).bubbles = false;
let el = target;
do {
el.dispatchEvent(new PointerEvent('pointerenter',uievent));
el = el['parentElement'];
} while (el)
(<any>uievent).bubbles = bubbles;
}
const firePointerLeaveEvents = (target:Element|Window|undefined, relatedTarget:any, uievent:PointerEvent) => {
if (!target) return;
// fire pointerover event
(<any>uievent).bubbles = true;
target.dispatchEvent(new PointerEvent('pointerout',uievent));
// fire pointerenter events
(<any>uievent).bubbles = false;
let el = target;
do {
el.dispatchEvent(new PointerEvent('pointerleave',uievent));
el = el['parentElement'];
} while (el)
}
const deserializeTouches = (touches:Touch[], target:Element|Window, uievent:TouchEvent) => {
touches.forEach((t, i)=>{
if (document.createTouch) {
touches[i] = document.createTouch(
uievent.view, target, t.identifier,
t.clientX, t.clientY, t.screenX, t.screenY
);
} else if (typeof Touch !== undefined) {
(<any>t).target = target;
touches[i] = new (<any>Touch)(t);
}
})
return touches;
}
const touchTargets = {};
const touchStartTimes = {};
const pointerTargets = {};
const capturedPointerTargets = {};
document.documentElement.addEventListener('gotpointercapture', (e)=>{
capturedPointerTargets[e.pointerId] = e.target;
})
document.documentElement.addEventListener('lostpointercapture', (e)=>{
delete capturedPointerTargets[e.pointerId];
})
Element.prototype.setPointerCapture = function (id) { capturedPointerTargets[id] = this; };
Element.prototype.releasePointerCapture = function (id) { capturedPointerTargets[id] = null; };
return eventSynthesizerFunction = (uievent:MouseEvent&WheelEvent&TouchEvent&PointerEvent)=>{
(<any>uievent).view = window;
let target : Element;
switch (uievent.type) {
case 'wheel':
target = document.elementFromPoint(uievent.clientX, uievent.clientY) || window;
target.dispatchEvent(new WheelEvent(uievent.type, uievent));
break;
case 'mouseleave':
target = document.elementFromPoint(uievent.clientX, uievent.clientY) || window;
fireMouseLeaveEvents(currentMouseTarget, undefined, uievent);
currentMouseTarget = undefined;
break;
case 'mouseenter':
target = document.elementFromPoint(uievent.clientX, uievent.clientY) || window;
fireMouseEnterEvents(target, undefined, uievent);
currentMouseTarget = target;
break;
case 'mousemove':
target = document.elementFromPoint(uievent.clientX, uievent.clientY) || window;
if (target !== currentMouseTarget) {
fireMouseLeaveEvents(currentMouseTarget, target, uievent);
fireMouseEnterEvents(target, currentMouseTarget, uievent);
currentMouseTarget = target;
}
target.dispatchEvent(new MouseEvent(uievent.type, uievent));
break;
case 'touchstart':
const primaryTouch = uievent.changedTouches[0];
target = document.elementFromPoint(primaryTouch.clientX, primaryTouch.clientY) || window;
for (const t of (<Touch[]><any>uievent.changedTouches)) {
touchTargets[t.identifier] = target;
touchStartTimes[t.identifier] = performance.now();
}
case 'touchmove':
case 'touchend':
case 'touchcancel':
target = touchTargets[uievent.changedTouches[0].identifier];
var evt = document.createEvent('TouchEvent');
let touches = deserializeTouches(<any>uievent.touches, target, uievent);
let targetTouches = deserializeTouches(<any>uievent.targetTouches, target, uievent);
let changedTouches = deserializeTouches(<any>uievent.changedTouches, target, uievent);
if (document.createTouchList) {
touches = document.createTouchList.apply(document, touches);
targetTouches = document.createTouchList.apply(document, targetTouches);
changedTouches = document.createTouchList.apply(document, changedTouches);
}
// Safari, Firefox: must use initTouchEvent.
if (typeof evt['initTouchEvent'] === "function") {
evt['initTouchEvent'](
uievent.type, uievent.bubbles, uievent.cancelable, uievent.view, uievent.detail,
uievent.screenX, uievent.screenY, uievent.clientX, uievent.clientY,
uievent.ctrlKey, uievent.altKey, uievent.shiftKey, uievent.metaKey,
touches, targetTouches, changedTouches, 1.0, 0.0
);
} else if ('TouchEvent' in window && TouchEvent.length > 0) {
// Chrome: must use TouchEvent constructor.
evt = new (<any>TouchEvent)(uievent.type, {
cancelable: uievent.cancelable,
bubbles: uievent.bubbles,
touches: touches,
targetTouches: targetTouches,
changedTouches: changedTouches
});
} else {
evt.initUIEvent(uievent.type, uievent.bubbles, uievent.cancelable, uievent.view, uievent.detail);
(<any>evt).touches = touches;
(<any>evt).targetTouches = targetTouches;
(<any>evt).changedTouches = changedTouches;
}
if (uievent.type === 'touchend' || uievent.type == 'touchcancel') {
target.dispatchEvent(evt);
const primaryTouch = changedTouches[0];
(<any>uievent).clientX = primaryTouch.clientX;
(<any>uievent).clientY = primaryTouch.clientY;
(<any>uievent).screenX = primaryTouch.screenX;
(<any>uievent).screenY = primaryTouch.screenY;
(<any>uievent).button = 0;
(<any>uievent).detail = 1;
if (uievent.type === 'touchend') {
if (performance.now() - touchStartTimes[primaryTouch.identifier] < 300 && !evt.defaultPrevented) {
target.dispatchEvent(new MouseEvent('mousedown', uievent))
target.dispatchEvent(new MouseEvent('mouseup', uievent))
target.dispatchEvent(new MouseEvent('click', uievent))
}
} else {
target.dispatchEvent(new MouseEvent('mouseout', uievent))
}
for (const t of (<Touch[]><any>uievent.changedTouches)) {
delete touchTargets[t.identifier];
delete touchStartTimes[t.identifier];
}
} else {
target.dispatchEvent(evt);
}
break;
case 'pointerenter':
case 'pointerleave':
case 'pointermove':
case 'pointercancel':
case 'pointerdown':
case 'pointerup':
const previousTarget = pointerTargets[uievent.pointerId];
const capturedTarget = target = capturedPointerTargets[uievent.pointerId];
const isLeaving = uievent.type === 'pointerleave' || uievent.type === 'pointercancel';
const pointerEvent = new PointerEvent(uievent.type, uievent);
if (capturedTarget) {
capturedTarget.dispatchEvent(pointerEvent);
} else {
target = document.elementFromPoint(uievent.clientX, uievent.clientY) || window;
if (target !== previousTarget) {
firePointerLeaveEvents(previousTarget, target, uievent);
if (!isLeaving) firePointerEnterEvents(target, previousTarget, uievent);
}
target.dispatchEvent(pointerEvent);
}
if (isLeaving) {
delete pointerTargets[uievent.pointerId];
} else {
pointerTargets[uievent.pointerId] = target;
}
break;
default:
target = document.elementFromPoint(uievent.clientX, uievent.clientY) || window;
target.dispatchEvent(new MouseEvent(uievent.type, uievent));
}
};
}
export default (typeof document !== 'undefined' && document.createElement) ?
getEventSynthesizier : ()=>{ return undefined; }; | the_stack |
import path from 'path'
import { Host } from './Host'
import { PostHogTracker } from '../PostHogTracker'
import { Auth } from './Auth'
import { MutagenManager, MutagenExecutable, MutagenDaemon } from '../mutagen'
import { dataPath, resourcePath } from '../resources'
import { Status } from './Status'
import { dialog, BrowserWindow, shell, app } from 'electron'
import { Logger } from '../Logger'
import { File } from '../config'
import { AppIPC, MutagenIPC, sharedAppIpc, sharedMutagenIpc } from '../ipc'
import { TypedEventEmitter } from '../TypedEventEmitter'
import ElectronWindowState from 'electron-window-state'
interface ApplicationEvents {
openPreferences: []
}
export class Application extends TypedEventEmitter<ApplicationEvents> {
readonly #host: Host
readonly #auth: Auth
readonly #protocol: string
readonly #mutagenManager: MutagenManager
readonly #postHogTracker: PostHogTracker
readonly #status: Status
readonly #logger: Logger
#window?: BrowserWindow
#lastURL?: URL
private constructor(
host: Host,
auth: Auth,
protocol: string,
mutagenManager: MutagenManager,
postHogTracker: PostHogTracker,
status: Status,
logger: Logger
) {
super()
this.#host = host
this.#auth = auth
this.#protocol = protocol
this.#postHogTracker = postHogTracker
this.#mutagenManager = mutagenManager
this.#status = status
this.#logger = logger
}
static async start({
host,
mutagenExecutable,
postHogToken,
protocol,
logger,
daemon,
status,
}: {
host: Host
mutagenExecutable: MutagenExecutable
postHogToken: string
protocol: string
logger: Logger
daemon: MutagenDaemon
status: Status
}) {
logger = logger.withPrefix(host.id)
logger.log('starting')
const auth = await Auth.start(host.graphqlURL)
const configFile =
host.id === 'cloud'
? await File.open(dataPath('config.json')) // fallback to support apps before the multi-backend update
: await File.open(dataPath(host.id, 'config.json'))
logger.log('config file', configFile.path)
const postHogTracker = new PostHogTracker(host.graphqlURL, postHogToken)
const mutagenManager = new MutagenManager(
logger,
daemon,
mutagenExecutable,
status,
configFile,
host.apiURL,
host.graphqlURL,
host.syncURL,
postHogTracker,
auth
)
await mutagenManager.preStartMutagen()
const migrated = await configFile.migrate()
if (migrated) {
await dialog.showMessageBox({
title: 'Migration Complete',
message:
"Thanks for being a Sturdy user! We've migrated the configuration from your existing Sturdy installation to the native app. Any questions? Reach out to support@getsturdy.com!",
})
}
auth.on('logged-in', async () => {
logger.log('logged-in')
if (auth.jwt) {
await postHogTracker
.updateUser(auth.jwt)
.catch((e) => logger.error('failed to setup posthog tracker', { e }))
postHogTracker.trackStartedApp()
}
})
auth.on('logged-out', async () => {
logger.log('logged-out')
postHogTracker.unsetUser()
})
if (auth.jwt != null) {
logger.log('starting with existing jwt')
await postHogTracker
.updateUser(auth.jwt)
.catch((e) => logger.error('failed to setup posthog tracker', { e }))
postHogTracker.trackStartedApp()
mutagenManager.start()
}
return new Application(host, auth, protocol, mutagenManager, postHogTracker, status, logger)
}
async close() {
if (this.#window) {
this.#logger.log('closing window')
this.#window.close()
}
}
async openOnlyIfNotExists(startURL?: URL) {
if (this.#window != null) {
// do nothing
return
}
return this.open(startURL)
}
async open(startURL?: URL) {
if (!startURL && this.#lastURL) {
startURL = this.#lastURL
}
// Re-use window if exists
if (this.#window != null) {
this.#logger.log('re-using existing window')
if (this.#window.isMinimized()) {
this.#window.restore()
}
this.#window.show()
this.#window.focus()
if (startURL != null) {
this.#logger.log('opening url in existing window', startURL.href)
await loadURLWithoutThrowingOnRedirects(this.#window, this.#logger, startURL.href)
}
return this.#window
}
this.#logger.log('creating new window')
app.dock?.show()
const mainWindowState = ElectronWindowState({
defaultHeight: 1200,
defaultWidth: 1800,
})
this.#window = new BrowserWindow({
...mainWindowState,
minWidth: 680,
minHeight: 400,
webPreferences: {
spellcheck: true,
preload: path.join(__dirname, 'preload.js'),
devTools: true,
},
frame: false,
titleBarStyle: 'hidden',
trafficLightPosition: { x: 16, y: 16 },
icon: path.join(`${__dirname}/../assets/Sturdy.iconset/icon_512x512.png`),
})
mainWindowState.manage(this.#window)
// Create base IPC
this.#addFallbackMutagenIpc()
this.#addNonMutagenIpc()
this.#window.removeMenu()
const url = new URL(startURL ?? this.#host.webURL.href)
if (startURL == null) {
if (this.#auth.jwt == null) {
url.pathname = '/login'
} else {
url.pathname = '/codebases'
for (const arg of process.argv) {
if (arg.startsWith(this.#protocol + '://')) {
try {
url.pathname = new URL(arg).pathname
} catch (e) {
this.#logger.error(e)
}
}
}
}
}
this.#window.once('closed', () => {
this.#window = undefined
})
this.#window.webContents.on('did-navigate-in-page', (_, url) => {
const targetURL = new URL(url)
if (targetURL.toString() === this.#lastURL?.toString()) return
this.#logger.log('navigated to', targetURL.toString())
this.#lastURL = new URL(targetURL)
})
this.#window.webContents.on('before-input-event', (event, input) => {
const cmdOrCtrl = input.meta || input.control
if (cmdOrCtrl && input.key.toLowerCase() === ',') {
event.preventDefault()
this.emit('openPreferences')
}
})
this.#window.webContents.on('will-navigate', (event, url) => {
if (!url.startsWith(this.#host.webURL.href)) {
shell.openExternal(url)
event.preventDefault()
}
})
// open target="_blank" links eternally
this.#window.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url)
return { action: 'deny' }
})
// If the page fails to load, display app-fail.html
this.#window.webContents.on(
'did-fail-load',
(
event: Event,
errorCode: number,
errorDescription: string,
validatedURL: string,
isMainFrame: boolean,
frameProcessId: number,
frameRoutingId: number
) => {
this.#logger.error('did-fail-load', { errorCode, errorDescription })
this.#window?.loadFile(resourcePath('app-fail.html'), {
query: {
goto: this.#host.webURL.href,
},
})
}
)
this.#mutagenManager.setMainWindow(this.#window)
try {
this.#logger.log('loading url', url.href)
await loadURLWithoutThrowingOnRedirects(this.#window, this.#logger, url.href)
} catch (e) {
this.#logger.error('failed to loadURL', e)
}
}
async isUp() {
return await this.#host.isUp()
}
get status() {
return this.#status
}
async cleanup() {
this.#logger.log('cleaning up...')
this.#postHogTracker.flush()
await this.#mutagenManager?.cleanup()
}
get host() {
return this.#host
}
async forceRestart() {
try {
await this.#mutagenManager.forceRestart()
} catch (e) {
this.#logger.error('failed to restart mutagen', e)
}
}
#addFallbackMutagenIpc() {
const ipcImplementation: MutagenIPC = {
version: async () => 1,
async createView(workspaceID, mountPath) {
throw new Error('mutagen is not available')
},
async createNewViewWithDialog(workspaceID: string) {
throw new Error('mutagen is not available')
},
}
Object.values(sharedMutagenIpc).forEach((method) => method.clean())
Object.entries(ipcImplementation).forEach(([channel, implementation]) => {
sharedMutagenIpc[channel as keyof MutagenIPC].implement(
implementation.bind(ipcImplementation) as any
)
})
}
#addNonMutagenIpc() {
const auth = this.#auth
const window = this.#window
const logger = this.#logger
const mutagenManager = this.#mutagenManager
const status = this.#status
const ipcImplementation: AppIPC = {
isAuthenticated() {
return auth.jwt !== null
},
goBack() {
window?.webContents.goBack()
},
goForward() {
window?.webContents.goForward()
},
canGoBack() {
return window?.webContents.canGoBack() ?? false
},
canGoForward() {
return window?.webContents.canGoForward() ?? false
},
state() {
return status.state
},
minimize() {
window?.minimize()
},
maximize() {
window?.maximize()
},
unmaximize() {
window?.unmaximize()
},
close() {
window?.close()
},
isMaximized() {
return window?.isMaximized() ?? false
},
isMinimized() {
return window?.isMinimized() ?? false
},
isNormal() {
return window?.isNormal() ?? false
},
setBadgeCount(n: number) {
return app.setBadgeCount(n)
},
async forceRestartMutagen() {
try {
await mutagenManager.forceRestart()
} catch (e) {
logger.error('failed to restart mutagen', e)
}
},
}
Object.values(sharedAppIpc).forEach((method) => method.clean())
Object.entries(ipcImplementation).forEach(([channel, implementation]) => {
sharedAppIpc[channel as keyof AppIPC].implement(implementation.bind(ipcImplementation) as any)
})
}
}
async function loadURLWithoutThrowingOnRedirects(
window: BrowserWindow,
logger: Logger,
url: string
) {
const newURL = new URL(url, window.webContents.getURL() || undefined)
try {
await window.loadURL(newURL.href)
} catch (e) {
if (typeof e === 'object' && e && 'code' in e && (e as any).code === 'ERR_ABORTED') {
// This error is emitted if the browser redirects immediately after
// loading the requested URL, which happens in the SPA for different
// reasons. So we don't want this to become an actual error.
// The exception is if the browser has actually remained on the
// page that we navigated to, but still produced the error, because
// then there was something that actually aborted the navigation.
if (window.webContents.getURL() === newURL.href) {
throw e
}
logger.log(
'caught redirected loadURL from',
newURL.href,
'to',
window.webContents.getURL(),
e
)
return
}
throw e
}
} | the_stack |
import { model, Schema } from 'mongoose';
import {
addModelToTypegoose,
buildSchema,
deleteModel,
deleteModelWithClass,
errors,
getClass,
getDiscriminatorModelForClass,
getModelForClass,
getModelWithString,
getName,
Passthrough,
pre,
prop,
setGlobalOptions,
} from '../../src/typegoose'; // import order is important with jest
import { DecoratorKeys, WhatIsIt } from '../../src/internal/constants';
import { _buildSchema } from '../../src/internal/schema';
import * as utils from '../../src/internal/utils';
import { mapValueToSeverity } from '../../src/globalOptions';
import { BasePropOptions } from '../../src/types';
beforeEach(() => {
jest.restoreAllMocks();
});
it('should error if no function for hooks is defined [TypeError]', () => {
try {
// @ts-expect-error expect that the first argument needs to be an function
@pre<Test>('')
class TestNoFunctionHook {
@prop()
public test: string;
}
buildSchema(TestNoFunctionHook);
fail('Expected to throw "TypeError"');
} catch (err) {
expect(err).toBeInstanceOf(TypeError);
expect(err.message).toMatchSnapshot();
}
});
it('should error if not all needed parameters for virtual-populate are given [NotAllVPOPElementsError]', () => {
try {
class TestNAEEVirtualPopulate {
@prop({ localField: true })
public test: string;
}
buildSchema(TestNAEEVirtualPopulate);
fail('Expected to throw "NotAllVPOPElementsError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.NotAllVPOPElementsError);
expect(err.message).toMatchSnapshot();
}
});
describe('tests for "NotValidModelError"', () => {
it('should throw a Error when no valid model is passed to "addModelToTypegoose" [NotValidModelError]', () => {
try {
// @ts-expect-error "addModelToTypegoose" does not support a string as the first argument
addModelToTypegoose('string', Error);
fail('Expected to throw "NotValidModelError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.NotValidModelError);
expect(err.message).toMatchSnapshot();
}
});
it('should throw a Error when no valid model is passed to "getDiscriminatorModelForClass" [NotValidModelError]', () => {
try {
// @ts-expect-error "getDiscriminatorModelForClass" does not support a string as the first argument
getDiscriminatorModelForClass('string', Error);
fail('Expected to throw "NotValidModelError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.NotValidModelError);
expect(err.message).toMatchSnapshot();
}
});
});
describe('tests for "NoValidClassError"', () => {
it('should error if no valid class is supplied to "addModelToTypegoose" [NoValidClassError]', () => {
try {
// @ts-expect-error expect that the second argument should be an "class"
addModelToTypegoose(model('hello', new Schema()), 'not class');
fail('Expected to throw "NoValidClassError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.NoValidClassError);
expect(err.message).toMatchSnapshot();
}
});
it('should error if no valid class is supplied to "buildSchema" [NoValidClassError]', () => {
try {
// @ts-expect-error expect that the first argument should be an class
buildSchema('hello');
fail('Expected to throw "NoValidClassError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.NoValidClassError);
expect(err.message).toMatchSnapshot();
}
});
it('should error if no valid class is supplied to "_buildSchema" [NoValidClassError]', () => {
try {
// @ts-expect-error expect that the first argument should be an class
_buildSchema('hello');
fail('Expected to throw "NoValidClassError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.NoValidClassError);
expect(err.message).toMatchSnapshot();
}
});
it('should error if no valid class is supplied to "getModelForClass" [NoValidClassError]', () => {
try {
// @ts-expect-error expect that the first argument should be an class
getModelForClass('hello');
fail('Expected to throw "NoValidClassError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.NoValidClassError);
expect(err.message).toMatchSnapshot();
}
});
it('should error if no valid class is supplied to "deleteModelWithClass" [NoValidClassError]', () => {
try {
// @ts-expect-error expect that the first argument should be an class
deleteModelWithClass(true);
fail('Expected to throw "NoValidClassError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.NoValidClassError);
expect(err.message).toMatchSnapshot();
}
});
it('should error if no valid class is supplied to "mergeSchemaOptions" [NoValidClassError]', () => {
try {
// @ts-expect-error expect that the second argument should be an class
utils.mergeSchemaOptions({}, true);
fail('Expected to throw "NoValidClassError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.NoValidClassError);
expect(err.message).toMatchSnapshot();
}
});
it('should error if no valid class is supplied to "getDiscriminatorModelForClass" [NoValidClassError]', () => {
try {
// @ts-expect-error expect that the second argument should be an class
getDiscriminatorModelForClass(model('NoValidClassgetDiscriminatorModelForClass', {}), true);
fail('Expected to throw "NoValidClassError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.NoValidClassError);
expect(err.message).toMatchSnapshot();
}
});
it('should throw a Error when "cl" in "getName" is null or undefined [NoValidClassError]', () => {
try {
// @ts-expect-error "getName" only accepts classes (and types that are not null / undefined)
getName(undefined);
fail('Expected to throw "NoValidClassError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.NoValidClassError);
expect(err.message).toMatchSnapshot();
}
});
it('should error if no valid class is supplied to "assignMetadata" (and "mergeMetadata") [NoValidClassError]', () => {
try {
// @ts-expect-error expect that the third argument is an class
utils.assignMetadata(DecoratorKeys.Index, {}, true);
fail('Expected to throw "NoValidClassError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.NoValidClassError);
expect(err.message).toMatchSnapshot();
}
});
});
describe('tests for "InvalidTypeError"', () => {
it('should error if no valid type is supplied to WhatIsIt.NONE [InvalidTypeError]', () => {
try {
class TestNME {
@prop({ type: undefined })
public test: undefined;
}
buildSchema(TestNME);
fail('Expected to throw "InvalidTypeError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.InvalidTypeError);
expect(err.message).toMatchSnapshot();
}
});
it('should error if no valid type is supplied to WhatIsIt.ARRAY [InvalidTypeError]', () => {
try {
class TestNoMetadataErrorAP {
@prop({ type: undefined }, WhatIsIt.ARRAY)
public something: undefined;
}
buildSchema(TestNoMetadataErrorAP);
fail('Expected to throw "InvalidTypeError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.InvalidTypeError);
expect(err.message).toMatchSnapshot();
}
});
it('should error if no valid type is supplied to WhatIsIt.MAP [InvalidTypeError]', () => {
try {
class TestNoMetadataErrorMP {
@prop({ type: undefined }, WhatIsIt.MAP)
public something: undefined;
}
buildSchema(TestNoMetadataErrorMP);
fail('Expected to throw "InvalidTypeError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.InvalidTypeError);
expect(err.message).toMatchSnapshot();
}
});
});
it('should throw an error if a self-contained class is used [typegoose#42] [SelfContainingClassError]', () => {
try {
class TestSelfContained {
@prop()
public self: TestSelfContained;
}
buildSchema(TestSelfContained);
fail('Expected to throw "Error"');
} catch (err) {
expect(err).toBeInstanceOf(errors.SelfContainingClassError);
expect(err.message).toMatchSnapshot();
}
});
it('should throw when "deleteModel" is called with no string [TypeError]', () => {
try {
// @ts-expect-error expect that the first argument should be an class
deleteModel(true);
fail('Expected to throw "TypeError"');
} catch (err) {
expect(err).toBeInstanceOf(TypeError);
expect(err.message).toMatchSnapshot();
}
});
describe('tests for "FunctionCalledMoreThanSupportedError"', () => {
it('should throw a Error when "addModelToTypegoose" got called more than once with the same model name [FunctionCalledMoreThanSupportedError]', () => {
class TestMoreThanOnce {
@prop()
public dummy?: string;
}
const model = getModelForClass(TestMoreThanOnce);
try {
addModelToTypegoose(model, TestMoreThanOnce);
fail('Expected to throw "FunctionCalledMoreThanSupportedError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.FunctionCalledMoreThanSupportedError);
expect(err.message).toMatchSnapshot();
}
});
});
it('should error if the Type does not have a valid "OptionsConstructor" [TypeError]', () => {
try {
utils.mapOptions({}, Error, Error, 'undefined-pkey');
fail('Expected to throw "TypeError"');
} catch (err) {
expect(err).toBeInstanceOf(TypeError);
expect(err.message).toMatchSnapshot();
}
});
describe('tests for "InvalidWhatIsItError"', () => {
it('should throw a Error when a unknown WhatIsIt is used for "utils#initProperty" [InvalidWhatIsItError]', () => {
try {
utils.initProperty('a1', 'a2', -1);
fail('Expected to throw "InvalidWhatIsItError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.InvalidWhatIsItError);
expect(err.message).toMatchSnapshot();
}
});
describe('WhatIsIt unknown (processProp)', () => {
beforeEach(() => {
// Mock implementation of "utils.initProperty", otherwise "InvalidWhatIsItError.whatisit(initProperty)" always gets thrown
const origInitProperty = utils.initProperty;
jest.spyOn(utils, 'initProperty').mockImplementation((...args) => {
return origInitProperty(
args[0],
args[1],
// @ts-expect-error "-1" does not exist in WhatIsIt
args[2] === -1 ? WhatIsIt.NONE : args[2] // map "-1" to "NONE" just to have "utils.initProperty" not throw a Error, but still use it
);
});
});
it('should throw a Error when a unknown WhatIsIt is used for "processProp#Passthrough" [InvalidWhatIsItError]', () => {
class ProcessPropPassthroughWhatIsIt {
@prop({ type: () => new Passthrough({}) }, -1)
public test?: any;
}
try {
buildSchema(ProcessPropPassthroughWhatIsIt);
fail('Expected to throw "InvalidWhatIsItError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.InvalidWhatIsItError);
expect(err.message).toMatchSnapshot();
}
});
it('should throw a Error when a unknown WhatIsIt is used for "processProp#ref" [InvalidWhatIsItError]', () => {
class ProcessPropRefWhatIsIt {
@prop({ ref: 'hi' }, -1)
public test?: any;
}
try {
buildSchema(ProcessPropRefWhatIsIt);
fail('Expected to throw "InvalidWhatIsItError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.InvalidWhatIsItError);
expect(err.message).toMatchSnapshot();
}
});
it('should throw a Error when a unknown WhatIsIt is used for "processProp#refPath" [InvalidWhatIsItError]', () => {
class ProcessPropRefWhatIsIt {
@prop()
public hi?: string;
@prop({ refPath: 'hi' }, -1)
public test?: any;
}
try {
buildSchema(ProcessPropRefWhatIsIt);
fail('Expected to throw "InvalidWhatIsItError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.InvalidWhatIsItError);
expect(err.message).toMatchSnapshot();
}
});
it('should throw a Error when a unknown WhatIsIt is used for "processProp#primitive" [InvalidWhatIsItError]', () => {
class ProcessPropRefWhatIsIt {
@prop({ type: () => String }, -1)
public test?: string;
}
try {
buildSchema(ProcessPropRefWhatIsIt);
fail('Expected to throw "InvalidWhatIsItError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.InvalidWhatIsItError);
expect(err.message).toMatchSnapshot();
}
});
it('should throw a Error when a unknown WhatIsIt is used for "processProp#subSchema" [InvalidWhatIsItError]', () => {
class Sub {
@prop()
public dummy?: string;
}
class ProcessPropRefWhatIsIt {
@prop({ type: () => Sub }, -1)
public test?: Sub;
}
try {
buildSchema(ProcessPropRefWhatIsIt);
fail('Expected to throw "InvalidWhatIsItError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.InvalidWhatIsItError);
expect(err.message).toMatchSnapshot();
}
});
});
it('should throw a Error when "WhatIsIt.MAP" is used for "processProp#refPath" [InvalidWhatIsItError]', () => {
class ProcessPropRefWhatIsIt {
@prop()
public hi?: string;
@prop({ refPath: 'hi' }, WhatIsIt.MAP)
public test?: any;
}
try {
buildSchema(ProcessPropRefWhatIsIt);
fail('Expected to throw "InvalidWhatIsItError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.InvalidWhatIsItError);
expect(err.message).toMatchSnapshot();
}
});
});
it('should error if the options provide to "setGlobalOptions" are not an object [TypeError]', () => {
try {
// @ts-expect-error "undefined" does not match the restriction "IGlobalOptions"
setGlobalOptions(undefined);
fail('Expected to throw "TypeError"');
} catch (err) {
expect(err).toBeInstanceOf(TypeError);
expect(err.message).toMatchSnapshot();
}
});
it('should fail when using Number-Enum on an String Type [NotStringTypeError]', () => {
try {
enum NumberEnum {
One = 0,
Two = 1,
}
class NumberEnumOnStringType {
@prop({ enum: NumberEnum })
public someEnum: string;
}
getModelForClass(NumberEnumOnStringType);
fail('Expected to throw "NotStringTypeError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.NotStringTypeError);
expect(err.message).toMatchSnapshot();
}
});
it('should fail when using String-Enum on an Number Type [NotNumberTypeError]', () => {
try {
enum StringEnum {
One = 'hi1',
Two = 'hi2',
}
class NumberEnumOnStringType {
@prop({ enum: StringEnum })
public someEnum: number;
}
getModelForClass(NumberEnumOnStringType);
fail('Expected to throw "NotNumberTypeError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.NotNumberTypeError);
expect(err.message).toMatchSnapshot();
}
});
it('should error if no valid key is supplied to "getModelWithString" [TypeError]', () => {
try {
// @ts-expect-error expect the first argument to be an "string"
getModelWithString(true);
fail('Expected to throw "TypeError"');
} catch (err) {
expect(err).toBeInstanceOf(TypeError);
expect(err.message).toMatchSnapshot();
}
});
it('should error if a non-valid object is passed to "getClass" [ReferenceError]', () => {
try {
getClass(undefined);
fail('Expected to throw "ReferenceError"');
} catch (err) {
expect(err).toBeInstanceOf(ReferenceError);
expect(err.message).toMatchSnapshot();
}
});
it('should error if 0 or less dimensions are given (createArrayFromDimensions) [RangeError]', () => {
try {
utils.createArrayFromDimensions({ dim: 0 }, { someThing: true }, '', '');
fail('Expected to throw "RangeError"');
} catch (err) {
expect(err).toBeInstanceOf(RangeError);
expect(err.message).toMatchSnapshot();
}
try {
utils.createArrayFromDimensions({ dim: -100 }, { someThing: true }, '', '');
fail('Expected to throw "RangeError"');
} catch (err) {
expect(err).toBeInstanceOf(RangeError);
expect(err.message).toMatchSnapshot();
}
});
describe('tests for "RefOptionIsUndefinedError"', () => {
it('should error if "ref" is set to a function, but returns "null" or "undefined" [RefOptionIsUndefinedError]', () => {
class Main {
// @ts-expect-error expect that "ref" is an function and returns an "string"
@prop({ ref: () => undefined })
public nested: any; // not setting type to "Ref", because this is a unsupported way for the type
}
try {
buildSchema(Main);
fail('Expected to throw "RefOptionIsUndefinedError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.RefOptionIsUndefinedError);
expect(err.message).toMatchSnapshot();
}
});
it('should error if ref is set but is "null" or "undefined" [RefOptionIsUndefinedError]', () => {
try {
class RefUndefined {
@prop({ ref: undefined })
public someref?: any; // not setting type to "Ref", because this is a unsupported way for the type
}
buildSchema(RefUndefined);
fail('Expect to throw "RefOptionIsUndefinedError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.RefOptionIsUndefinedError);
expect(err.message).toMatchSnapshot();
}
});
});
it('should throw default error if no error is specified (assertion) [AssertionFallbackError]', () => {
expect.assertions(2);
try {
utils.assertion(false);
// The following is unreachable (by types), but still there just in case something happens
fail('Expected to throw "AssertionFallbackError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.AssertionFallbackError);
expect(err.message).toMatchSnapshot();
}
});
it('should throw a Error when the property is a Symbol [CannotBeSymbolError]', async () => {
const sym = Symbol();
class TestPropertySymbol {
@prop()
public dummy?: string;
@prop()
public [sym]?: string;
}
try {
buildSchema(TestPropertySymbol);
fail('Expected to fail with "CannotBeSymbolError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.CannotBeSymbolError);
expect(err.message).toMatchSnapshot();
}
});
it('should throw a Error when "ref" is a array [OptionRefDoesNotSupportArraysError]', async () => {
class Sub {
@prop()
public dummy?: string;
}
class TestOptionRefDoesNotSupportArraysError {
// @ts-expect-error option "ref" does not accept a array
@prop({ ref: () => [Sub] })
public nested?: any;
}
try {
buildSchema(TestOptionRefDoesNotSupportArraysError);
fail('Expected to throw "OptionRefDoesNotSupportArraysError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.OptionRefDoesNotSupportArraysError);
expect(err.message).toMatchSnapshot();
}
});
it('should throw a Error when "mapValueToSeverity" gets called but is not in "Severity" [Error]', () => {
try {
mapValueToSeverity(-1);
fail('Expected to throw "Error"');
} catch (err) {
expect(err).toBeInstanceOf(Error);
expect(err.message).toMatchSnapshot();
}
});
describe('tests for "StringLengthExpectedError"', () => {
class DummyClass {}
it('should throw a Error in "utils.getName" when "customName" is defined but not a String [StringLengthExpectedError]', () => {
try {
utils.getName(DummyClass, {
options: {
// @ts-expect-error "customName" only accepts "undefined", "string" or a function returning a "string"
customName: 10,
},
});
fail('Expected to throw "StringLengthExpectedError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.StringLengthExpectedError);
expect(err.message).toMatchSnapshot();
}
});
it('should throw a Error in "utils.getName" when "customName" is defined but string does not meet the required length [StringLengthExpectedError]', () => {
try {
utils.getName(DummyClass, {
options: {
customName: '',
},
});
fail('Expected to throw "StringLengthExpectedError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.StringLengthExpectedError);
expect(err.message).toMatchSnapshot();
}
});
it('should throw a Error in "utils.getName" when "customName" is defined as a function but does not return a String [StringLengthExpectedError]', () => {
try {
utils.getName(DummyClass, {
options: {
// @ts-expect-error "customName" only accepts "undefined", "string" or a function returning a "string"
customName: () => 10,
},
});
fail('Expected to throw "StringLengthExpectedError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.StringLengthExpectedError);
expect(err.message).toMatchSnapshot();
}
});
it('should throw a Error in "utils.getName" when "customName" is defined as a function but return does not meet the required length [StringLengthExpectedError]', () => {
try {
utils.getName(DummyClass, {
options: {
customName: () => '',
},
});
fail('Expected to throw "StringLengthExpectedError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.StringLengthExpectedError);
expect(err.message).toMatchSnapshot();
}
});
it('should throw a Error in "utils.mergeMetadata" when "key" is not a string [StringLengthExpectedError]', () => {
try {
utils.mergeMetadata(
// @ts-expect-error "undefined" is not a key in "DecoratorKeys"
undefined,
undefined,
DummyClass
);
fail('Expected to throw "StringLengthExpectedError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.StringLengthExpectedError);
expect(err.message).toMatchSnapshot();
}
});
it('should throw a Error in "utils.mergeMetadata" when "key" is a string but does not meet the required length [StringLengthExpectedError]', () => {
try {
utils.mergeMetadata(
// @ts-expect-error "" is not a key in "DecoratorKeys"
'',
undefined,
DummyClass
);
fail('Expected to throw "StringLengthExpectedError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.StringLengthExpectedError);
expect(err.message).toMatchSnapshot();
}
});
it('should throw a Error in "processProp" when "refPath" is not a string [StringLengthExpectedError]', () => {
try {
class TestRefPathString {
@prop(
// @ts-expect-error "refPath" only accepts strings
{
refPath: 10,
} as BasePropOptions
)
public test?: string;
}
buildSchema(TestRefPathString);
fail('Expected to throw "StringLengthExpectedError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.StringLengthExpectedError);
expect(err.message).toMatchSnapshot();
}
});
it('should throw a Error in "processProp" when "refPath" is a string but does not meet the required length [StringLengthExpectedError]', () => {
try {
class TestRefPathString {
@prop({ refPath: '' })
public test?: string;
}
buildSchema(TestRefPathString);
fail('Expected to throw "StringLengthExpectedError"');
} catch (err) {
expect(err).toBeInstanceOf(errors.StringLengthExpectedError);
expect(err.message).toMatchSnapshot();
}
});
}); | the_stack |
import {
Actor,
assign,
createMachine,
send,
SpawnedActorRef,
State,
} from "xstate";
import RenJS from "@renproject/ren";
import { DepositCommon, LockChain, MintChain } from "@renproject/interfaces";
import { assert } from "@renproject/utils";
import { log } from "xstate/lib/actions";
import { UTXO } from "@renproject/chains-bitcoin/build/main/APIs/API";
import {
AllGatewayTransactions,
AcceptedGatewayTransaction,
ConfirmingGatewayTransaction,
GatewaySession,
GatewayTransaction,
MintedGatewayTransaction,
isMinted,
OpenedGatewaySession,
isOpen,
} from "../types/mint";
import {
DepositMachineContext,
DepositMachineEvent,
DepositMachineSchema,
DepositMachineTypestate,
} from "./deposit";
export interface GatewayMachineContext<DepositType, MintType = any> {
/**
* The session arguments used for instantiating a mint gateway
*/
tx: GatewaySession<DepositType> | OpenedGatewaySession<DepositType>;
/**
* A reference to a deposit hashes of transactions that can be
* minted on their destination chains
*/
mintRequests?: string[];
/**
* @private
* Keeps track of child machines that track underlying deposits
*/
depositMachines?: {
[key in string]: SpawnedActorRef<
DepositMachineEvent<DepositType>,
State<
DepositMachineContext<AllGatewayTransactions<DepositType>>,
DepositMachineEvent<DepositType>,
DepositMachineSchema<DepositType>,
DepositMachineTypestate<DepositType>
>
>;
};
/**
* @private
* a listener callback that interacts with renjs deposit objects
*/
depositListenerRef?: Actor<any>;
/**
* Function to create the "from" param;
*/
from: (
context: GatewayMachineContext<DepositType>,
) => LockChain<DepositType, DepositCommon<DepositType>>;
/**
* Function to create the "to" RenJS param;
*/
to: (context: GatewayMachineContext<DepositType>) => MintChain<MintType>;
sdk: RenJS;
}
export enum GatewayStates {
RESTORING = "restoring",
CREATING = "creating",
ERROR_CREATING = "srcInitializeError",
LISTENING = "listening",
COMPLETED = "completed",
}
export interface GatewayMachineSchema {
states: {
restoring: {};
creating: {};
srcInitializeError: {};
listening: {};
completed: {};
};
}
export type DepositEvent<DepositType> = {
type: "DEPOSIT";
data: GatewayTransaction<DepositType>;
};
export type GatewayMachineEvent<DepositType> =
| DepositMachineEvent<DepositType>
| { type: "CLAIMABLE"; data: AcceptedGatewayTransaction<DepositType> }
| { type: "ERROR_LISTENING"; data: any }
| DepositEvent<DepositType>
| { type: "DEPOSIT_UPDATE"; data: AllGatewayTransactions<DepositType> }
| { type: "DEPOSIT_COMPLETED"; data: MintedGatewayTransaction<DepositType> }
| { type: "SIGN"; data: ConfirmingGatewayTransaction<DepositType> }
| { type: "SETTLE"; data: GatewayTransaction<DepositType> }
| { type: "MINT"; data: AcceptedGatewayTransaction<DepositType> }
| { type: "EXPIRED"; data: GatewayTransaction<DepositType> }
| { type: "ACKNOWLEDGE"; data: any }
| { type: "RESTORE"; data: GatewayTransaction<DepositType> };
type extractGeneric<Type> = Type extends LockChain<infer X> ? X : never;
export interface LockChainMap<Context> {
[key: string]: (context: Context) => LockChain<any, DepositCommon<any>>;
}
export interface MintChainMap<Context> {
[key: string]: (context: Context) => MintChain<any>;
}
export const buildMintContextWithMap = <X>(params: {
tx: GatewaySession<X> | OpenedGatewaySession<X>;
sdk: RenJS;
/**
* Functions to create the "from" param;
*/
fromChainMap: LockChainMap<GatewayMachineContext<X>>;
/**
* Functions to create the "to" RenJS param;
*/
toChainMap: MintChainMap<GatewayMachineContext<X>>;
}) => {
const from = params.fromChainMap[params.tx.sourceChain];
const to = params.toChainMap[params.tx.destChain];
const constructed: GatewayMachineContext<
extractGeneric<ReturnType<typeof from>>
> = {
tx: params.tx,
to,
sdk: params.sdk,
from,
};
return constructed;
};
/**
* An Xstate machine that, when given a serializable [[GatewaySession]] tx,
* will instantiate a RenJS LockAndMint session, provide a gateway address,
* listen for deposits, and request a signature once a deposit has reached
* the appropriate number of confirmations.
*
* Given the same [[GatewaySession]] parameters, as long as the tx has not
* expired, the machine will restore the transaction to the appropriate
* state and enable the completion of in-progress minting transactions.
*
* The machine allows for multiple deposits to be detected; it is up to the
* developer to decide if a detected deposit should be signed or rejected.
* See `/demos/simpleMint.ts` for example usage.
*/
export const buildMintMachine = <X extends UTXO>() =>
createMachine<GatewayMachineContext<X>, GatewayMachineEvent<X>>(
{
id: "RenVMGatewaySession",
initial: "restoring",
states: {
restoring: {
entry: [
send("RESTORE"),
assign({
mintRequests: (_c, _e) => [],
depositMachines: (_ctx, _evt) => ({}),
}),
],
meta: { test: async () => {} },
on: {
RESTORE: [
{
target: "completed",
cond: "isExpired",
},
{
target: "listening",
cond: "isCreated",
},
{
target: "creating",
},
],
},
},
creating: {
meta: {
test: (_: void, state: any) => {
assert(
!state.context.tx.gatewayAddress ? true : false,
"Gateway address should not be initialized",
);
},
},
invoke: {
src: "txCreator",
onDone: {
target: "listening",
actions: assign({
tx: (_context, evt) => ({ ...evt.data }),
}),
},
onError: {
target: "srcInitializeError",
actions: [
assign({
tx: (context, evt) => {
const newTx = {
...context.tx,
error: evt.data || true,
};
return newTx;
},
}),
log((_ctx, evt) => evt.data, "ERROR"),
],
},
},
},
srcInitializeError: {
meta: {
test: (_: void, state: any) => {
assert(
state.context.tx.error ? true : false,
"Error must exist",
);
},
},
},
listening: {
meta: {
test: (_: void, state: any) => {
assert(
state.context.tx.gatewayAddress ? true : false,
"GatewayAddress must exist",
);
},
},
invoke: {
src: "depositListener",
},
on: {
EXPIRED: "completed",
// once we have ren-js listening for deposits,
// start the statemachines to determine deposit states
LISTENING: { actions: "depositMachineSpawner" },
ERROR_LISTENING: {
target: "srcInitializeError",
actions: [
assign({
tx: (context, evt) => {
const newTx = {
...context.tx,
error: evt.data || true,
};
return newTx;
},
}),
log((_ctx, evt) => evt.data, "ERROR"),
],
},
// forward messages from child machines to renjs listeners
RESTORE: [
{
cond: "isPersistedDeposit",
actions: "forwardEvent",
},
{
actions: [
assign({
tx: ({ tx }, e) => {
if (!e.data.sourceTxHash) return tx;
return {
...tx,
transactions: {
...tx.transactions,
[e.data.sourceTxHash]:
e.data,
},
} as any;
},
}),
"spawnDepositMachine",
"forwardEvent",
],
},
],
SETTLE: {
actions: "forwardEvent",
},
SIGN: {
actions: "forwardEvent",
},
MINT: {
actions: "forwardEvent",
},
// Send messages to child machines
RESTORED: {
actions: "routeEvent",
},
CLAIM: { actions: "routeEvent" },
CONFIRMATION: { actions: "routeEvent" },
CONFIRMED: { actions: "routeEvent" },
ERROR: { actions: "routeEvent" },
SIGN_ERROR: { actions: "routeEvent" },
REVERTED: { actions: "routeEvent" },
SUBMIT_ERROR: { actions: "routeEvent" },
SIGNED: { actions: "routeEvent" },
SUBMITTED: { actions: "routeEvent" },
ACKNOWLEDGE: { actions: "routeEvent" },
CLAIMABLE: {
actions: assign({
mintRequests: (context, evt) => {
const oldRequests =
context.mintRequests || [];
const newRequest = evt.data?.sourceTxHash;
if (!newRequest) {
return oldRequests;
}
if (oldRequests.includes(newRequest)) {
return oldRequests;
}
return [...oldRequests, newRequest];
},
tx: (context, evt) => {
if (evt.data.sourceTxHash) {
context.tx.transactions[
evt.data.sourceTxHash
] = evt.data;
}
return context.tx;
},
}),
},
// We only complete when expiring
// DEPOSIT_COMPLETED: {
// target: "completed",
// cond: "isCompleted",
// },
DEPOSIT_UPDATE: [
{
actions: [
assign({
mintRequests: (ctx, evt) => {
// check if completed
if (isMinted(evt.data)) {
return (
ctx.mintRequests?.filter(
(x) =>
x !==
evt.data
.sourceTxHash,
) || []
);
} else {
return ctx.mintRequests;
}
},
tx: (context, evt) => {
if (evt.data.sourceTxHash) {
context.tx.transactions[
evt.data.sourceTxHash
] = evt.data;
}
return context.tx;
},
}),
send(
(_, evt) => {
return {
type: "UPDATE",
hash: evt.data.sourceTxHash,
data: evt.data,
};
},
{
to: (
_ctx: GatewayMachineContext<X>,
) => "depositListener",
},
),
],
},
],
DEPOSIT: {
cond: "isNewDeposit",
actions: [
assign({
tx: (context, evt) => {
// Replace the transaction with the newly
// detected one; the listener will provide
// persisted data if it is already present
return {
...context.tx,
transactions: {
...context.tx.transactions,
[evt.data.sourceTxHash]:
evt.data,
},
};
},
}),
"spawnDepositMachine",
],
},
},
},
completed: {
meta: {
test: (_: any, state: any) => {
if (state.context.depositListenerRef) {
throw Error(
"Deposit listener has not been cleaned up",
);
}
},
},
},
},
},
{
guards: {
isPersistedDeposit: (ctx, evt) => {
const depositEvt = evt as DepositEvent<X>;
if (!depositEvt.data) return false;
return (ctx.tx.transactions || {})[
depositEvt.data.sourceTxHash
]
? true
: false;
},
isNewDeposit: (ctx, evt) => {
const depositEvt = evt as DepositEvent<X>;
if (!depositEvt.data) return false;
return !(ctx.depositMachines || {})[
depositEvt.data.sourceTxHash
];
},
isExpired: ({ tx }) => tx.expiryTime < new Date().getTime(),
isCreated: ({ tx }) => isOpen(tx),
},
},
); | the_stack |
import './setup';
import { PLATFORM } from 'aurelia-pal';
import { HttpClient } from '../src/http-client';
import { HttpClientConfiguration } from '../src/http-client-configuration';
import { Interceptor } from '../src/interfaces';
import { retryStrategy } from '../src/retry-interceptor';
import { json } from '../src/util';
describe('HttpClient', () => {
let originalFetch = window.fetch;
let client;
let fetch: jasmine.Spy;
function setUpTests() {
beforeEach(() => {
client = new HttpClient();
fetch = window.fetch = jasmine.createSpy('fetch');
});
afterEach(() => {
fetch = window.fetch = originalFetch as any;
});
}
setUpTests();
it('errors on missing fetch implementation', () => {
window.fetch = undefined;
expect(() => new HttpClient()).toThrow();
});
describe('configure', () => {
it('accepts plain objects', () => {
let defaults = {};
client.configure(defaults);
expect(client.isConfigured).toBe(true);
expect(client.defaults).toBe(defaults);
});
it('accepts configuration callbacks', () => {
let defaults = { foo: true };
let baseUrl = '/test';
let interceptor = {};
client.configure(config => {
expect(config).toEqual(jasmine.any(HttpClientConfiguration));
return config
.withDefaults(defaults)
.withBaseUrl(baseUrl)
.withInterceptor(interceptor);
});
expect(client.isConfigured).toBe(true);
expect(client.defaults.foo).toBe(true);
expect(client.baseUrl).toBe(baseUrl);
expect(client.interceptors.indexOf(interceptor)).toBe(0);
});
it('accepts configuration override', () => {
let defaults = { foo: true };
client.configure(config => config.withDefaults(defaults));
client.configure(config => {
expect(config.defaults.foo).toBe(true);
});
});
it('rejects invalid configs', () => {
expect(() => client.configure(1)).toThrow();
});
it('applies standard configuration', () => {
client.configure(config => config.useStandardConfiguration());
expect(client.defaults.credentials).toBe('same-origin');
expect(client.interceptors.length).toBe(1);
});
it('rejects error responses', () => {
client.configure(config => config.rejectErrorResponses());
expect(client.interceptors.length).toBe(1);
});
});
describe('fetch', () => {
it('makes requests with string inputs', (done) => {
fetch.and.returnValue(emptyResponse(200));
client
.fetch('http://example.com/some/cool/path')
.then(result => {
expect(result.ok).toBe(true);
})
.catch(result => {
expect(result).not.toBe(result);
})
.then(() => {
expect(fetch).toHaveBeenCalled();
done();
});
});
it('makes proper requests with json() inputs', (done) => {
fetch.and.returnValue(emptyResponse(200));
client
.fetch('http://example.com/some/cool/path', {
method: 'post',
body: json({ test: 'object' })
})
.then(result => {
expect(result.ok).toBe(true);
})
.catch(result => {
expect(result).not.toBe(result);
})
.then(() => {
expect(fetch).toHaveBeenCalled();
let [request] = fetch.calls.first().args;
expect(request.headers.has('content-type')).toBe(true);
expect(request.headers.get('content-type')).toMatch(/application\/json/);
done();
});
});
it('makes proper requests with JSON.stringify inputs', (done) => {
fetch.and.returnValue(emptyResponse(200));
client
.fetch('http://example.com/some/cool/path', {
method: 'post',
body: JSON.stringify({ test: 'object' })
})
.then(result => {
expect(result.ok).toBe(true);
})
.catch(result => {
expect(result).not.toBe(result);
})
.then(() => {
expect(fetch).toHaveBeenCalled();
let [request] = fetch.calls.first().args;
expect(request.headers.has('content-type')).toBe(true);
expect(request.headers.get('content-type')).toMatch(/application\/json/);
done();
});
});
it('makes requests with null RequestInit', (done) => {
fetch.and.returnValue(emptyResponse(200));
client
.fetch('http://example.com/some/cool/path', null)
.then(result => {
expect(result.ok).toBe(true);
})
.catch(result => {
expect(result).not.toBe(result);
})
.then(() => {
expect(fetch).toHaveBeenCalled();
done();
});
});
it('makes requests with Request inputs', (done) => {
fetch.and.returnValue(emptyResponse(200));
client
.fetch(new Request('http://example.com/some/cool/path'))
.then(result => {
expect(result.ok).toBe(true);
})
.catch(result => {
expect(result).not.toBe(result);
})
.then(() => {
expect(fetch).toHaveBeenCalled();
done();
});
});
it('makes requests with Request inputs when configured', (done) => {
fetch.and.returnValue(emptyResponse(200));
client.configure(config => config.withBaseUrl('http://example.com/'));
client
.fetch(new Request('some/cool/path'))
.then(result => {
expect(result.ok).toBe(true);
})
.catch(result => {
expect(result).not.toBe(result);
})
.then(() => {
expect(fetch).toHaveBeenCalled();
done();
});
});
it('makes request and aborts with an AbortController signal', (done) => {
fetch = window.fetch = originalFetch as any;
const controller = new AbortController();
client
.fetch('http://jsonplaceholder.typicode.com/users', {signal: controller.signal})
.then(result => {
expect(result).not.toBe(result);
})
.catch(result => {
expect(result instanceof Error).toBe(true);
expect(result.name).toBe('AbortError');
})
.then(() => {
done();
});
controller.abort();
});
});
describe('get', () => {
it('passes-through to fetch', (done) => {
fetch.and.returnValue(emptyResponse(200));
client
.get('http://example.com/some/cool/path')
.then(result => {
expect(result.ok).toBe(true);
})
.catch(result => {
expect(result).not.toBe(result);
})
.then(() => {
expect(fetch).toHaveBeenCalled();
done();
});
});
});
describe('post', () => {
it('sets method to POST and body of request and calls fetch', (done) => {
fetch.and.returnValue(emptyResponse(200));
client
.post('http://example.com/some/cool/path', JSON.stringify({ test: 'object' }))
.then(result => {
expect(result.ok).toBe(true);
})
.catch(result => {
expect(result).not.toBe(result);
})
.then(() => {
expect(fetch).toHaveBeenCalled();
done();
});
});
});
describe('put', () => {
it('sets method to PUT and body of request and calls fetch', (done) => {
fetch.and.returnValue(emptyResponse(200));
client
.put('http://example.com/some/cool/path', JSON.stringify({ test: 'object' }))
.then(result => {
expect(result.ok).toBe(true);
})
.catch(result => {
expect(result).not.toBe(result);
})
.then(() => {
expect(fetch).toHaveBeenCalled();
done();
});
});
});
describe('patch', () => {
it('sets method to PATCH and body of request and calls fetch', (done) => {
fetch.and.returnValue(emptyResponse(200));
client
.patch('http://example.com/some/cool/path', JSON.stringify({ test: 'object' }))
.then(result => {
expect(result.ok).toBe(true);
})
.catch(result => {
expect(result).not.toBe(result);
})
.then(() => {
expect(fetch).toHaveBeenCalled();
done();
});
});
});
describe('delete', () => {
it('sets method to DELETE and body of request and calls fetch', (done) => {
fetch.and.returnValue(emptyResponse(200));
client
.delete('http://example.com/some/cool/path', JSON.stringify({ test: 'object' }))
.then(result => {
expect(result.ok).toBe(true);
})
.catch(result => {
expect(result).not.toBe(result);
})
.then(() => {
expect(fetch).toHaveBeenCalled();
done();
});
});
});
describe('interceptors', () => {
setUpTests();
it('run on request', (done) => {
fetch.and.returnValue(emptyResponse(200));
let interceptor = { request(r) { return r; }, requestError(r) { throw r; } };
spyOn(interceptor, 'request').and.callThrough();
spyOn(interceptor, 'requestError').and.callThrough();
client.interceptors.push(interceptor);
client.fetch('path')
.then(() => {
expect(interceptor.request).toHaveBeenCalledWith(jasmine.any(Request), client);
expect(interceptor.requestError).not.toHaveBeenCalled();
done();
});
});
it('run on request error', (done) => {
fetch.and.returnValue(emptyResponse(200));
let interceptor = { request(r) { return r; }, requestError(r) { throw r; } };
spyOn(interceptor, 'request').and.callThrough();
spyOn(interceptor, 'requestError').and.callThrough();
client.interceptors.push({ request() { return Promise.reject(new Error('test')); }});
client.interceptors.push(interceptor);
client.fetch()
.catch(() => {
expect(interceptor.request).not.toHaveBeenCalled();
expect(interceptor.requestError).toHaveBeenCalledWith(jasmine.any(Error), client);
done();
});
});
it('run on response', (done) => {
fetch.and.returnValue(emptyResponse(200));
let interceptor = { response(r) { return r; }, responseError(r) { throw r; } };
spyOn(interceptor, 'response').and.callThrough();
spyOn(interceptor, 'responseError').and.callThrough();
client.interceptors.push(interceptor);
client.fetch('path')
.then(() => {
expect(interceptor.response).toHaveBeenCalledWith(jasmine.any(Response), jasmine.any(Request), client);
expect(interceptor.responseError).not.toHaveBeenCalled();
done();
});
});
it('run on response error', (done) => {
fetch.and.returnValue(Promise.reject(new Response(null, { status: 500 })));
let interceptor = { response(r) { return r; }, responseError(r) { throw r; } };
spyOn(interceptor, 'response').and.callThrough();
spyOn(interceptor, 'responseError').and.callThrough();
client.interceptors.push(interceptor);
client.fetch('path')
.catch(() => {
expect(interceptor.response).not.toHaveBeenCalled();
expect(interceptor.responseError).toHaveBeenCalledWith(jasmine.any(Response), jasmine.any(Request), client);
done();
});
});
it('forward requests', (done) => {
const path = 'retry';
let retry = 3;
fetch.and.returnValue(Promise.reject(new Response(null, { status: 500 })));
let interceptor: Interceptor = {
response(r) { return r; },
responseError(r) {
if (retry--) {
let request = client.buildRequest(path);
return request;
} else {
throw r;
}
}
};
spyOn(interceptor, 'response').and.callThrough();
spyOn(interceptor, 'responseError').and.callThrough();
client.interceptors.push(interceptor);
client.fetch(path)
.catch(() => {
expect(interceptor.response).not.toHaveBeenCalled();
expect(interceptor.responseError).toHaveBeenCalledWith(jasmine.any(Response), jasmine.any(Request), client);
expect(fetch).toHaveBeenCalledTimes(4);
done();
});
});
it('normalizes input for interceptors', (done) => {
fetch.and.returnValue(emptyResponse(200));
let request;
client.interceptors.push({ request(r) { request = r; return r; } });
client
.fetch('http://example.com/some/cool/path')
.then(() => {
expect(request instanceof Request).toBe(true);
done();
});
});
it('runs multiple interceptors', (done) => {
fetch.and.returnValue(emptyResponse(200));
let first = { request(r) { return r; } };
let second = { request(r) { return r; } };
spyOn(first, 'request').and.callThrough();
spyOn(second, 'request').and.callThrough();
client.interceptors.push(first);
client.interceptors.push(second);
client.fetch('path')
.then(() => {
expect(first.request).toHaveBeenCalledWith(jasmine.any(Request), client);
expect(second.request).toHaveBeenCalledWith(jasmine.any(Request), client);
done();
});
});
it('request interceptors can modify request', (done) => {
fetch.and.returnValue(emptyResponse(200));
let interceptor = { request() { return new Request('http://aurelia.io/'); } };
client.interceptors.push(interceptor);
client.fetch('first')
.then(() => {
expect(fetch.calls.mostRecent().args[0].url).toBe('http://aurelia.io/');
done();
});
});
it('request interceptors can short circuit request', (done) => {
let response = new Response();
let interceptor = { request() { return response; } };
client.interceptors.push(interceptor);
client.fetch('path')
.then((r) => {
expect(r).toBe(response);
expect(fetch).not.toHaveBeenCalled();
done();
});
});
it('doesn\'t reject unsuccessful responses', (done) => {
let response = new Response(null, { status: 500 });
fetch.and.returnValue(Promise.resolve(response));
client.fetch('path')
.catch((r) => {
expect(r).not.toBe(response);
})
.then((r) => {
expect(r.ok).toBe(false);
done();
});
});
describe('rejectErrorResponses', () => {
it('can reject error responses', (done) => {
let response = new Response(null, { status: 500 });
fetch.and.returnValue(Promise.resolve(response));
client.configure(config => config.rejectErrorResponses());
client.fetch('path')
.then((r) => {
expect(r).not.toBe(r);
})
.catch((r) => {
expect(r).toBe(response);
done();
});
});
it('resolves successful requests', (done) => {
fetch.and.returnValue(emptyResponse(200));
client.configure(config => config.rejectErrorResponses());
client.fetch('path')
.catch((r) => {
expect(r).not.toBe(r);
})
.then((r) => {
expect(r.ok).toBe(true);
done();
});
});
});
});
describe('default request parameters', () => {
setUpTests();
it('applies baseUrl to requests', (done) => {
fetch.and.returnValue(emptyResponse(200));
client.baseUrl = 'http://aurelia.io/';
client.fetch('path')
.then(() => {
let [request] = fetch.calls.first().args;
expect(request.url).toBe('http://aurelia.io/path');
done();
});
});
it('doesn\'t apply baseUrl to absolute URLs', (done) => {
fetch.and.returnValue(emptyResponse(200));
client.baseUrl = 'http://aurelia.io/';
client.fetch('https://example.com/test')
.then(() => {
let [request] = fetch.calls.first().args;
expect(request.url).toBe('https://example.com/test');
done();
});
});
it('applies default headers to requests with no headers', (done) => {
fetch.and.returnValue(emptyResponse(200));
client.defaults = { headers: { 'x-foo': 'bar' } };
client.fetch('path')
.then(() => {
let [request] = fetch.calls.first().args;
expect(request.headers.has('x-foo')).toBe(true);
expect(request.headers.get('x-foo')).toBe('bar');
done();
});
});
it('applies default headers to requests with other headers', (done) => {
fetch.and.returnValue(emptyResponse(200));
client.defaults = { headers: { 'x-foo': 'bar' } };
client.fetch('path', { headers: { 'x-baz': 'bat' } })
.then(() => {
let [request] = fetch.calls.first().args;
expect(request.headers.has('x-foo')).toBe(true);
expect(request.headers.has('x-baz')).toBe(true);
expect(request.headers.get('x-foo')).toBe('bar');
expect(request.headers.get('x-baz')).toBe('bat');
done();
});
});
it('applies default headers to requests using Headers instance', (done) => {
fetch.and.returnValue(emptyResponse(200));
client.defaults = { headers: { 'x-foo': 'bar' } };
client.fetch('path', { headers: new Headers({ 'x-baz': 'bat' }) })
.then(() => {
let [request] = fetch.calls.first().args;
expect(request.headers.has('x-foo')).toBe(true);
expect(request.headers.has('x-baz')).toBe(true);
expect(request.headers.get('x-foo')).toBe('bar');
expect(request.headers.get('x-baz')).toBe('bat');
done();
});
});
it('does not overwrite request headers with default headers', (done) => {
fetch.and.returnValue(emptyResponse(200));
client.defaults = { headers: { 'x-foo': 'bar' } };
client.fetch('path', { headers: { 'x-foo': 'baz' } })
.then(() => {
let [request] = fetch.calls.first().args;
expect(request.headers.has('x-foo')).toBe(true);
expect(request.headers.get('x-foo')).toBe('baz');
done();
});
});
it('evaluates default header function values with no headers', (done) => {
fetch.and.returnValue(emptyResponse(200));
client.defaults = { headers: { 'x-foo': () => 'bar' } };
client.fetch('path')
.then(() => {
let [request] = fetch.calls.first().args;
expect(request.headers.has('x-foo')).toBe(true);
expect(request.headers.get('x-foo')).toBe('bar');
done();
});
});
it('evaluates default header function values with other headers', (done) => {
fetch.and.returnValue(emptyResponse(200));
client.defaults = { headers: { 'x-foo': () => 'bar' } };
client.fetch('path', { headers: { 'x-baz': 'bat' } })
.then(() => {
let [request] = fetch.calls.first().args;
expect(request.headers.has('x-foo')).toBe(true);
expect(request.headers.has('x-baz')).toBe(true);
expect(request.headers.get('x-foo')).toBe('bar');
expect(request.headers.get('x-baz')).toBe('bat');
done();
});
});
it('evaluates default header function values on each request', (done) => {
fetch.and.returnValue(emptyResponse(200));
let value = 0;
client.defaults = {
headers: {
'x-foo': () => {
value++;
return value;
}
}
};
let promises = [];
promises.push(client.fetch('path1'));
promises.push(client.fetch('path2'));
Promise.all(promises)
.then(() => {
let [request1] = fetch.calls.first().args;
let [request2] = fetch.calls.mostRecent().args;
expect(request1.headers.has('x-foo')).toBe(true);
expect(request1.headers.get('x-foo')).toBe('1');
expect(request2.headers.has('x-foo')).toBe(true);
expect(request2.headers.get('x-foo')).toBe('2');
done();
});
});
it('uses default content-type header', (done) => {
fetch.and.returnValue(emptyResponse(200));
let contentType = 'application/octet-stream';
client.defaults = { method: 'post', body: '{}', headers: { 'content-type': contentType } };
client.fetch('path')
.then(() => {
let [request] = fetch.calls.first().args;
expect(request.headers.has('content-type')).toBe(true);
expect(request.headers.get('content-type')).toBe(contentType);
done();
});
});
});
describe('retry', () => {
const originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
beforeEach(() => {
client = new HttpClient();
// fetch = window.fetch = jasmine.createSpy('fetch');
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
});
afterEach(() => {
// fetch = window.fetch = originalFetch as any;
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
});
it('fails if multiple RetryInterceptors are defined', () => {
const configure = () => {
client.configure(config => config.withRetry().withRetry());
};
expect(configure).toThrowError('Only one RetryInterceptor is allowed.');
});
it('fails if RetryInterceptor is not last interceptor defined', () => {
const configure = () => {
client.configure(config => config.withRetry().rejectErrorResponses());
};
expect(configure).toThrowError('The retry interceptor must be the last interceptor defined.');
});
it('retries the specified number of times', (done) => {
let response = new Response(null, { status: 500 });
fetch.and.returnValue(Promise.resolve(response));
client.configure(config => config.rejectErrorResponses().withRetry({
maxRetries: 3,
interval: 10
}));
client.fetch('path')
.then((r) => {
done.fail('fetch did not error');
})
.catch((r) => {
// 1 original call plus 3 retries
expect(fetch).toHaveBeenCalledTimes(4);
done();
});
});
it('continues with retry when doRetry returns true', (done) => {
let response = new Response(null, { status: 500 });
fetch.and.returnValue(Promise.resolve(response));
let doRetryCallback = jasmine.createSpy('doRetry').and.returnValue(true);
client.configure(config => config.rejectErrorResponses().withRetry({
maxRetries: 2,
interval: 10,
doRetry: doRetryCallback
}));
client.fetch('path')
.then((r) => {
done.fail('fetch did not error');
})
.catch((r) => {
// 1 original call plus 2 retries
expect(fetch).toHaveBeenCalledTimes(3);
// only called on retries
expect(doRetryCallback).toHaveBeenCalledTimes(2);
done();
});
});
it('does not retry when doRetry returns false', (done) => {
let response = new Response(null, { status: 500 });
fetch.and.returnValue(Promise.resolve(response));
let doRetryCallback = jasmine.createSpy('doRetry').and.returnValue(false);
client.configure(config => config.rejectErrorResponses().withRetry({
maxRetries: 2,
interval: 10,
doRetry: doRetryCallback
}));
client.fetch('path')
.then((r) => {
done.fail('fetch did not error');
})
.catch((r) => {
// 1 original call plus 0 retries
expect(fetch).toHaveBeenCalledTimes(1);
// only called on retries
expect(doRetryCallback).toHaveBeenCalledTimes(1);
done();
});
});
it('calls beforeRetry callback when specified', (done) => {
let response = new Response(null, { status: 500 });
fetch.and.returnValue(Promise.resolve(response));
let beforeRetryCallback = jasmine.createSpy('beforeRetry').and.returnValue(new Request('path'));
client.configure(config => config.rejectErrorResponses().withRetry({
maxRetries: 2,
interval: 10,
beforeRetry: beforeRetryCallback
}));
return client
.fetch('path')
.then(
() => done.fail('fetch did not error'),
() => {
// 1 original call plus 2 retries
expect(fetch).toHaveBeenCalledTimes(3);
// only called on retries
expect(beforeRetryCallback).toHaveBeenCalledTimes(2);
done();
});
});
it('calls custom retry strategy callback when specified', (done) => {
let response = new Response(null, { status: 500 });
fetch.and.returnValue(Promise.resolve(response));
let strategyRetryCallback = jasmine.createSpy('strategy').and.returnValue(10);
client.configure(config => config.rejectErrorResponses().withRetry({
maxRetries: 2,
strategy: strategyRetryCallback
}));
return client.fetch('path')
.then(
() => done.fail('fetch did not error'),
() => {
// 1 original call plus 2 retries
expect(fetch).toHaveBeenCalledTimes(3);
// only called on retries
expect(strategyRetryCallback).toHaveBeenCalledTimes(2);
done();
});
});
it('waits correct number amount of time with fixed retry strategy', (done) => {
let response = new Response(null, { status: 500 });
fetch.and.returnValue(Promise.resolve(response));
spyOn(PLATFORM.global, 'setTimeout').and.callThrough();
client.configure(config => config.rejectErrorResponses().withRetry({
maxRetries: 2,
interval: 250,
strategy: retryStrategy.fixed
}));
return client.fetch('path')
.then(
() => done.fail('fetch did not error'),
() => {
// setTimeout is called when request starts and end, so those args need to filtered out
const callArgs = (PLATFORM.global.setTimeout as jasmine.Spy).calls.allArgs().filter(args => args[1] > 1);
// only called on retries
expect(callArgs[0]).toEqual([jasmine.any(Function), 250]);
expect(callArgs[1]).toEqual([jasmine.any(Function), 250]);
done();
});
});
it('waits correct number amount of time with incremental retry strategy', (done) => {
let response = new Response(null, { status: 500 });
fetch.and.returnValue(Promise.resolve(response));
spyOn(PLATFORM.global, 'setTimeout').and.callThrough();
client.configure(config => config.rejectErrorResponses().withRetry({
maxRetries: 2,
interval: 250,
strategy: retryStrategy.incremental
}));
return client
.fetch('path')
.then(
() => done.fail('fetch did not error'),
() => {
// setTimeout is called when request starts and end, so those args need to filtered out
const callArgs = (PLATFORM.global.setTimeout as jasmine.Spy).calls.allArgs().filter(args => args[1] > 1);
// only called on retries
expect(callArgs.length).toBe(2);
expect(callArgs[0]).toEqual([jasmine.any(Function), 250]);
expect(callArgs[1]).toEqual([jasmine.any(Function), 500]);
done();
});
});
it('waits correct number amount of time with exponential retry strategy', (done) => {
let response = new Response(null, { status: 500 });
fetch.and.returnValue(Promise.resolve(response));
spyOn(PLATFORM.global, 'setTimeout').and.callThrough();
client.configure(config => config.rejectErrorResponses().withRetry({
maxRetries: 2,
interval: 2000,
strategy: retryStrategy.exponential
}));
return client
.fetch('path')
.then(
() => done.fail('fetch did not error'),
() => {
// setTimeout is called when request starts and end, so those args need to filtered out
const callArgs = (PLATFORM.global.setTimeout as jasmine.Spy).calls.allArgs().filter(args => args[1] > 1);
// only called on retries
expect(callArgs.length).toBe(2);
expect(callArgs[0]).toEqual([jasmine.any(Function), 2000]);
expect(callArgs[1]).toEqual([jasmine.any(Function), 4000]);
done();
});
});
it('waits correct number amount of time with random retry strategy', (done) => {
let response = new Response(null, { status: 500 });
const firstRandom = 0.1;
const secondRandom = 0.4;
fetch.and.returnValue(Promise.resolve(response));
spyOn(PLATFORM.global, 'setTimeout').and.callThrough();
spyOn(Math, 'random').and.returnValues(firstRandom, secondRandom);
client.configure(config => config.rejectErrorResponses().withRetry({
maxRetries: 2,
interval: 2000,
strategy: retryStrategy.random,
minRandomInterval: 1000,
maxRandomInterval: 3000
}));
const firstInterval = firstRandom * (3000 - 1000) + 1000;
const secondInterval = secondRandom * (3000 - 1000) + 1000;
return client
.fetch('path')
.then(
() => done.fail('fetch did not error'),
() => {
// setTimeout is called when request starts and end, so those args need to filtered out
const callArgs = (PLATFORM.global.setTimeout as jasmine.Spy).calls.allArgs().filter(args => args[1] > 1);
// only called on retries
expect(callArgs[0]).toEqual([jasmine.any(Function), firstInterval]);
expect(callArgs[1]).toEqual([jasmine.any(Function), secondInterval]);
done();
}
);
});
it('successfully returns without error if a retry succeeds', (done) => {
let firstResponse = new Response(null, { status: 500 });
let secondResponse = new Response(null, { status: 200 });
fetch.and.returnValues(Promise.resolve(firstResponse), Promise.resolve(secondResponse));
client.configure(config => config.rejectErrorResponses().withRetry({
maxRetries: 3,
interval: 1,
strategy: retryStrategy.fixed
}));
return client.fetch('path')
.then(
(r) => {
// 1 original call plus 1 retry
expect(fetch).toHaveBeenCalledTimes(2);
expect(r).toEqual(secondResponse);
done();
},
() => done.fail('retry was unsuccessful'));
});
});
describe('isRequesting', () => {
it('is set to true when starting a request', (done) => {
fetch.and.returnValue(emptyResponse(200));
expect(client.isRequesting).withContext('Before start').toBe(false);
let request = client.fetch('http://example.com/some/cool/path');
expect(client.isRequesting).withContext('When started').toBe(true);
request.then(() => {
expect(fetch).toHaveBeenCalled();
done();
});
});
it('is set to false when request is finished', (done) => {
fetch.and.returnValue(emptyResponse(200));
expect(client.isRequesting).withContext('Before start').toBe(false);
let request = client.fetch('http://example.com/some/cool/path');
expect(client.isRequesting).withContext('When started').toBe(true);
request.then(() => {
expect(client.isRequesting).withContext('When finished').toBe(false);
}).then(() => {
expect(fetch).toHaveBeenCalled();
done();
});
});
it('is still true when a request is still in progress', (done) => {
let firstResponse = emptyResponse(200)
let secondResponse = new Promise((resolve) => {
setTimeout(() => {
resolve(emptyResponse(200));
}, 200)
});
fetch.and.returnValues(firstResponse, secondResponse);
expect(client.isRequesting).withContext('Before start').toBe(false);
let request1 = client.fetch('http://example.com/some/cool/path');
let request2 = client.fetch('http://example.com/some/cool/path');
expect(client.isRequesting).withContext('When started').toBe(true);
request1.then(() => {
expect(client.isRequesting).withContext('When request 1 is completed').toBe(true);
});
setTimeout(() => {
expect(client.isRequesting).withContext('After 100ms').toBe(true);
}, 100);
request2.then(() => {
expect(client.isRequesting).withContext('When all requests are finished').toBe(false);
}).then(() => {
expect(fetch).toHaveBeenCalledTimes(2);
done();
});
});
it('is set to false when request is rejected', (done) => {
fetch.and.returnValue(Promise.reject(new Error('Failed to fetch')));
expect(client.isRequesting).withContext('Before start').toBe(false);
client.fetch('http://example.com/some/cool/path').then(result => {
expect(result).not.toBe(result);
}).catch((result) => {
expect(result instanceof Error).toBe(true);
expect(result.message).toBe('Failed to fetch');
expect(client.isRequesting).withContext('When finished').toBe(false);
return Promise.resolve();
}).then(() => {
expect(fetch).toHaveBeenCalled();
done();
})
});
it('stays true during a series of retries', (done) => {
let response = new Response(null, { status: 500 });
fetch.and.returnValue(Promise.resolve(response));
client.configure(config => config.rejectErrorResponses().withRetry({
maxRetries: 3,
interval: 100
}));
expect(client.isRequesting).withContext('Before start').toBe(false);
let request = client.fetch('path');
expect(client.isRequesting).withContext('When started').toBe(true);
setTimeout(() => {
expect(client.isRequesting).withContext('After 100ms').toBe(true);
}, 100);
setTimeout(() => {
expect(client.isRequesting).withContext('After 200ms').toBe(true);
}, 200);
request.then((result) => {
done.fail('fetch did not error');
}).catch((r) => {
// 1 original call plus 3 retries
expect(fetch).toHaveBeenCalledTimes(4);
done();
});
});
it('is set to false after a series of retry that fail', (done) => {
let response = new Response(null, { status: 500 });
fetch.and.returnValue(Promise.resolve(response));
client.configure(config => config.rejectErrorResponses().withRetry({
maxRetries: 3,
interval: 100
}));
expect(client.isRequesting).withContext('Before start').toBe(false);
let request = client.fetch('path');
expect(client.isRequesting).withContext('When started').toBe(true);
request.then((result) => {
done.fail('fetch did not error');
}).catch(() => {
// 1 original call plus 3 retries
expect(fetch).toHaveBeenCalledTimes(4);
expect(client.isRequesting).withContext('When finished').toBe(false);
done();
});
});
it('is set to false after a series of retry that fail that succeed', (done) => {
let firstResponse = new Response(null, { status: 500 });
let secondResponse = new Response(null, { status: 200 });
fetch.and.returnValues(Promise.resolve(firstResponse), Promise.resolve(secondResponse));
client.configure(config => config.rejectErrorResponses().withRetry({
maxRetries: 3,
interval: 1,
strategy: retryStrategy.fixed
}));
expect(client.isRequesting).withContext('Before start').toBe(false);
let request = client.fetch('path');
expect(client.isRequesting).withContext('When started').toBe(true);
request.then(() => {
// 1 original call plus 1 retry
expect(fetch).toHaveBeenCalledTimes(2);
expect(client.isRequesting).withContext('When finished').toBe(false);
done();
}).catch((result) => {
done.fail('fetch did error');
});
});
it('forward requests', (done) => {
const path = 'retry';
let retry = 3;
fetch.and.returnValue(Promise.reject(new Response(null, { status: 500 })));
let interceptor: Interceptor = {
response(r) { return r; },
responseError(r) {
if (retry--) {
let request = client.buildRequest(path);
return request;
} else {
throw r;
}
}
};
spyOn(interceptor, 'response').and.callThrough();
spyOn(interceptor, 'responseError').and.callThrough();
client.interceptors.push(interceptor);
// add check before fetch, this one passes.
expect(client.isRequesting).toBe(false);
client.fetch(path)
.catch(() => {
expect(interceptor.response).not.toHaveBeenCalled();
expect(interceptor.responseError).toHaveBeenCalledWith(jasmine.any(Response), jasmine.any(Request), client);
expect(fetch).toHaveBeenCalledTimes(4);
expect(client.activeRequestCount).toBe(0);
expect(client.isRequesting).toBe(false);
done();
});
});
});
});
function emptyResponse(status: number) {
return Promise.resolve(new Response(null, { status }));
} | 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 { useEscapeKeydown } from '@radix-ui/react-use-escape-keydown';
import { usePrevious } from '@radix-ui/react-use-previous';
import { useRect } from '@radix-ui/react-use-rect';
import { Presence } from '@radix-ui/react-presence';
import { Primitive } from '@radix-ui/react-primitive';
import * as PopperPrimitive from '@radix-ui/react-popper';
import { createPopperScope } from '@radix-ui/react-popper';
import { Portal } from '@radix-ui/react-portal';
import { Slottable } from '@radix-ui/react-slot';
import * as VisuallyHiddenPrimitive from '@radix-ui/react-visually-hidden';
import { useId } from '@radix-ui/react-id';
import type * as Radix from '@radix-ui/react-primitive';
import type { Scope } from '@radix-ui/react-context';
type ScopedProps<P = {}> = P & { __scopeTooltip?: Scope };
const [createTooltipContext, createTooltipScope] = createContextScope('Tooltip', [
createPopperScope,
]);
const usePopperScope = createPopperScope();
/* -------------------------------------------------------------------------------------------------
* TooltipProvider
* -----------------------------------------------------------------------------------------------*/
const PROVIDER_NAME = 'TooltipProvider';
const DEFAULT_DELAY_DURATION = 700;
const TOOLTIP_OPEN = 'tooltip.open';
type TooltipProviderContextValue = {
isOpenDelayed: boolean;
delayDuration: number;
onOpen(): void;
onClose(): void;
};
const [TooltipProviderContextProvider, useTooltipProviderContext] =
createTooltipContext<TooltipProviderContextValue>(PROVIDER_NAME, {
isOpenDelayed: true,
delayDuration: DEFAULT_DELAY_DURATION,
onOpen: () => {},
onClose: () => {},
});
interface TooltipProviderProps {
/**
* The duration from when the mouse enters the trigger until the tooltip gets opened.
* @defaultValue 700
*/
delayDuration?: number;
/**
* How much time a user has to enter another trigger without incurring a delay again.
* @defaultValue 300
*/
skipDelayDuration?: number;
children: React.ReactNode;
}
const TooltipProvider: React.FC<TooltipProviderProps> = (
props: ScopedProps<TooltipProviderProps>
) => {
const {
__scopeTooltip,
delayDuration = DEFAULT_DELAY_DURATION,
skipDelayDuration = 300,
children,
} = props;
const [isOpenDelayed, setIsOpenDelayed] = React.useState(true);
const skipDelayTimerRef = React.useRef(0);
React.useEffect(() => {
const skipDelayTimer = skipDelayTimerRef.current;
return () => window.clearTimeout(skipDelayTimer);
}, []);
return (
<TooltipProviderContextProvider
scope={__scopeTooltip}
isOpenDelayed={isOpenDelayed}
delayDuration={delayDuration}
onOpen={React.useCallback(() => {
window.clearTimeout(skipDelayTimerRef.current);
setIsOpenDelayed(false);
}, [])}
onClose={React.useCallback(() => {
window.clearTimeout(skipDelayTimerRef.current);
skipDelayTimerRef.current = window.setTimeout(
() => setIsOpenDelayed(true),
skipDelayDuration
);
}, [skipDelayDuration])}
>
{children}
</TooltipProviderContextProvider>
);
};
TooltipProvider.displayName = PROVIDER_NAME;
/* -------------------------------------------------------------------------------------------------
* Tooltip
* -----------------------------------------------------------------------------------------------*/
const TOOLTIP_NAME = 'Tooltip';
type TooltipContextValue = {
contentId: string;
open: boolean;
stateAttribute: 'closed' | 'delayed-open' | 'instant-open';
trigger: TooltipTriggerElement | null;
onTriggerChange(trigger: TooltipTriggerElement | null): void;
onTriggerEnter(): void;
onOpen(): void;
onClose(): void;
};
const [TooltipContextProvider, useTooltipContext] =
createTooltipContext<TooltipContextValue>(TOOLTIP_NAME);
interface TooltipProps {
open?: boolean;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
/**
* The duration from when the mouse enters the trigger until the tooltip gets opened. This will
* override the prop with the same name passed to Provider.
* @defaultValue 700
*/
delayDuration?: number;
children?: React.ReactNode;
}
const Tooltip: React.FC<TooltipProps> = (props: ScopedProps<TooltipProps>) => {
const {
__scopeTooltip,
children,
open: openProp,
defaultOpen = false,
onOpenChange,
delayDuration: delayDurationProp,
} = props;
const context = useTooltipProviderContext(TOOLTIP_NAME, __scopeTooltip);
const popperScope = usePopperScope(__scopeTooltip);
const [trigger, setTrigger] = React.useState<HTMLButtonElement | null>(null);
const contentId = useId();
const openTimerRef = React.useRef(0);
const delayDuration = delayDurationProp ?? context.delayDuration;
const wasOpenDelayedRef = React.useRef(false);
const { onOpen, onClose } = context;
const [open = false, setOpen] = useControllableState({
prop: openProp,
defaultProp: defaultOpen,
onChange: (open) => {
if (open) {
// we dispatch here so `TooltipProvider` isn't required to
// ensure other tooltips are aware of this one opening.
document.dispatchEvent(new CustomEvent(TOOLTIP_OPEN));
onOpen();
}
onOpenChange?.(open);
},
});
const stateAttribute = React.useMemo(() => {
return open ? (wasOpenDelayedRef.current ? 'delayed-open' : 'instant-open') : 'closed';
}, [open]);
const handleOpen = React.useCallback(() => {
window.clearTimeout(openTimerRef.current);
wasOpenDelayedRef.current = false;
setOpen(true);
}, [setOpen]);
const handleDelayedOpen = React.useCallback(() => {
window.clearTimeout(openTimerRef.current);
openTimerRef.current = window.setTimeout(() => {
wasOpenDelayedRef.current = true;
setOpen(true);
}, delayDuration);
}, [delayDuration, setOpen]);
React.useEffect(() => {
return () => window.clearTimeout(openTimerRef.current);
}, []);
return (
<PopperPrimitive.Root {...popperScope}>
<TooltipContextProvider
scope={__scopeTooltip}
contentId={contentId}
open={open}
stateAttribute={stateAttribute}
trigger={trigger}
onTriggerChange={setTrigger}
onTriggerEnter={React.useCallback(() => {
if (context.isOpenDelayed) handleDelayedOpen();
else handleOpen();
}, [context.isOpenDelayed, handleDelayedOpen, handleOpen])}
onOpen={React.useCallback(handleOpen, [handleOpen])}
onClose={React.useCallback(() => {
window.clearTimeout(openTimerRef.current);
setOpen(false);
onClose();
}, [setOpen, onClose])}
>
{children}
</TooltipContextProvider>
</PopperPrimitive.Root>
);
};
Tooltip.displayName = TOOLTIP_NAME;
/* -------------------------------------------------------------------------------------------------
* TooltipTrigger
* -----------------------------------------------------------------------------------------------*/
const TRIGGER_NAME = 'TooltipTrigger';
type TooltipTriggerElement = React.ElementRef<typeof Primitive.button>;
type PrimitiveButtonProps = Radix.ComponentPropsWithoutRef<typeof Primitive.button>;
interface TooltipTriggerProps extends PrimitiveButtonProps {}
const TooltipTrigger = React.forwardRef<TooltipTriggerElement, TooltipTriggerProps>(
(props: ScopedProps<TooltipTriggerProps>, forwardedRef) => {
const { __scopeTooltip, ...triggerProps } = props;
const context = useTooltipContext(TRIGGER_NAME, __scopeTooltip);
const popperScope = usePopperScope(__scopeTooltip);
const composedTriggerRef = useComposedRefs(forwardedRef, context.onTriggerChange);
const isMouseDownRef = React.useRef(false);
const handleMouseUp = React.useCallback(() => (isMouseDownRef.current = false), []);
React.useEffect(() => {
return () => document.removeEventListener('mouseup', handleMouseUp);
}, [handleMouseUp]);
return (
<PopperPrimitive.Anchor asChild {...popperScope}>
<Primitive.button
// We purposefully avoid adding `type=button` here because tooltip triggers are also
// commonly anchors and the anchor `type` attribute signifies MIME type.
aria-describedby={context.open ? context.contentId : undefined}
data-state={context.stateAttribute}
{...triggerProps}
ref={composedTriggerRef}
onMouseEnter={composeEventHandlers(props.onMouseEnter, context.onTriggerEnter)}
onMouseLeave={composeEventHandlers(props.onMouseLeave, context.onClose)}
onMouseDown={composeEventHandlers(props.onMouseDown, () => {
context.onClose();
isMouseDownRef.current = true;
document.addEventListener('mouseup', handleMouseUp, { once: true });
})}
onFocus={composeEventHandlers(props.onFocus, () => {
if (!isMouseDownRef.current) context.onOpen();
})}
onBlur={composeEventHandlers(props.onBlur, context.onClose)}
// Handle anything that the browser considers a click for the element type if
// not using pointer e.g. Space keyup and Enter keydown
onClick={composeEventHandlers(props.onClick, context.onClose)}
/>
</PopperPrimitive.Anchor>
);
}
);
TooltipTrigger.displayName = TRIGGER_NAME;
/* -------------------------------------------------------------------------------------------------
* TooltipContent
* -----------------------------------------------------------------------------------------------*/
const CONTENT_NAME = 'TooltipContent';
type TooltipContentElement = TooltipContentImplElement;
interface TooltipContentProps extends TooltipContentImplProps {
/**
* Used to force mounting when more control is needed. Useful when
* controlling animation with React animation libraries.
*/
forceMount?: true;
}
const TooltipContent = React.forwardRef<TooltipContentElement, TooltipContentProps>(
(props: ScopedProps<TooltipContentProps>, forwardedRef) => {
const { forceMount, ...contentProps } = props;
const context = useTooltipContext(CONTENT_NAME, props.__scopeTooltip);
return (
<Presence present={forceMount || context.open}>
<TooltipContentImpl ref={forwardedRef} {...contentProps} />
</Presence>
);
}
);
type TooltipContentImplElement = React.ElementRef<typeof PopperPrimitive.Content>;
type PopperContentProps = Radix.ComponentPropsWithoutRef<typeof PopperPrimitive.Content>;
interface TooltipContentImplProps extends PopperContentProps {
/**
* A more descriptive label for accessibility purpose
*/
'aria-label'?: string;
/**
* Whether the Tooltip should render in a Portal
* (default: `true`)
*/
portalled?: boolean;
}
const TooltipContentImpl = React.forwardRef<TooltipContentImplElement, TooltipContentImplProps>(
(props: ScopedProps<TooltipContentImplProps>, forwardedRef) => {
const {
__scopeTooltip,
children,
'aria-label': ariaLabel,
portalled = true,
...contentProps
} = props;
const context = useTooltipContext(CONTENT_NAME, __scopeTooltip);
const popperScope = usePopperScope(__scopeTooltip);
const PortalWrapper = portalled ? Portal : React.Fragment;
const { onClose } = context;
useEscapeKeydown(() => onClose());
React.useEffect(() => {
// Close this tooltip if another one opens
document.addEventListener(TOOLTIP_OPEN, onClose);
return () => document.removeEventListener(TOOLTIP_OPEN, onClose);
}, [onClose]);
return (
<PortalWrapper>
<CheckTriggerMoved __scopeTooltip={__scopeTooltip} />
<PopperPrimitive.Content
data-state={context.stateAttribute}
{...popperScope}
{...contentProps}
ref={forwardedRef}
style={{
...contentProps.style,
// re-namespace exposed content custom property
['--radix-tooltip-content-transform-origin' as any]:
'var(--radix-popper-transform-origin)',
}}
>
<Slottable>{children}</Slottable>
<VisuallyHiddenPrimitive.Root id={context.contentId} role="tooltip">
{ariaLabel || children}
</VisuallyHiddenPrimitive.Root>
</PopperPrimitive.Content>
</PortalWrapper>
);
}
);
TooltipContent.displayName = CONTENT_NAME;
/* -------------------------------------------------------------------------------------------------
* TooltipArrow
* -----------------------------------------------------------------------------------------------*/
const ARROW_NAME = 'TooltipArrow';
type TooltipArrowElement = React.ElementRef<typeof PopperPrimitive.Arrow>;
type PopperArrowProps = Radix.ComponentPropsWithoutRef<typeof PopperPrimitive.Arrow>;
interface TooltipArrowProps extends PopperArrowProps {}
const TooltipArrow = React.forwardRef<TooltipArrowElement, TooltipArrowProps>(
(props: ScopedProps<TooltipArrowProps>, forwardedRef) => {
const { __scopeTooltip, ...arrowProps } = props;
const popperScope = usePopperScope(__scopeTooltip);
return <PopperPrimitive.Arrow {...popperScope} {...arrowProps} ref={forwardedRef} />;
}
);
TooltipArrow.displayName = ARROW_NAME;
/* -----------------------------------------------------------------------------------------------*/
function CheckTriggerMoved(props: ScopedProps<{}>) {
const { __scopeTooltip } = props;
const context = useTooltipContext('CheckTriggerMoved', __scopeTooltip);
const triggerRect = useRect(context.trigger);
const triggerLeft = triggerRect?.left;
const previousTriggerLeft = usePrevious(triggerLeft);
const triggerTop = triggerRect?.top;
const previousTriggerTop = usePrevious(triggerTop);
const handleClose = context.onClose;
React.useEffect(() => {
// checking if the user has scrolled…
const hasTriggerMoved =
(previousTriggerLeft !== undefined && previousTriggerLeft !== triggerLeft) ||
(previousTriggerTop !== undefined && previousTriggerTop !== triggerTop);
if (hasTriggerMoved) {
handleClose();
}
}, [handleClose, previousTriggerLeft, previousTriggerTop, triggerLeft, triggerTop]);
return null;
}
const Provider = TooltipProvider;
const Root = Tooltip;
const Trigger = TooltipTrigger;
const Content = TooltipContent;
const Arrow = TooltipArrow;
export {
createTooltipScope,
//
TooltipProvider,
Tooltip,
TooltipTrigger,
TooltipContent,
TooltipArrow,
//
Provider,
Root,
Trigger,
Content,
Arrow,
};
export type { TooltipProps, TooltipTriggerProps, TooltipContentProps, TooltipArrowProps }; | the_stack |
import { EventDispatcher, TypedDispatcher } from "./dispatcher";
import { BluetoothDevice, BluetoothDeviceEvents } from "./device";
import { getServiceUUID } from "./helpers";
import { adapter, NobleAdapter } from "./adapter";
import { W3CBluetooth } from "./interfaces";
import { DOMEvent } from "./events";
/**
* Bluetooth Options interface
*/
export interface BluetoothOptions {
/**
* A `device found` callback function to allow the user to select a device
*/
deviceFound?: (device: BluetoothDevice, selectFn: () => void) => boolean;
/**
* The amount of seconds to scan for the device (default is 10)
*/
scanTime?: number;
/**
* An optional referring device
*/
referringDevice?: BluetoothDevice;
}
/**
* @hidden
*/
export interface BluetoothEvents extends BluetoothDeviceEvents {
/**
* Bluetooth Availability Changed event
*/
availabilitychanged: Event;
}
/**
* Bluetooth class
*/
export class Bluetooth extends (EventDispatcher as new() => TypedDispatcher<BluetoothEvents>) implements W3CBluetooth {
/**
* Bluetooth Availability Changed event
* @event
*/
public static EVENT_AVAILABILITY: string = "availabilitychanged";
/**
* Referring device for the bluetooth instance
*/
public readonly referringDevice?: BluetoothDevice;
private deviceFound: (device: BluetoothDevice, selectFn: () => void) => boolean = null;
private scanTime: number = 10.24 * 1000;
private scanner = null;
private _oncharacteristicvaluechanged: (ev: Event) => void;
public set oncharacteristicvaluechanged(fn: (ev: Event) => void) {
if (this._oncharacteristicvaluechanged) {
this.removeEventListener("characteristicvaluechanged", this._oncharacteristicvaluechanged);
}
this._oncharacteristicvaluechanged = fn;
this.addEventListener("characteristicvaluechanged", this._oncharacteristicvaluechanged);
}
private _onserviceadded: (ev: Event) => void;
public set onserviceadded(fn: (ev: Event) => void) {
if (this._onserviceadded) {
this.removeEventListener("serviceadded", this._onserviceadded);
}
this._onserviceadded = fn;
this.addEventListener("serviceadded", this._onserviceadded);
}
private _onservicechanged: (ev: Event) => void;
public set onservicechanged(fn: (ev: Event) => void) {
if (this._onservicechanged) {
this.removeEventListener("servicechanged", this._onservicechanged);
}
this._onservicechanged = fn;
this.addEventListener("servicechanged", this._onservicechanged);
}
private _onserviceremoved: (ev: Event) => void;
public set onserviceremoved(fn: (ev: Event) => void) {
if (this._onserviceremoved) {
this.removeEventListener("serviceremoved", this._onserviceremoved);
}
this._onserviceremoved = fn;
this.addEventListener("serviceremoved", this._onserviceremoved);
}
private _ongattserverdisconnected: (ev: Event) => void;
public set ongattserverdisconnected(fn: (ev: Event) => void) {
if (this._ongattserverdisconnected) {
this.removeEventListener("gattserverdisconnected", this._ongattserverdisconnected);
}
this._ongattserverdisconnected = fn;
this.addEventListener("gattserverdisconnected", this._ongattserverdisconnected);
}
private _onadvertisementreceived: (ev: Event) => void;
public set onadvertisementreceived(fn: (ev: Event) => void) {
if (this._onadvertisementreceived) {
this.removeEventListener("advertisementreceived", this._onadvertisementreceived);
}
this._onadvertisementreceived = fn;
this.addEventListener("advertisementreceived", this._onadvertisementreceived);
}
private _onavailabilitychanged: (ev: Event) => void;
public set onavailabilitychanged(fn: (ev: Event) => void) {
if (this._onavailabilitychanged) {
this.removeEventListener("availabilitychanged", this._onavailabilitychanged);
}
this._onavailabilitychanged = fn;
this.addEventListener("availabilitychanged", this._onavailabilitychanged);
}
/**
* Bluetooth constructor
* @param options Bluetooth initialisation options
*/
constructor(options?: BluetoothOptions) {
super();
options = options || {};
this.referringDevice = options.referringDevice;
this.deviceFound = options.deviceFound;
if (options.scanTime) this.scanTime = options.scanTime * 1000;
adapter.on(NobleAdapter.EVENT_ENABLED, _value => {
this.dispatchEvent(new DOMEvent(this, "availabilitychanged"));
});
}
private filterDevice(filters: Array<BluetoothRequestDeviceFilter>, deviceInfo, validServices) {
let valid = false;
filters.forEach(filter => {
// Name
if (filter.name && filter.name !== deviceInfo.name) return;
// NamePrefix
if (filter.namePrefix) {
if (!deviceInfo.name || filter.namePrefix.length > deviceInfo.name.length) return;
if (filter.namePrefix !== deviceInfo.name.substr(0, filter.namePrefix.length)) return;
}
// Services
if (filter.services) {
const serviceUUIDs = filter.services.map(getServiceUUID);
const servicesValid = serviceUUIDs.every(serviceUUID => {
return (deviceInfo._serviceUUIDs.indexOf(serviceUUID) > -1);
});
if (!servicesValid) return;
validServices = validServices.concat(serviceUUIDs);
}
valid = true;
});
if (!valid) return false;
return deviceInfo;
}
/**
* Gets the availability of a bluetooth adapter
* @returns Promise containing a flag indicating bluetooth availability
*/
public getAvailability(): Promise<boolean> {
return new Promise((resolve, _reject) => {
adapter.getEnabled(enabled => {
resolve(enabled);
});
});
}
/**
* Scans for a device matching optional filters
* @param options The options to use when scanning
* @returns Promise containing a device which matches the options
*/
public requestDevice(options: RequestDeviceOptions = { filters: [] }): Promise<BluetoothDevice> {
return new Promise((resolve, reject) => {
if (this.scanner !== null) return reject("requestDevice error: request in progress");
interface Filtered {
filters: Array<BluetoothRequestDeviceFilter>;
optionalServices?: Array<BluetoothServiceUUID>;
}
interface AcceptAll {
acceptAllDevices: boolean;
optionalServices?: Array<BluetoothServiceUUID>;
}
const isFiltered = (maybeFiltered: RequestDeviceOptions): maybeFiltered is Filtered =>
(maybeFiltered as Filtered).filters !== undefined;
const isAcceptAll = (maybeAcceptAll: RequestDeviceOptions): maybeAcceptAll is AcceptAll =>
(maybeAcceptAll as AcceptAll).acceptAllDevices === true;
let searchUUIDs = [];
if (isFiltered(options)) {
// Must have a filter
if (options.filters.length === 0) {
return reject(new TypeError("requestDevice error: no filters specified"));
}
// Don't allow empty filters
const emptyFilter = options.filters.some(filter => {
return (Object.keys(filter).length === 0);
});
if (emptyFilter) {
return reject(new TypeError("requestDevice error: empty filter specified"));
}
// Don't allow empty namePrefix
const emptyPrefix = options.filters.some(filter => {
return (typeof filter.namePrefix !== "undefined" && filter.namePrefix === "");
});
if (emptyPrefix) {
return reject(new TypeError("requestDevice error: empty namePrefix specified"));
}
options.filters.forEach(filter => {
if (filter.services) searchUUIDs = searchUUIDs.concat(filter.services.map(getServiceUUID));
// Unique-ify
searchUUIDs = searchUUIDs.filter((item, index, array) => {
return array.indexOf(item) === index;
});
});
} else if (!isAcceptAll(options)) {
return reject(new TypeError("requestDevice error: specify filters or acceptAllDevices"));
}
let found = false;
adapter.startScan(searchUUIDs, deviceInfo => {
let validServices = [];
function complete(bluetoothDevice) {
this.cancelRequest()
.then(() => {
resolve(bluetoothDevice);
});
}
// filter devices if filters specified
if (isFiltered(options)) {
deviceInfo = this.filterDevice(options.filters, deviceInfo, validServices);
}
if (deviceInfo) {
found = true;
// Add additional services
if (options.optionalServices) {
validServices = validServices.concat(options.optionalServices.map(getServiceUUID));
}
// Set unique list of allowed services
const allowedServices = validServices.filter((item, index, array) => {
return array.indexOf(item) === index;
});
Object.assign(deviceInfo, {
_bluetooth: this,
_allowedServices: allowedServices
});
const bluetoothDevice = new BluetoothDevice(deviceInfo);
function selectFn() {
complete.call(this, bluetoothDevice);
}
if (!this.deviceFound || this.deviceFound(bluetoothDevice, selectFn.bind(this)) === true) {
// If no deviceFound function, or deviceFound returns true, resolve with this device immediately
complete.call(this, bluetoothDevice);
}
}
}, () => {
this.scanner = setTimeout(() => {
this.cancelRequest()
.then(() => {
if (!found) reject("requestDevice error: no devices found");
});
}, this.scanTime);
}, error => reject(`requestDevice error: ${error}`));
});
}
/**
* Cancels the scan for devices
*/
public cancelRequest(): Promise<void> {
return new Promise((resolve, _reject) => {
if (this.scanner) {
clearTimeout(this.scanner);
this.scanner = null;
adapter.stopScan();
}
resolve();
});
}
} | the_stack |
import type { AwsMethod } from "./api";
const BASE_URL = process.env.FUNCTIONLESS_LOCAL
? `http://localhost:3000`
: `https://functionless.org`;
/**
* Error to throw during synth failures
*/
export class SynthError extends Error {
constructor(readonly code: ErrorCode, message?: string) {
super(formatErrorMessage(code, message));
}
}
/**
* Formats an error message consistently across Functionless.
*
* Includes a deep link url to functionless.org's error code page.
*
* ```
* [messageText | code.MessageText]
*
* http://functionless.org/docs/error-codes/#[Anchor from Message Text]
* ```
*/
export const formatErrorMessage = (code: ErrorCode, messageText?: string) => `${
messageText ?? code.title
}
${formatErrorUrl(code)}`;
/**
* Deep link to functionless.org's error code page.
*
* `http://functionless.org/docs/error-codes/#[Anchor from Message Text]`
*/
export const formatErrorUrl = (code: ErrorCode) =>
`${BASE_URL}/docs/error-codes#${code.title
.toLowerCase()
.replace(/\s/g, "-")}`;
export enum ErrorType {
"ERROR" = "ERROR",
"WARN" = "WARN",
"INFO" = "INFO",
"DEPRECATED" = "DEPRECATED",
}
export interface ErrorCode {
/**
* Error code, a unique number between 10000 and 99999.
*
* New error codes should be sequential.
*/
readonly code: number;
/**
* The type of the error, determine how the error is displayed in the language service and on the website.
*/
readonly type: ErrorType;
/**
* Title of the error which will appear on `https://functionless.org/docs/error-codes` and act as the deep link.
* (https://functionless.org/docs/error-codes#title-with-dashes)
*/
readonly title: string;
}
export namespace ErrorCodes {
/**
* The computations that [Amazon States Language](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-amazon-states-language.html)
* can do is restricted by JSON Path and the limited [Intrinsic Functions](https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-intrinsic-functions.html). Currently, arithmetic expressions are not supported.
* ```ts
* // ok
* new StepFunction(scope, id, () => 1 + 2);
*
* // illegal!
* new StepFunction(scope, id, (input: { num: number }) => input.number + 1);
* ```
*
* To workaround, use a Lambda Function to implement the arithmetic expression. Be aware that this comes with added cost and operational risk.
*
* ```ts
* const add = new Function(scope, "add", (input: { a: number, b: number }) => input.a + input.b);
*
* new StepFunction(scope, id, async (input: { num: number }) => {
* await add({a: input.number, b: 1});
* });
* ```
*/
export const Cannot_perform_arithmetic_on_variables_in_Step_Function: ErrorCode =
{
code: 10000,
type: ErrorType.ERROR,
title: "Cannot perform arithmetic on variables in Step Function",
};
/**
* During CDK synth a function was encountered which was not compiled by the Functionless compiler plugin.
* This suggests that the plugin was not correctly configured for this project.
*
* Ensure you follow the instructions at https://functionless.org/docs/getting-started.
*/
export const FunctionDecl_not_compiled_by_Functionless: ErrorCode = {
code: 10001,
type: ErrorType.ERROR,
title: "Function not compiled by Functionless plugin",
};
/**
* The argument must be an inline Function.
*
* ```ts
* const func = () => {
* // ..
* }
* // invalid - `func` must be an inline Function
* new Function(this, id, func);
* ```
*
* To fix, inline the `func` implementation.
*
* ```ts
* // option 1 - arrow function
* new Function(this, id, async () => { .. });
*
* // option 2 - function
* new Function(this, id, async function () { .. });
* ```
*/
export const Argument_must_be_an_inline_Function: ErrorCode = {
code: 10002,
type: ErrorType.ERROR,
title: `Argument must be an inline Function`,
};
/**
* When using the {@link AwsMethod}, the `request` argument must be a function
* with exactly one integration call.
*
* ```ts
* new AwsMethod(
* {
* httpMethod: "GET",
* resource: api.root
* },
* ($input) => {
* return $AWS.DynamoDB.GetItem({ .. });
* },
* // etc.
* )
* ```
*/
export const AwsMethod_request_must_have_exactly_one_integration_call: ErrorCode =
{
code: 10003,
type: ErrorType.ERROR,
title: `AwsMethod request must have exactly one integration call`,
};
/**
* Lambda Function closure synthesis runs async, but CDK does not normally support async.
*
* In order for the synthesis to complete successfully
* 1. Use autoSynth `new App({ authSynth: true })` or `new App()` with the CDK Cli (`cdk synth`)
* 2. Use `await asyncSynth(app)` exported from Functionless in place of `app.synth()`
* 3. Manually await on the closure serializer promises `await Promise.all(Function.promises)`
*
* https://github.com/functionless/functionless/issues/128
*/
export const Function_Closure_Serialization_Incomplete: ErrorCode = {
code: 10004,
type: ErrorType.ERROR,
title: "Function closure serialization was not allowed to complete",
};
/**
* Generic error message to denote errors that should not happen and are not the fault of the Functionless library consumer.
*
* Please report this issue
*/
export const Unexpected_Error: ErrorCode = {
code: 10005,
type: ErrorType.ERROR,
title: "Unexpected Error, please report this issue",
};
/**
* Incorrect State Machine Type Imported
*
* Functionless {@link StepFunction}s are separated into {@link ExpressStepFunction} and {@link StepFunction}
* based on being {@link aws_stepfunctions.StateMachineType.EXPRESS} or {@link aws_stepfunctions.StateMachineType.STANDARD}
* respectively.
*
* In order to ensure correct function of Functionless integrations, the correct import statement must be used.
*
* ```ts
* const sfn = new aws_stepfunctions.StateMachine(scope, 'standardMachine', {...});
* // valid
* StateMachine.fromStepFunction(sfn);
* // invalid - not an express machine
* ExpressStateMachine.fromStepFunction(sfn);
*
* const exprSfn = new aws_stepfunctions.StateMachine(scope, 'standardMachine', {
* stateMachineType: aws_stepfunctions.StateMachineType.EXPRESS,
* });
* // valid
* ExpressStateMachine.fromStepFunction(exprSfn);
* // invalid - not a standard machine
* StateMachine.fromStepFunction(exprSfn);
* ```
*/
export const Incorrect_StateMachine_Import_Type: ErrorCode = {
code: 10006,
type: ErrorType.ERROR,
title: "Incorrect state machine type imported",
};
/**
* Unsafe usage of Secrets.
*
* The use of secrets is unsafe or not supported by Functionless.
*
* @see https://github.com/functionless/functionless/issues/252 to track supported secret patterns.
*/
export const Unsafe_use_of_secrets: ErrorCode = {
code: 10007,
type: ErrorType.ERROR,
title: "Unsafe use of secrets",
};
/**
* Unsupported initialization of Resources in a Function closure
*
* 1. Valid - EventBus resource is created outside of the closure.
* ```ts
* const bus = new EventBus(this, 'bus');
* const function = new Function(this, 'func', () => {
* bus.putEvents(...);
* });
* ```
*
* 2. Invalid - EventBus resource is created in the closure.
* ```ts
* const function = new Function(this, 'func', () => {
* new EventBus(this, 'bus').putEvents(...);
* });
* ```
*
* 3. Invalid - EventBus resource is created in a method called by the closure.
* ```ts
* function bus() {
* return new EventBus(this, 'bus');
* }
* const function = new Function(this, 'func', () => {
* bus().putEvents(...);
* });
* ```
*
* 4. Valid - EventBus resource is created outside of the closure and called methods.
* ```ts
* const bus = new EventBus(this, 'bus');
* function bus() {
* return bus;
* }
* const function = new Function(this, 'func', () => {
* bus().putEvents(...);
* });
* ```
*/
export const Unsupported_initialization_of_resources_in_function: ErrorCode =
{
code: 10008,
type: ErrorType.ERROR,
title: "Unsupported initialization of Resources in a Function closure",
};
/**
* Cannot use Infrastructure resource in Function closure.
*
* The `.resource` property of `Function`, `StepFunction`, `ExpressStepFunction`, `EventBus`, and `Table` are not available
* in Native Function Closures.
*
* ```ts
* const table = new Table(this, 'table', { ... });
* new Function(this, 'func', async () => {
* // valid use of a Table
* const $AWS.DynamoDB.GetItem({
* TableName: table,
* ...
* })
* // invalid - .resource is not available
* const index = table.resource.tableStreamArn;
* });
* ```
*
* ### Workaround - Functionless Resource Properties
*
* In many cases, common properties are available on the Functionless Resource, for example:
*
* ```ts
* const table = new Table(this, 'table', { ... });
* new Function(this, 'func', async () => {
* const tableArn = table.tableArn;
* });
* ```
*
* ### Workaround - Dereference
*
* For some properties, referencing to a variable outside of the closure will work.
*
* ```ts
* const table = new Table(this, 'table', { ... });
* const tableStreamArn = table.resource.tableStreamArn;
* new Function(this, 'func', async () => {
* const tableStreamArn = tableStreamArn;
* });
* ```
*
* ### Workaround - Environment Variable
*
* Finally, if none of the above work, the lambda environment variables can be used.
*
* ```ts
* const table = new Table(this, 'table', { ... });
* new Function(this, 'func', {
* environment: {
* STREAM_ARN: table.resource.tableStreamArn
* }
* }, async () => {
* const tableStreamArn = process.env.STREAM_ARN;
* });
* ```
*/
export const Cannot_use_infrastructure_Resource_in_Function_closure: ErrorCode =
{
code: 10009,
type: ErrorType.ERROR,
title: "Cannot use infrastructure Resource in Function closure",
};
/**
* Computed Property Names are not supported in API Gateway.
*
* For example:
* ```ts
* new AwsMethod({
* request: ($input) => $AWS.DynamoDB.GetItem({
* TableName: table,
* // invalid, all property names must be literals
* [computedProperty]: prop
* })
* });
* ```
*
* To workaround, be sure to only use literal property names.
*/
export const API_Gateway_does_not_support_computed_property_names: ErrorCode =
{
code: 10010,
type: ErrorType.ERROR,
title: "API Gateway does not supported computed property names",
};
/**
* Due to limitations in API Gateway's VTL engine (no $util.toJson, for example)
* it is not possible to fully support spread expressions.
*
* For example:
* ```ts
* new AwsMethod({
* response: ($input) => ({
* hello: "world",
* ...$input.data
* })
* });
* ```
*
* To workaround the limitation, explicitly specify each property.
*
* ```ts
* new AwsMethod({
* response: ($input) => ({
* hello: "world",
* propA: $input.data.propA,
* propB: $input.data.propB,
* })
* });
* ```
*/
export const API_Gateway_does_not_support_spread_assignment_expressions: ErrorCode =
{
code: 10011,
type: ErrorType.ERROR,
title: "API Gateway does not support spread assignment expressions",
};
/**
* Due to limitations in respective Functionless interpreters, it is often a
* requirement to specify an object literal instead of a variable reference.
*
* ```ts
* const input = {
* TableName: table,
* Key: {
* // etc.
* }
* };
* // invalid - input must be an object literal
* $AWS.DynamoDB.GetItem(input)
* ```
*
* To work around, ensure that you specify an object literal.
*
* ```ts
* $AWS.DynamoDB.GetItem({
* TableName: table,
* Key: {
* // etc.
* }
* })
* ```
*/
export const Expected_an_object_literal: ErrorCode = {
code: 10012,
type: ErrorType.ERROR,
title: "Expected_an_object_literal",
};
/**
* Code running within an API Gateway's response mapping template must not attempt
* to call any integration. It can only perform data transformation.
*
* ```ts
* new AwsMethod({
* ...,
*
* response: () => {
* // INVALID! - you cannot call an integration from within a response mapping template
* return $AWS.DynamoDB.GetItem({
* TableName: table,
* ...
* });
* }
* })
* ```
*
* To workaround, make sure to only call an integration from within the `request` mapping function.
*/
export const API_gateway_response_mapping_template_cannot_call_integration: ErrorCode =
{
code: 10013,
type: ErrorType.ERROR,
title: "API gateway response mapping template cannot call integration",
};
} | the_stack |
export const numberToBinUintLE = (value: number) => {
const baseUint8Array = 256;
const result: number[] = [];
// eslint-disable-next-line functional/no-let
let remaining = value;
// eslint-disable-next-line functional/no-loop-statement
while (remaining >= baseUint8Array) {
// eslint-disable-next-line functional/no-expression-statement, functional/immutable-data
result.push(remaining % baseUint8Array);
// eslint-disable-next-line functional/no-expression-statement
remaining = Math.floor(remaining / baseUint8Array);
}
// eslint-disable-next-line functional/no-conditional-statement, functional/no-expression-statement, functional/immutable-data
if (remaining > 0) result.push(remaining);
return Uint8Array.from(result);
};
/**
* Fill a new Uint8Array of a specific byte-length with the contents of a given
* Uint8Array, truncating or padding the Uint8Array with zeros.
*
* @param bin - the Uint8Array to resize
* @param bytes - the desired byte-length
*/
export const binToFixedLength = (bin: Uint8Array, bytes: number) => {
const fixedBytes = new Uint8Array(bytes);
const maxValue = 255;
// eslint-disable-next-line functional/no-expression-statement
bin.length > bytes ? fixedBytes.fill(maxValue) : fixedBytes.set(bin);
// TODO: re-enable eslint-disable-next-line @typescript-eslint/no-unused-expressions
return fixedBytes;
};
/**
* Encode a positive integer as a 2-byte Uint16LE Uint8Array, clamping the
* results. (Values exceeding `0xffff` return the same result as `0xffff`,
* negative values will return the same result as `0`.)
*
* @param value - the number to encode
*/
export const numberToBinUint16LEClamped = (value: number) => {
const uint16 = 2;
return binToFixedLength(numberToBinUintLE(value), uint16);
};
/**
* Encode a positive integer as a 4-byte Uint32LE Uint8Array, clamping the
* results. (Values exceeding `0xffffffff` return the same result as
* `0xffffffff`, negative values will return the same result as `0`.)
*
* @param value - the number to encode
*/
export const numberToBinUint32LEClamped = (value: number) => {
const uint32 = 4;
return binToFixedLength(numberToBinUintLE(value), uint32);
};
/**
* Encode a positive integer as a 2-byte Uint16LE Uint8Array.
*
* This method will return an incorrect result for values outside of the range
* `0` to `0xffff`.
*
* @param value - the number to encode
*/
export const numberToBinUint16LE = (value: number) => {
const uint16Length = 2;
const bin = new Uint8Array(uint16Length);
const writeAsLittleEndian = true;
const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);
// eslint-disable-next-line functional/no-expression-statement
view.setUint16(0, value, writeAsLittleEndian);
return bin;
};
/**
* Encode an integer as a 2-byte Int16LE Uint8Array.
*
* This method will return an incorrect result for values outside of the range
* `0x0000` to `0xffff`.
*
* @param value - the number to encode
*/
export const numberToBinInt16LE = (value: number) => {
const int16Length = 2;
const bin = new Uint8Array(int16Length);
const writeAsLittleEndian = true;
const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);
// eslint-disable-next-line functional/no-expression-statement
view.setInt16(0, value, writeAsLittleEndian);
return bin;
};
/**
* Encode an integer as a 4-byte Uint32LE Uint8Array.
*
* This method will return an incorrect result for values outside of the range
* `0x00000000` to `0xffffffff`.
*
* @param value - the number to encode
*/
export const numberToBinInt32LE = (value: number) => {
const int32Length = 4;
const bin = new Uint8Array(int32Length);
const writeAsLittleEndian = true;
const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);
// eslint-disable-next-line functional/no-expression-statement
view.setInt32(0, value, writeAsLittleEndian);
return bin;
};
/**
* Decode a 2-byte Int16LE Uint8Array into a number.
*
* Throws if `bin` is shorter than 2 bytes.
*
* @param bin - the Uint8Array to decode
*/
export const binToNumberInt16LE = (bin: Uint8Array) => {
const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);
const readAsLittleEndian = true;
return view.getInt16(0, readAsLittleEndian);
};
/**
* Decode a 4-byte Int32LE Uint8Array into a number.
*
* Throws if `bin` is shorter than 4 bytes.
*
* @param bin - the Uint8Array to decode
*/
export const binToNumberInt32LE = (bin: Uint8Array) => {
const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);
const readAsLittleEndian = true;
return view.getInt32(0, readAsLittleEndian);
};
/**
* Encode a positive integer as a 2-byte Uint16LE Uint8Array.
*
* This method will return an incorrect result for values outside of the range
* `0` to `0xffff`.
*
* @param value - the number to encode
*/
export const numberToBinUint16BE = (value: number) => {
const uint16Length = 2;
const bin = new Uint8Array(uint16Length);
const writeAsLittleEndian = false;
const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);
// eslint-disable-next-line functional/no-expression-statement
view.setUint16(0, value, writeAsLittleEndian);
return bin;
};
/**
* Encode a positive number as a 4-byte Uint32LE Uint8Array.
*
* This method will return an incorrect result for values outside of the range
* `0` to `0xffffffff`.
*
* @param value - the number to encode
*/
export const numberToBinUint32LE = (value: number) => {
const uint32Length = 4;
const bin = new Uint8Array(uint32Length);
const writeAsLittleEndian = true;
const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);
// eslint-disable-next-line functional/no-expression-statement
view.setUint32(0, value, writeAsLittleEndian);
return bin;
};
/**
* Encode a positive number as a 4-byte Uint32BE Uint8Array.
*
* This method will return an incorrect result for values outside of the range
* `0` to `0xffffffff`.
*
* @param value - the number to encode
*/
export const numberToBinUint32BE = (value: number) => {
const uint32Length = 4;
const bin = new Uint8Array(uint32Length);
const writeAsLittleEndian = false;
const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);
// eslint-disable-next-line functional/no-expression-statement
view.setUint32(0, value, writeAsLittleEndian);
return bin;
};
/**
* Encode a positive BigInt as little-endian Uint8Array. Negative values will
* return the same result as `0`.
*
* @param value - the number to encode
*/
export const bigIntToBinUintLE = (value: bigint) => {
const baseUint8Array = 256;
const base = BigInt(baseUint8Array);
const result: number[] = [];
// eslint-disable-next-line functional/no-let
let remaining = value;
// eslint-disable-next-line functional/no-loop-statement
while (remaining >= base) {
// eslint-disable-next-line functional/no-expression-statement, functional/immutable-data
result.push(Number(remaining % base));
// eslint-disable-next-line functional/no-expression-statement
remaining /= base;
}
// eslint-disable-next-line functional/no-conditional-statement, functional/no-expression-statement, functional/immutable-data
if (remaining > BigInt(0)) result.push(Number(remaining));
return Uint8Array.from(result.length > 0 ? result : [0]);
};
/**
* Encode a positive BigInt as an 8-byte Uint64LE Uint8Array, clamping the
* results. (Values exceeding `0xffff_ffff_ffff_ffff` return the same result as
* `0xffff_ffff_ffff_ffff`, negative values return the same result as `0`.)
*
* @param value - the number to encode
*/
export const bigIntToBinUint64LEClamped = (value: bigint) => {
const uint64 = 8;
return binToFixedLength(bigIntToBinUintLE(value), uint64);
};
/**
* Encode a positive BigInt as an 8-byte Uint64LE Uint8Array.
*
* This method will return an incorrect result for values outside of the range
* `0` to `0xffff_ffff_ffff_ffff`.
*
* @param value - the number to encode
*/
export const bigIntToBinUint64LE = (value: bigint) => {
const uint64LengthInBits = 64;
const valueAsUint64 = BigInt.asUintN(uint64LengthInBits, value);
const fixedLengthBin = bigIntToBinUint64LEClamped(valueAsUint64);
return fixedLengthBin;
};
/**
* Encode an integer as a 4-byte, little-endian Uint8Array using the number's
* two's compliment representation (the format used by JavaScript's bitwise
* operators).
*
* @remarks
* The C++ bitcoin implementations sometimes represent short vectors using
* signed 32-bit integers (e.g. `sighashType`). This method can be used to test
* compatibility with those implementations.
*
* @param value - the number to encode
*/
export const numberToBinInt32TwosCompliment = (value: number) => {
const bytes = 4;
const bitsInAByte = 8;
const bin = new Uint8Array(bytes);
// eslint-disable-next-line functional/no-let, functional/no-loop-statement, no-plusplus
for (let offset = 0; offset < bytes; offset++) {
// eslint-disable-next-line functional/no-expression-statement, functional/immutable-data
bin[offset] = value;
// eslint-disable-next-line functional/no-expression-statement, no-bitwise, no-param-reassign
value >>>= bitsInAByte;
}
return bin;
};
/**
* Decode a little-endian Uint8Array of any length into a number. For numbers
* larger than `Number.MAX_SAFE_INTEGER` (`9007199254740991`), use
* `binToBigIntUintLE`.
*
* The `bytes` parameter can be set to constrain the expected length (default:
* `bin.length`). This method throws if `bin.length` is not equal to `bytes`.
*
* @privateRemarks
* We avoid a bitwise strategy here because JavaScript uses 32-bit signed
* integers for bitwise math, so larger numbers are converted incorrectly. E.g.
* `2147483648 << 8` is `0`, while `2147483648n << 8n` is `549755813888n`.
*
* @param bin - the Uint8Array to decode
* @param bytes - the number of bytes to read (default: `bin.length`)
*/
export const binToNumberUintLE = (bin: Uint8Array, bytes = bin.length) => {
const base = 2;
const bitsInAByte = 8;
// eslint-disable-next-line functional/no-conditional-statement
if (bin.length !== bytes) {
// eslint-disable-next-line functional/no-throw-statement
throw new TypeError(`Bin length must be ${bytes}.`);
}
return new Uint8Array(bin.buffer, bin.byteOffset, bin.length).reduce(
(accumulated, byte, i) => accumulated + byte * base ** (bitsInAByte * i),
0
);
};
/**
* Decode a 2-byte Uint16LE Uint8Array into a number.
*
* Throws if `bin` is shorter than 2 bytes.
*
* @param bin - the Uint8Array to decode
*/
export const binToNumberUint16LE = (bin: Uint8Array) => {
const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);
const readAsLittleEndian = true;
return view.getUint16(0, readAsLittleEndian);
};
/**
* Decode a 4-byte Uint32LE Uint8Array into a number.
*
* Throws if `bin` is shorter than 4 bytes.
*
* @param bin - the Uint8Array to decode
*/
export const binToNumberUint32LE = (bin: Uint8Array) => {
const view = new DataView(bin.buffer, bin.byteOffset, bin.byteLength);
const readAsLittleEndian = true;
return view.getUint32(0, readAsLittleEndian);
};
/**
* Decode a big-endian Uint8Array of any length into a BigInt. If starting from
* a hex value, consider using the BigInt constructor instead:
* ```
* BigInt(`0x${hex}`)
* ```
*
* The `bytes` parameter can be set to constrain the expected length (default:
* `bin.length`). This method throws if `bin.length` is not equal to `bytes`.
*
* @param bin - the Uint8Array to decode
* @param bytes - the number of bytes to read (default: `bin.length`)
*/
export const binToBigIntUintBE = (bin: Uint8Array, bytes = bin.length) => {
const bitsInAByte = 8;
const shift = BigInt(bitsInAByte);
// eslint-disable-next-line functional/no-conditional-statement
if (bin.length !== bytes) {
// eslint-disable-next-line functional/no-throw-statement
throw new TypeError(`Bin length must be ${bytes}.`);
}
return new Uint8Array(bin.buffer, bin.byteOffset, bin.length).reduce(
// eslint-disable-next-line no-bitwise
(accumulated, byte) => (accumulated << shift) | BigInt(byte),
BigInt(0)
);
};
/**
* Decode an unsigned, 32-byte big-endian Uint8Array into a BigInt. This can be
* used to decode Uint8Array-encoded cryptographic primitives like private
* keys, public keys, curve parameters, and signature points.
*
* If starting from a hex value, consider using the BigInt constructor instead:
* ```
* BigInt(`0x${hex}`)
* ```
* @param bin - the Uint8Array to decode
*/
export const binToBigIntUint256BE = (bin: Uint8Array) => {
const uint256Bytes = 32;
return binToBigIntUintBE(bin, uint256Bytes);
};
/**
* Encode a positive BigInt into an unsigned 32-byte big-endian Uint8Array. This
* can be used to encoded numbers for cryptographic primitives like private
* keys, public keys, curve parameters, and signature points.
*
* Negative values will return the same result as `0`, values higher than
* 2^256-1 will return the maximum expressible unsigned 256-bit value
* (`0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff`).
*
* @param value - the BigInt to encode
*/
export const bigIntToBinUint256BEClamped = (value: bigint) => {
const uint256Bytes = 32;
return binToFixedLength(bigIntToBinUintLE(value), uint256Bytes).reverse();
};
/**
* Decode a little-endian Uint8Array of any length into a BigInt.
*
* The `bytes` parameter can be set to constrain the expected length (default:
* `bin.length`). This method throws if `bin.length` is not equal to `bytes`.
*
* @param bin - the Uint8Array to decode
* @param bytes - the number of bytes to read (default: `bin.length`)
*/
export const binToBigIntUintLE = (bin: Uint8Array, bytes = bin.length) => {
const bitsInAByte = 8;
// eslint-disable-next-line functional/no-conditional-statement
if (bin.length !== bytes) {
// eslint-disable-next-line functional/no-throw-statement
throw new TypeError(`Bin length must be ${bytes}.`);
}
return new Uint8Array(bin.buffer, bin.byteOffset, bin.length).reduceRight(
// eslint-disable-next-line no-bitwise
(accumulated, byte) => (accumulated << BigInt(bitsInAByte)) | BigInt(byte),
BigInt(0)
);
};
/**
* Decode an 8-byte Uint64LE Uint8Array into a BigInt.
*
* Throws if `bin` is shorter than 8 bytes.
*
* @param bin - the Uint8Array to decode
*/
export const binToBigIntUint64LE = (bin: Uint8Array) => {
const uint64LengthInBytes = 8;
const truncatedBin =
bin.length > uint64LengthInBytes ? bin.slice(0, uint64LengthInBytes) : bin;
return binToBigIntUintLE(truncatedBin, uint64LengthInBytes);
};
const enum VarInt {
uint8MaxValue = 0xfc,
uint16Prefix = 0xfd,
uint16MaxValue = 0xffff,
uint32Prefix = 0xfe,
uint32MaxValue = 0xffffffff,
uint64Prefix = 0xff,
}
/**
* Get the expected byte length of a Bitcoin VarInt given a first byte.
*
* @param firstByte - the first byte of the VarInt
*/
export const varIntPrefixToSize = (firstByte: number) => {
const uint8 = 1;
const uint16 = 2;
const uint32 = 4;
const uint64 = 8;
switch (firstByte) {
case VarInt.uint16Prefix:
return uint16 + 1;
case VarInt.uint32Prefix:
return uint32 + 1;
case VarInt.uint64Prefix:
return uint64 + 1;
default:
return uint8;
}
};
/**
* Read a Bitcoin VarInt (Variable-length integer) from a Uint8Array, returning
* the `nextOffset` after the VarInt and the value as a BigInt.
*
* @param bin - the Uint8Array from which to read the VarInt
* @param offset - the offset at which the VarInt begins
*/
export const readBitcoinVarInt = (bin: Uint8Array, offset = 0) => {
const bytes = varIntPrefixToSize(bin[offset]);
const hasPrefix = bytes !== 1;
return {
nextOffset: offset + bytes,
value: hasPrefix
? binToBigIntUintLE(bin.subarray(offset + 1, offset + bytes), bytes - 1)
: binToBigIntUintLE(bin.subarray(offset, offset + bytes), 1),
};
};
/**
* Encode a positive BigInt as a Bitcoin VarInt (Variable-length integer).
*
* Note: the maximum value of a Bitcoin VarInt is `0xffff_ffff_ffff_ffff`. This
* method will return an incorrect result for values outside of the range `0` to
* `0xffff_ffff_ffff_ffff`.
*
* @param value - the BigInt to encode (no larger than `0xffff_ffff_ffff_ffff`)
*/
export const bigIntToBitcoinVarInt = (value: bigint) =>
value <= BigInt(VarInt.uint8MaxValue)
? Uint8Array.of(Number(value))
: value <= BigInt(VarInt.uint16MaxValue)
? Uint8Array.from([
VarInt.uint16Prefix,
...numberToBinUint16LE(Number(value)),
])
: value <= BigInt(VarInt.uint32MaxValue)
? Uint8Array.from([
VarInt.uint32Prefix,
...numberToBinUint32LE(Number(value)),
])
: Uint8Array.from([VarInt.uint64Prefix, ...bigIntToBinUint64LE(value)]); | the_stack |
import { BigNumber } from "bignumber.js";
import * as Knex from "knex";
import * as _ from "lodash";
import { Address, OutcomesLiquidityRow } from "../types";
import { Percent, percent, Price, scalar, Scalar, Shares, Tokens, tokens } from "./dimension-quantity";
import { getSharePrice, MarketMaxPrice, MarketMinPrice, ReporterFeeRate, TotalFeeRate, continuousCompound } from "./financial-math";
import { currentStandardGasPriceGwei } from "./gas";
import { BidsAndAsks, getMarketOrderBooks, OrderBook, QuantityAtPrice } from "./simulated-order-book";
export const DefaultSpreadPercentString: string = "1";
export const DefaultSpreadPercentBigNumber: BigNumber = new BigNumber(DefaultSpreadPercentString, 10);
export const DefaultInvalidROIPercentString: string = "0";
export const DefaultInvalidROIPercentBigNumber: BigNumber = new BigNumber(DefaultInvalidROIPercentString, 10);
export const DefaultTakerInvalidProfitTokensString: string = "0";
export const DefaultTakerInvalidProfitTokensBigNumber: BigNumber = new BigNumber(DefaultTakerInvalidProfitTokensString, 10);
interface GetInvalidMetricsParams extends MarketMinPrice, MarketMaxPrice, ReporterFeeRate, TotalFeeRate, BidsAndAsks {
numOutcomes: number; // number of outcomes in this market
endDate: Date;
}
interface InvalidMetrics {
invalidROIPercent: Percent;
bestBidTakerInvalidProfitTokens: Tokens;
bestAskTakerInvalidProfitTokens: Tokens;
}
interface GetOutcomeSpreadParams extends MarketMinPrice, MarketMaxPrice, BidsAndAsks {
percentQuantityIncludedInSpread: Percent; // tuning parameter. Percent quantity of largest side order book side that will be used to calculate spread percent
}
const DefaultPercentQuantityIncludedInSpread = new Percent(new BigNumber(0.1)); // default for GetOutcomeSpreadParams.percentQuantityIncludedInSpread
interface GetOutcomeSpreadResult {
spreadPercent: Percent;
}
// updateLiquidityMetricsForMarketAndOutcomes updates all liquidity metrics in DB
// for passed marketId. Clients must call updateLiquidityMetricsForMarketAndOutcomes
// each time the orders table changes for any reason.
export async function updateLiquidityMetricsForMarketAndOutcomes(db: Knex, marketId: Address): Promise<void> {
const marketOrderBooks = await getMarketOrderBooks(db, marketId);
const outcomeLiquidityMetrics: Array<InvalidMetrics & GetOutcomeSpreadResult & GetLiquidityResult & { outcome: number }> = marketOrderBooks.orderBooks.map((ob) => {
const invalidMetrics = getInvalidMetrics({
...ob.orderBook.getBidsAndAsks(), // WARNING we rely on getInvalidMetrics to not modify market order books because getBidsAndAsks currently doesn't do a deep clone
...marketOrderBooks,
});
const outcomeSpread = getOutcomeSpread({
...ob.orderBook.getBidsAndAsks(), // WARNING we rely on getOutcomeSpread to not modify market order books because getBidsAndAsks currently doesn't do a deep clone
...marketOrderBooks,
percentQuantityIncludedInSpread: DefaultPercentQuantityIncludedInSpread,
});
// WARNING getLiquidity mutates order book which is ok only because it's the last thing to depend on order books
const liquidity = getLiquidity({
spreadPercents: LIQUIDITY_SPREAD_PERCENTS,
completeSetCost: marketOrderBooks.displayRange,
feeRate: marketOrderBooks.totalFeeRate,
orderBook: ob.orderBook,
});
return {
outcome: ob.outcome,
...invalidMetrics,
...outcomeSpread,
...liquidity,
};
});
const marketSpreadPercent: Percent = outcomeLiquidityMetrics.reduce<Percent>(
(maxSpreadPercent, os) => maxSpreadPercent.max(os.spreadPercent),
Percent.ZERO);
const marketInvalidROIPercent: Percent = outcomeLiquidityMetrics.reduce<Percent>(
(maxInvalidROIPercent, os) => maxInvalidROIPercent.max(os.invalidROIPercent),
Percent.ZERO);
const marketBestBidTakerInvalidProfitTokens: Tokens = outcomeLiquidityMetrics.reduce<Tokens>(
(bestBidTakerInvalidProfitTokens, os) => bestBidTakerInvalidProfitTokens.max(os.bestBidTakerInvalidProfitTokens),
outcomeLiquidityMetrics[0].bestBidTakerInvalidProfitTokens);
const marketBestAskTakerInvalidProfitTokens: Tokens = outcomeLiquidityMetrics.reduce<Tokens>(
(bestAskTakerInvalidProfitTokens, os) => bestAskTakerInvalidProfitTokens.max(os.bestAskTakerInvalidProfitTokens),
outcomeLiquidityMetrics[0].bestAskTakerInvalidProfitTokens);
outcomeLiquidityMetrics.forEach(async (os) => {
await db("outcomes").update({
spreadPercent: os.spreadPercent.magnitude.toString(),
invalidROIPercent: os.invalidROIPercent.magnitude.toString(),
bestBidTakerInvalidProfitTokens: os.bestBidTakerInvalidProfitTokens.magnitude.toString(),
bestAskTakerInvalidProfitTokens: os.bestAskTakerInvalidProfitTokens.magnitude.toString(),
}).where({ outcome: os.outcome, marketId });
});
await db("markets").update({
spreadPercent: marketSpreadPercent.magnitude.toString(),
invalidROIPercent: marketInvalidROIPercent.magnitude.toString(),
bestBidTakerInvalidProfitTokens: marketBestBidTakerInvalidProfitTokens.magnitude.toString(),
bestAskTakerInvalidProfitTokens: marketBestAskTakerInvalidProfitTokens.magnitude.toString(),
}).where({ marketId });
await updateOutcomesLiquidity(db, marketId, outcomeLiquidityMetrics);
}
function getInvalidSharePrice(params: GetInvalidMetricsParams, feeRate: Percent): Price {
const marketDisplayRange = params.marketMaxPrice.minus(params.marketMinPrice);
const invalidTradePriceMinusMinPrice: Price =
marketDisplayRange.dividedBy(scalar(params.numOutcomes));
// Eg. invalidSharePriceWithoutFees==0.5 for binary and scalar markets;
// invalidSharePriceWithoutFees==0.333 for categorical markets with three outcomes;
// invalidSharePriceWithoutFees=5 for a scalar market with min=10, max=20.
const invalidSharePriceWithoutFees = getSharePrice({
...params,
tradePriceMinusMinPrice: invalidTradePriceMinusMinPrice,
positionType: "long",
}).sharePrice;
// The proceeds from redeeming an invalid share are reduced by any fees paid.
const invalidSharePriceWithFees = invalidSharePriceWithoutFees
.multipliedBy(Scalar.ONE.minus(feeRate));
return invalidSharePriceWithFees;
}
// getInvalidROIPercent returns the return on investment percent the order creator
// of this outcome's best bid and ask would get if this market was determined to be
// invalid. The intuition is that although v1 cannot measure market invalidity we
// can still detect an order book that will profit if the market becomes invalid.
function getInvalidROIPercent(params: GetInvalidMetricsParams): Percent {
// Defensively assume that the market creator fees are going to the creator
// of the orders on the book, ie. we assume that order creator is the market
// creator. This causes invalidROIPercent to potentially be erroneously higher
// in the general case- because most order creators aren't in fact the market
// creator- but it removes the attack vector where invalidROIPercent is zero but a
// market creator could still make profit on an invalid market from creator fees.
const invalidSharePrice: Price = getInvalidSharePrice(params, params.reporterFeeRate);
const bestBidSharePrice: undefined | Price = params.bidsSortedByPriceDescending.length < 1 ? undefined : getSharePrice({
...params,
tradePriceMinusMinPrice:
params.bidsSortedByPriceDescending[0].tradePrice.minus(params.marketMinPrice),
positionType: "long",
}).sharePrice;
const bestAskSharePrice: undefined | Price = params.asksSortedByPriceAscending.length < 1 ? undefined : getSharePrice({
...params,
tradePriceMinusMinPrice:
params.asksSortedByPriceAscending[0].tradePrice.minus(params.marketMinPrice),
positionType: "short",
}).sharePrice;
const bestBidROIPercent: undefined | Percent = (() => {
if (bestBidSharePrice === undefined) return undefined;
else if (bestBidSharePrice.lte(Price.ZERO)) return Percent.ZERO;
return invalidSharePrice.dividedBy(bestBidSharePrice).expect(Percent).minus(Scalar.ONE);
})();
const bestAskROIPercent: undefined | Percent = (() => {
if (bestAskSharePrice === undefined) return undefined;
else if (bestAskSharePrice.lte(Price.ZERO)) return Percent.ZERO;
return invalidSharePrice.multipliedBy(scalar(params.numOutcomes - 1)) // the short side gets N-1 shares which will resolve at invalid price
.dividedBy(bestAskSharePrice).expect(Percent).minus(Scalar.ONE);
})();
const invalidROIPercent: Percent = (() => {
if (bestBidROIPercent === undefined ||
bestAskROIPercent === undefined ||
bestBidROIPercent.lte(Percent.ZERO) ||
bestAskROIPercent.lte(Percent.ZERO)) {
return Percent.ZERO;
}
return bestBidROIPercent.plus(bestAskROIPercent).dividedBy(Scalar.TWO);
})();
return invalidROIPercent;
}
const gasToTrade = new BigNumber(1750000, 10); // 1.75M gas for a trade
const gasToClaimWinnings = new BigNumber(1000000, 10); // 1M gas to claim winnings
const tenToTheNine = new BigNumber(10 ** 9, 10);
const annualDiscountRate = percent(0.1);
const yearsAfterExpiryToAssumeFinalization = scalar(14.0 / 365.0);
const millisecondsPerYear = scalar(365 * 24 * 60 * 60 * 1000);
function yearsBetweenDates(params: {
startDate: Date,
endDate: Date,
}): Scalar {
const millisDelta = scalar(params.endDate.getTime())
.minus(scalar(params.startDate.getTime()));
return millisDelta.dividedBy(millisecondsPerYear);
}
function getBestBidAskTakerInvalidProfit(params: GetInvalidMetricsParams): Pick<InvalidMetrics, "bestBidTakerInvalidProfitTokens" | "bestAskTakerInvalidProfitTokens"> {
const invalidSharePrice: Price = getInvalidSharePrice(params, params.totalFeeRate);
const bestBidQuantity: undefined | Shares = params.bidsSortedByPriceDescending.length < 1 ? undefined : params.bidsSortedByPriceDescending[0].quantity;
const bestAskQuantity: undefined | Shares = params.asksSortedByPriceAscending.length < 1 ? undefined : params.asksSortedByPriceAscending[0].quantity;
const bestBidTakerInvalidRevenue: undefined | Tokens = bestBidQuantity && bestBidQuantity.multipliedBy(invalidSharePrice)
.multipliedBy(scalar(params.numOutcomes - 1)) // the taker is taking the short side of bestBid and gets N-1 shares which will resolve at invalid price
.expect(Tokens);
const bestAskTakerInvalidRevenue: undefined | Tokens = bestAskQuantity && bestAskQuantity.multipliedBy(invalidSharePrice).expect(Tokens);
const bestBidTakerSharePrice: undefined | Price = params.bidsSortedByPriceDescending.length < 1 ? undefined : getSharePrice({
...params,
tradePriceMinusMinPrice:
params.bidsSortedByPriceDescending[0].tradePrice.minus(params.marketMinPrice),
positionType: "short", // taker is taking the short side of the best bid
}).sharePrice;
const bestAskTakerSharePrice: undefined | Price = params.asksSortedByPriceAscending.length < 1 ? undefined : getSharePrice({
...params,
tradePriceMinusMinPrice:
params.asksSortedByPriceAscending[0].tradePrice.minus(params.marketMinPrice),
positionType: "long", // taker is taking the long side of the best ask
}).sharePrice;
const takerGasCostToRealizeProfit = new Tokens(gasToTrade.plus(gasToClaimWinnings)
.multipliedBy(currentStandardGasPriceGwei()).dividedBy(tenToTheNine)); // gas*(gwei/gas) = gwei / 10^9 = tokens
const yearsToExpiry: Scalar = yearsBetweenDates({
startDate: new Date(),
endDate: params.endDate,
});
const timeToFinalizationInYears: Scalar =
yearsToExpiry.plus(yearsAfterExpiryToAssumeFinalization)
.max(Scalar.ZERO); // disallow negative timeToFinalizationInYears which would be like claiming invalid winnings in the past
const bestBidTakerInvalidCost: undefined | Tokens = bestBidQuantity && bestBidTakerSharePrice &&
continuousCompound({
amount: bestBidQuantity.multipliedBy(bestBidTakerSharePrice).expect(Tokens),
interestRate: annualDiscountRate,
compoundingDuration: timeToFinalizationInYears,
});
const bestAskTakerInvalidCost: undefined | Tokens = bestAskQuantity && bestAskTakerSharePrice &&
continuousCompound({
amount: bestAskQuantity.multipliedBy(bestAskTakerSharePrice).expect(Tokens),
interestRate: annualDiscountRate,
compoundingDuration: timeToFinalizationInYears,
});
const bestBidTakerInvalidProfit: undefined | Tokens = bestBidTakerInvalidRevenue && bestBidTakerInvalidCost && bestBidTakerInvalidRevenue.minus(bestBidTakerInvalidCost).minus(takerGasCostToRealizeProfit);
const bestAskTakerInvalidProfit: undefined | Tokens = bestAskTakerInvalidRevenue && bestAskTakerInvalidCost && bestAskTakerInvalidRevenue.minus(bestAskTakerInvalidCost).minus(takerGasCostToRealizeProfit);
return {
bestBidTakerInvalidProfitTokens: bestBidTakerInvalidProfit || Tokens.ZERO,
bestAskTakerInvalidProfitTokens: bestAskTakerInvalidProfit || Tokens.ZERO,
};
}
function getInvalidMetrics(params: GetInvalidMetricsParams): InvalidMetrics {
return {
invalidROIPercent: getInvalidROIPercent(params),
...getBestBidAskTakerInvalidProfit(params),
};
}
function getOutcomeSpread(params: GetOutcomeSpreadParams): GetOutcomeSpreadResult {
// numShares is the number of shares that will be used in the spreadPercent
// calculation. numShares will be used from each side of order book,
// so if numShares=10 then we'll take 10 from sell and 10 from buy.
const numShares: Shares = (() => {
const sumAskQuantity: Shares = params.asksSortedByPriceAscending.reduce<Shares>((sum, qtyAtPrice) => sum.plus(qtyAtPrice.quantity), Shares.ZERO);
const sumBidQuantity: Shares =
params.bidsSortedByPriceDescending.reduce<Shares>((sum, qtyAtPrice) => sum.plus(qtyAtPrice.quantity), Shares.ZERO);
const percentSharesOfLargestSide: Shares = sumAskQuantity.max(sumBidQuantity)
.multipliedBy(params.percentQuantityIncludedInSpread);
// If entire book is empty then we'll set numShares to one which causes
// spreadPercent to naturally and correctly be 100% because we'll take
// one share from each side of an empty book, and our "empty book" has
// infinite quantity bids at minPrice and asks at maxPrice (see below).
return percentSharesOfLargestSide.isZero() ? Shares.ONE : percentSharesOfLargestSide;
})();
const bidValue = takeFromBidsOrAsks({
numShares,
marketMinPrice: params.marketMinPrice,
marketMaxPrice: params.marketMaxPrice,
bidsSortedByPriceDescending: params.bidsSortedByPriceDescending,
});
const askValue = takeFromBidsOrAsks({
numShares,
marketMinPrice: params.marketMinPrice,
marketMaxPrice: params.marketMaxPrice,
asksSortedByPriceAscending: params.asksSortedByPriceAscending,
});
const spreadPercent: Percent = (() => {
const tmpSpreadPercent = askValue.minus(bidValue).dividedBy(
params.marketMaxPrice.minus(params.marketMinPrice).multipliedBy(numShares))
.expect(Percent);
// tmpSpreadPercent may be negative if the passed bids/asks were corrupt such
// that bids were greater than asks, which shouldn't happen since trades should
// be created to clear the order book any time best best is greater than best ask.
return tmpSpreadPercent.lt(Percent.ZERO) ? Percent.ZERO : tmpSpreadPercent;
})();
return {
spreadPercent,
};
}
const InfinityShares = new Shares(new BigNumber(Infinity));
// takeFromBidsOrAsks simulates consecutive takes from the passed
// bids or asks up until the passed numShares have been taken.
// Returns the total value (sum of TradePrice) of the takes.
function takeFromBidsOrAsks(params: {
numShares: Shares,
} & MarketMinPrice & MarketMaxPrice & (
Pick<GetOutcomeSpreadParams, "asksSortedByPriceAscending"> | Pick<GetOutcomeSpreadParams, "bidsSortedByPriceDescending">)): Tokens {
let valueTaken = Tokens.ZERO;
// params includes asksSortedByPriceAscending xor bidsSortedByPriceDescending.
// In either case, we'll create a new array by appending an order with
// infinite quantity. This has the effect of being able to take from
// bidsOrAsks without it ever becoming empty, which helps calculate
// spread percents when one side of the order book is small or empty.
const bidsOrAsks: Array<QuantityAtPrice> = ("asksSortedByPriceAscending" in params) ?
params.asksSortedByPriceAscending.concat([{
quantity: InfinityShares,
tradePrice: params.marketMaxPrice,
}]) :
params.bidsSortedByPriceDescending.concat([{
quantity: InfinityShares,
tradePrice: params.marketMinPrice,
}]);
let qtyRemainingToTake = params.numShares;
let i = 0;
while (qtyRemainingToTake.gt(Shares.ZERO)) {
// bidsOrAsks[i] is always defined because we appended an order with infinite quantity to bidsOrAsks
const qtyToTakeAtThisPrice = qtyRemainingToTake.min(bidsOrAsks[i].quantity);
valueTaken = valueTaken.plus(
qtyToTakeAtThisPrice.multipliedBy(bidsOrAsks[i].tradePrice).expect(Tokens));
qtyRemainingToTake = qtyRemainingToTake.minus(qtyToTakeAtThisPrice);
i += 1;
}
return valueTaken;
}
interface LiquidityTokensAtSpreadPercent {
spreadPercent: Percent;
liquidityTokens: Tokens;
}
interface GetLiquidityParams {
spreadPercents: Array<Percent>;
completeSetCost: Price;
feeRate: Percent;
orderBook: OrderBook;
}
interface GetLiquidityResult {
liquidityTokensAtSpreadPercents: Array<LiquidityTokensAtSpreadPercent>;
}
export const MAX_SPREAD_PERCENT = 1;
const LIQUIDITY_SPREAD_PERCENTS: Array<Percent> = [
percent(0.1),
percent(0.15),
percent(0.2),
percent(MAX_SPREAD_PERCENT),
];
const SELL_INCREMENT_COST_DEFAULT: Tokens = tokens(0.02);
let SELL_INCREMENT_COST: Tokens = SELL_INCREMENT_COST_DEFAULT;
export function unsafeSetSELL_INCREMENT_COST(t: BigNumber): void {
SELL_INCREMENT_COST = new Tokens(t);
}
export function unsafeResetSELL_INCREMENT_COST(): void {
SELL_INCREMENT_COST = SELL_INCREMENT_COST_DEFAULT;
}
const ONE_HUNDRED_MILLION = scalar(100000000);
const MAX_ITERATIONS = 100000; // MAX_ITERATIONS is not arbitrary: the formula `MAX_ITERATIONS * SELL_INCREMENT_COST` is the amount of tokens that getLiquidity will process at "high resolution"
function getLiquidity(params: GetLiquidityParams): GetLiquidityResult {
const sellIncrement: Shares =
SELL_INCREMENT_COST.dividedBy(params.completeSetCost).expect(Shares);
let liquidityTokenCost = Tokens.ZERO; // accrued/running total cost for complete sets bought from system
let liquidityTokens = Tokens.ZERO; // accrued/running total revenue for complete sets sold into order book
let nextLiquidityTokens = Tokens.ZERO; // value of liquidityTokens in next loop iteration because both next/current value are needed in algorithm
const liquidityTokensAtSpreadPercents: Array<LiquidityTokensAtSpreadPercent> = [];
// Spread percents are ascending so that we can use the liquidityTokens for
// the previous spread percent as part of liquidityTokens for the next spread
// percent because return on investment is monotonically decreasing as we take
// from the order book each iteration because we take the best bids/asks first.
const spreadPercentsAscending = _.sortBy(params.spreadPercents, (sp: Percent) => sp.magnitude.toNumber());
let i = 0;
let iterations = 0;
while (i < spreadPercentsAscending.length) {
iterations++;
// When iterations exceeds MAX_ITERATIONS we'll greatly increase the
// incremental take amount so as to terminate the algorithm faster. This is
// because extremely large quantity with dust/epsilon prices orders function
// as a denial of service attack because this algorithm processes quantity
// incrementally, so if you have a 100k qty order and it's taking only
// 0.05qty per iteration it's going to take two million iterations... and
// the data structures are fairly inefficient so that takes a very long time.
const sellIncrementCostThisIteration = SELL_INCREMENT_COST.multipliedBy(iterations > MAX_ITERATIONS ? ONE_HUNDRED_MILLION : Scalar.ONE);
const sellIncrementThisIteration = sellIncrement.multipliedBy(iterations > MAX_ITERATIONS ? ONE_HUNDRED_MILLION : Scalar.ONE);
// Incrementally sell complete sets into the order book
liquidityTokenCost = liquidityTokenCost.plus(sellIncrementCostThisIteration);
const proceedsThisIncrement: Tokens = params.orderBook
.closeLongFillOnlyWithFeeAdjustment(sellIncrementThisIteration, params.feeRate)
.plus(params.orderBook
.closeShortFillOnlyWithFeeAdjustment(sellIncrementThisIteration, params.feeRate),
);
nextLiquidityTokens = liquidityTokens.plus(proceedsThisIncrement);
// Determine if this incremental sell is the last one for spreadPercentsAscending[i] and possibly subsequent spread percents
while (i < spreadPercentsAscending.length &&
(proceedsThisIncrement.lte(Tokens.ZERO) ||
nextLiquidityTokens.dividedBy(liquidityTokenCost).expect(Percent)
.lt(Percent.ONE.minus(spreadPercentsAscending[i])))) {
// One of two things happened
// 1. proceedsThisIncrement is zero which means the order book is completely empty; this while loop will naturally terminate and assign liquidityTokens for the current and all remaining spreadPercents
// OR
// 2. nextLiquidityTokens has a return-on-investment vs liquidityTokenCost that is too low to satisfy spreadPercentsAscending[i], ie. nextLiquidityTokens yields an implied spread percent that is now larger than spreadPercentsAscending[i], so we have determined the final liquidityTokens value for spreadPercentsAscending[i] (and that value is liquidityTokens, not nextLiquidityTokens, because nextLiquidityTokens was disqualified)
liquidityTokensAtSpreadPercents.push({
spreadPercent: spreadPercentsAscending[i],
liquidityTokens,
});
i++;
}
liquidityTokens = nextLiquidityTokens;
}
return {
liquidityTokensAtSpreadPercents,
};
}
async function updateOutcomesLiquidity(db: Knex, marketId: string, data: Array<GetLiquidityResult & { outcome: number }>): Promise<void> {
// We must delete all existing data because the passed data
// may not correspond with what's previously in DB and we
// don't want the DB containing a mixture of old/new metrics.
await db.from("outcomes_liquidity").where("marketId", marketId).delete();
const inserts: Array<OutcomesLiquidityRow<string>> = [];
data.forEach((d) => {
d.liquidityTokensAtSpreadPercents.forEach((l) => {
inserts.push({
marketId,
outcome: d.outcome,
spreadPercent: l.spreadPercent.magnitude.toString(),
liquidityTokens: l.liquidityTokens.magnitude.toString(),
});
});
});
if (inserts.length > 0) {
await db.batchInsert("outcomes_liquidity", inserts, inserts.length);
}
} | the_stack |
/*
此文件需要放在引擎安装目录
例如 C:\Program Files\Egret\EgretEngine\win\selector.js
或 /Applications/EgretEngine.app/Contents/Resources/mac/selector.js
根据命令行参数
--ev 2.4.3
或项目中 egretProperties.json 中指定的引擎版本来执行对应的引擎。
引擎选择优先级为
--ev
egretProperties.json
默认引擎
历史版本的引擎位置为:
Mac: /Users/${user}/Library/Application Support/Egret/engine/${version}/
Windows: %AppData%/Egret/engine/${version}/
其中根目录下有 config.json(可选,默认没有) 记录默认引擎和自定义引擎目录
{
"egret":{
"2.0.5":{
"root":"D:\\Work\\egret-core\\" //自定义目录
},
"defaultEngine":"2.4.3"
}
}
默认版本查找顺序
config.json defaultEngine 指定的版本号
config.json 中指定的自定义路径
引擎安装目录/egret
历史版本根目录/${version}
EGRET_PATH环境变量仅仅作为兼容以前版本使用
egret versions 命令输出可用的引擎版本
Egret Engine 2.4.3 D:/Program Files/Egret/EgretEngine/win/egret/
Egret Engine 2.0.5 D:/Work/egret-core/
*/
import FS = require("fs");
import Path = require("path");
var DEFAULT_ENGINE = "defaultEngine"
var args: Args;
var configData: ConfigData;
var language: string;
var engines: EnginesMap;
var localsMessages = {
en: {
1: "Can not find Egret Engine {0}, please install it with Egret Launcher.",
2: "Can not find Egret Engine, please open Egret Launcher and press the \"Reset\" button.",
3: "Egret Engine default version: {0}\nEgret Engine current version: {1}\nYou can upgrade your project via egret upgrade",
4: "Egret Engine current version: {0}",
5: "Error! The egretProperties.json is not a valid json.",
6: "Egret path : {0}"
},
zh: {
1: "找不到 Egret Engine {0} 请打开引擎面板并添加对应版本的引擎",
2: "找不到默认引擎,请尝试打开引擎面板并点击“重置引擎”按钮",
3: "您的默认引擎版本为 {0}\n当前项目使用版本为 {1}\n您可以执行 egret upgrade 命令升级项目",
4: "您正在使用的引擎版本为 {0}",
5: "错误!! egretProperties.json 不是有效的 json 文件",
6: "Egret安装路径 : {0}"
}
}
var commandsToSkip = {
"upgrade": true
};
function entry() {
readConfig();
getLanguage();
args = parseArgs();
var requestVersion: any = args.egretversion || args.ev;
if (requestVersion === true)
requestVersion = undefined;
var handled = false;
if (args.command == "versions") {
return printVersions();
}
var projectVersion = getProjectVersion();
var defaultVersion = getDefaultEngineInfo();
if (args.command == "info") {
console.log(tr(4, defaultVersion.version));
var root = getEgretRoot();
console.log(tr(6, root))
return;
}
if (requestVersion || (projectVersion && !(args.command in commandsToSkip))) {
requestVersion = requestVersion || projectVersion;
var isUsingDefault = requestVersion == defaultVersion.version;
var messageCode = isUsingDefault ? 4 : 3;
console.log(tr(messageCode, defaultVersion.version, requestVersion));
if (!engines[requestVersion]) {
console.log(tr(1, requestVersion));
process.exit(1);
return;
}
executeVersion(requestVersion);
return;
}
if (!defaultVersion) {
console.log(tr(2, defaultVersion.version));
process.exit(2);
return;
}
if (!handled) {
console.log(tr(4, defaultVersion.version, requestVersion));
executeVersion(defaultVersion.version, defaultVersion.root);
}
}
function getEgretRoot() {
var path = require("path");
var obj = _getEnv();
var egretRoot: string;
var globalpath = module['paths'].concat();
var existsFlag = false;
for (var i = 0; i < globalpath.length; i++) {
var prefix = globalpath[i];
var url = file.joinPath(prefix, '../');
if (file.exists(file.joinPath(url, 'tools/bin/egret'))) {
existsFlag = true;
break;
}
url = prefix;
if (file.exists(file.joinPath(url, 'tools/bin/egret'))) {
existsFlag = true;
break;
}
}
if (!existsFlag) {
throw new Error("can't find Egret");
}
egretRoot = url;
return file.escapePath(file.joinPath(egretRoot, '/'));
}
function _getEnv() {
return process.env;
}
function printVersions() {
if (!engines) {
getAllEngineVersions();
}
Object.keys(engines).sort(compareVersion).reverse().forEach(v => {
console.log(`Egret Engine ${engines[v].version} ` + engines[v].root);
});
}
function executeVersion(version: string, root?: string): boolean {
if (!engines) {
getAllEngineVersions();
}
root = root || engines[version].root;
var bin = getBin(root);
process.env["EGRET_PATH"] = root;
//Fix 1.5 can not find typescript lib
if (process['mainModule']) {
process['mainModule'].filename = bin;
}
require(bin);
return true;
}
function getDefaultEngineInfo(): EngineVersion {
var defaultRoot: string = null;
var version: string = null;
if (!engines) {
getAllEngineVersions();
}
if (configData && configData.egret) {
var defaultVersion: string = <any>configData.egret[DEFAULT_ENGINE]
if (defaultVersion && engines[defaultVersion]) {
version = defaultVersion;
}
}
if (!version) {
var info = getEngineInfoInInstaller();
if (info && info.root) {
version = info.version;
}
}
if (!version || !engines[version]) {
console.log(tr(2, version));
process.exit(2);
}
return engines[version];
}
function getBin(versionRoot: string) {
return file.joinPath(versionRoot, "tools/bin/egret");
}
function getEngineVersion(root: string): EngineVersion {
var packagePath = file.joinPath(root || "", "package.json");
if (!file.exists(packagePath)) {
return null;
}
var packageText = file.read(packagePath);
try {
var packageData = JSON.parse(packageText);
}
catch (e) {
console.log(packagePath, "is not a egret package file");
return null;
}
var engineInfo = {
version: <string>packageData['version'],
root: <string>root
}
return engineInfo;
}
function getProjectVersion(): string {
var dir;
if (args.command != "create_app") {
dir = args.projectDir;
} else {
dir = args["f"]
}
var propsPath = file.joinPath(dir, "egretProperties.json");
if (file.exists(propsPath)) {
var jsonText = file.read(propsPath);
var props;
try {
props = JSON.parse(jsonText);
} catch (e) {
console.log(tr(5));
process.exit(2);
}
return props["egret_version"];
}
return null;
}
function readConfig() {
var configPath = getAppDataEnginesRootPath() + "config.json";
if (file.exists(configPath)) {
var jsonText = file.read(configPath);
try {
configData = JSON.parse(jsonText);
}
catch (e) {
configData = null;
}
}
}
function getEngineInfoInInstaller(): EngineVersion {
var selector: string = process['mainModule'].filename;
var root = file.escapePath(file.joinPath(Path.dirname(selector), './egret/'));
return getEngineVersion(root);
}
function getAppDataEnginesRootPath(): string {
var path: string;
switch (process.platform) {
case 'darwin':
var home = process.env.HOME || ("/Users/" + (process.env.NAME || process.env.LOGNAME));
if (!home)
return null;
path = `${home}/Library/Application Support/Egret/engine/`;
break;
case 'win32':
var appdata = process.env.AppData || `${process.env.USERPROFILE}/AppData/Roaming/`;
path = file.escapePath(`${appdata}/Egret/engine/`);
break;
default:
;
}
if (file.exists(path))
return path;
return null;
}
export interface EngineVersion {
version: string;
root: string;
}
export interface EnginesMap {
[name: string]: EngineVersion
}
function getAllEngineVersions() {
var root = getAppDataEnginesRootPath();
var egret = getEngineInfoInInstaller();
engines = {};
if (!root) {
engines[egret.version] = egret;
return;
}
var versionRoots = file.getDirectoryListing(root);
versionRoots && versionRoots.forEach(versionRoot => {
versionRoot = file.escapePath(versionRoot);
var bin = getBin(versionRoot);
var exist = file.exists(bin);
if (exist) {
var info = getEngineVersion(versionRoot);
if (!info) {
return;
}
engines[info.version] = info;
}
});
// AppData 中的引擎不能覆盖默认安装,确保用户能够用新安装覆盖原来有问题的引擎
engines[egret.version] = egret;
if (configData) {
for (var v in configData.egret) {
if (!configData.egret[v].root) {
continue;
}
var rootInConfig = file.escapePath(configData.egret[v].root);
var bin = getBin(rootInConfig);
var exist = file.exists(bin);
if (exist) {
var info = getEngineVersion(rootInConfig);
if (!info) {
continue;
}
engines[info.version] = info;
}
}
}
}
function tr(code, ...args: any[]) {
var messages = localsMessages[language];
var message = messages[code];
message = format(message, args);
return message;
}
function format(text: string, args: any[]): string {
var length = args.length;
for (var i = 0; i < length; i++) {
text = text.replace(new RegExp("\\{" + i + "\\}", "ig"), args[i]);
}
return text;
}
interface ConfigData {
egret: {
[version: string]: {
root: string
};
};
}
interface Args {
command?: string;
projectDir?: string;
egretversion?: string;
ev?: string;
}
function parseArgs(): Args {
var i = 0;
var commands: string[] = [];
var options: Args = {}
var args: string[] = process.argv.concat();
args.splice(0, 2);
while (i < args.length) {
var s = args[i++];
if (s.charAt(0) === '-') {
s = s.slice(s.charAt(1) === '-' ? 2 : 1).toLowerCase();
if (!args[i] || args[i].charAt(0) == '-') {
options[s] = true;
}
else {
options[s] = args[i++] || "";
}
}
else {
commands.push(s);
}
}
if (commands.length > 0) {
options.command = commands[0];
if (commands.length > 1 && file.isDirectory(commands[1])) {
options.projectDir = commands[1];
}
}
if (options.projectDir == null) {
options.projectDir = process.cwd()
}
else {
var absPath = file.joinPath(process.cwd(), options.projectDir);
if (file.isDirectory(absPath)) {
options.projectDir = absPath;
}
}
options.projectDir = file.joinPath(options.projectDir, "/");
return options;
}
function compareVersion(v1: string, v2: string) {
return versionToNumber(v1) - versionToNumber(v2);
function versionToNumber(v: string): number {
var numbers = v.split(".").map(n => {
try {
return parseInt(n) || 0;
}
catch (e) {
return 0;
}
});
var total = 0;
numbers.forEach((n, i) => {
total += n * Math.pow(0.01, i);
});
return total;
}
}
module file {
var charset = "utf-8";
/**
* 指定路径的文件或文件夹是否存在
*/
export function exists(path: string): boolean {
path = escapePath(path);
return FS.existsSync(path);
}
/**
* 转换本机路径为Unix风格路径。
*/
export function escapePath(path: string): string {
if (!path)
return "";
return path.split("\\").join("/");
}
/**
* 读取文本文件,返回打开文本的字符串内容,若失败,返回"".
* @param path 要打开的文件路径
*/
export function read(path: string, ignoreCache = false): string {
path = escapePath(path);
try {
var text = FS.readFileSync(path, charset);
text = text.replace(/^\uFEFF/, '');
}
catch (err0) {
return "";
}
return text;
}
/**
* 连接路径,支持传入多于两个的参数。也支持"../"相对路径解析。返回的分隔符为Unix风格。
*/
export function joinPath(dir: string, ...filename: string[]): string {
var path = Path.join.apply(null, arguments);
path = escapePath(path);
return path;
}
export function isDirectory(path: string): boolean {
path = escapePath(path);
try {
var stat = FS.statSync(path);
}
catch (e) {
return false;
}
return stat.isDirectory();
}
/**
* 获取指定文件夹下的文件或文件夹列表,不包含子文件夹内的文件。
* @param path 要搜索的文件夹
* @param relative 是否返回相对路径,若不传入或传入false,都返回绝对路径。
*/
export function getDirectoryListing(path: string, relative: boolean = false): string[] {
path = escapePath(path);
try {
var list = FS.readdirSync(path);
}
catch (e) {
return [];
}
var length = list.length;
if (!relative) {
for (var i = length - 1; i >= 0; i--) {
if (list[i].charAt(0) == ".") {
list.splice(i, 1);
}
else {
list[i] = joinPath(path, list[i]);
}
}
}
else {
for (i = length - 1; i >= 0; i--) {
if (list[i].charAt(0) == ".") {
list.splice(i, 1);
}
}
}
return list;
}
/**
* 获取路径的文件名(不含扩展名)或文件夹名
*/
export function getFileName(path: string): string {
if (!path)
return "";
path = escapePath(path);
var startIndex = path.lastIndexOf("/");
var endIndex;
if (startIndex > 0 && startIndex == path.length - 1) {
path = path.substring(0, path.length - 1);
startIndex = path.lastIndexOf("/");
endIndex = path.length;
return path.substring(startIndex + 1, endIndex);
}
endIndex = path.lastIndexOf(".");
if (endIndex == -1 || isDirectory(path))
endIndex = path.length;
return path.substring(startIndex + 1, endIndex);
}
}
function getLanguage() {
let osLocal = require("./lib/os-local.js");
let i18n:string = osLocal();
i18n = i18n.toLowerCase();
if (i18n == "zh_cn" || i18n == "zh_tw" || i18n == "zh_hk") {
language = "en";
}
else {
language = "en";
}
}
entry(); | the_stack |
import * as os from 'os';
import { DebugProtocol } from 'vscode-debugprotocol';
import { LoggingDebugSession, ErrorDestination, Response, logger } from 'vscode-debugadapter';
import { ChromeDebugAdapter } from './chromeDebugAdapter';
import { ITargetFilter, ChromeConnection, IChromeError } from './chromeConnection';
import { BasePathTransformer } from '../transformers/basePathTransformer';
import { BaseSourceMapTransformer } from '../transformers/baseSourceMapTransformer';
import { LineColTransformer } from '../transformers/lineNumberTransformer';
import { IDebugAdapter } from '../debugAdapterInterfaces';
import { telemetry, ExceptionType, IExecutionResultTelemetryProperties, TelemetryPropertyCollector, ITelemetryPropertyCollector } from '../telemetry';
import * as utils from '../utils';
import { ExecutionTimingsReporter, StepProgressEventsEmitter, IObservableEvents, IStepStartedEventsEmitter, IFinishedStartingUpEventsEmitter } from '../executionTimingsReporter';
import { Breakpoints } from './breakpoints';
import { ScriptContainer } from '../chrome/scripts';
export interface IChromeDebugAdapterOpts {
targetFilter?: ITargetFilter;
logFilePath?: string; // obsolete, vscode log dir should be used
// Override services
chromeConnection?: typeof ChromeConnection;
pathTransformer?: { new(): BasePathTransformer };
sourceMapTransformer?: { new(sourceHandles: any): BaseSourceMapTransformer };
lineColTransformer?: { new(session: any): LineColTransformer };
breakpoints?: typeof Breakpoints;
scriptContainer?: typeof ScriptContainer;
}
export interface IChromeDebugSessionOpts extends IChromeDebugAdapterOpts {
/** The class of the adapter, which is instantiated for each session */
adapter: typeof ChromeDebugAdapter;
extensionName: string;
}
export const ErrorTelemetryEventName = 'error';
// A failed request can return either an Error, an error from Chrome, or a DebugProtocol.Message which is returned as-is to the client
type RequestHandleError = Error | DebugProtocol.Message | IChromeError;
function isMessage(e: RequestHandleError): e is DebugProtocol.Message {
return !!(<DebugProtocol.Message>e).format;
}
function isChromeError(e: RequestHandleError): e is IChromeError {
return !!(<IChromeError>e).data;
}
export class ChromeDebugSession extends LoggingDebugSession implements IObservableEvents<IStepStartedEventsEmitter & IFinishedStartingUpEventsEmitter> {
private readonly _readyForUserTimeoutInMilliseconds = 5 * 60 * 1000; // 5 Minutes = 5 * 60 seconds = 5 * 60 * 1000 milliseconds
private _debugAdapter: IDebugAdapter & IObservableEvents<IStepStartedEventsEmitter & IFinishedStartingUpEventsEmitter>;
private _extensionName: string;
public readonly events: StepProgressEventsEmitter;
private reporter = new ExecutionTimingsReporter();
private haveTimingsWhileStartingUpBeenReported = false;
public static readonly FinishedStartingUpEventName = 'finishedStartingUp';
/**
* This needs a bit of explanation -
* The Session is reinstantiated for each session, but consumers need to configure their instance of
* ChromeDebugSession. Consumers should call getSession with their config options, then call
* DebugSession.run with the result. Alternatively they could subclass ChromeDebugSession and pass
* their options to the super constructor, but I think this is easier to follow.
*/
public static getSession(opts: IChromeDebugSessionOpts): typeof ChromeDebugSession {
// class expression!
return class extends ChromeDebugSession {
constructor(debuggerLinesAndColumnsStartAt1?: boolean, isServer?: boolean) {
super(debuggerLinesAndColumnsStartAt1, isServer, opts);
}
};
}
public constructor(obsolete_debuggerLinesAndColumnsStartAt1?: boolean, obsolete_isServer?: boolean, opts?: IChromeDebugSessionOpts) {
super(opts.logFilePath, obsolete_debuggerLinesAndColumnsStartAt1, obsolete_isServer);
logVersionInfo();
this._extensionName = opts.extensionName;
this._debugAdapter = new (<any>opts.adapter)(opts, this);
this.events = new StepProgressEventsEmitter([this._debugAdapter.events]);
this.configureExecutionTimingsReporting();
const safeGetErrDetails = err => {
let errMsg;
try {
errMsg = (err && (<Error>err).stack) ? (<Error>err).stack : JSON.stringify(err);
} catch (e) {
errMsg = 'Error while handling previous error: ' + e.stack;
}
return errMsg;
};
const reportErrorTelemetry = (err, exceptionType: ExceptionType) => {
let properties: IExecutionResultTelemetryProperties = {};
properties.successful = 'false';
properties.exceptionType = exceptionType;
utils.fillErrorDetails(properties, err);
/* __GDPR__
"error" : {
"${include}": [
"${IExecutionResultTelemetryProperties}",
"${DebugCommonProperties}"
]
}
*/
telemetry.reportEvent(ErrorTelemetryEventName, properties);
};
process.addListener('uncaughtException', (err: any) => {
reportErrorTelemetry(err, 'uncaughtException');
logger.error(`******** Unhandled error in debug adapter: ${safeGetErrDetails(err)}`);
});
process.addListener('unhandledRejection', (err: Error|DebugProtocol.Message) => {
reportErrorTelemetry(err, 'unhandledRejection');
// Node tests are watching for the ********, so fix the tests if it's changed
logger.error(`******** Unhandled error in debug adapter - Unhandled promise rejection: ${safeGetErrDetails(err)}`);
});
}
/**
* Overload dispatchRequest to the debug adapters' Promise-based methods instead of DebugSession's callback-based methods
*/
protected dispatchRequest(request: DebugProtocol.Request): void {
// We want the request to be non-blocking, so we won't await for reportTelemetry
this.reportTelemetry(`ClientRequest/${request.command}`, async (reportFailure, telemetryPropertyCollector) => {
const response: DebugProtocol.Response = new Response(request);
try {
logger.verbose(`From client: ${request.command}(${JSON.stringify(request.arguments) })`);
if (!(request.command in this._debugAdapter)) {
reportFailure('The debug adapter doesn\'t recognize this command');
this.sendUnknownCommandResponse(response, request.command);
} else {
telemetryPropertyCollector.addTelemetryProperty('requestType', request.type);
response.body = await this._debugAdapter[request.command](request.arguments, telemetryPropertyCollector, request.seq);
this.sendResponse(response);
}
} catch (e) {
if (!this.isEvaluateRequest(request.command, e)) {
reportFailure(e);
}
this.failedRequest(request.command, response, e);
}
});
}
// { command: request.command, type: request.type };
private async reportTelemetry(eventName: string,
action: (reportFailure: (failure: any) => void, telemetryPropertyCollector: ITelemetryPropertyCollector) => Promise<void>): Promise<void> {
const startProcessingTime = process.hrtime();
const startTime = Date.now();
const isSequentialRequest = eventName === 'ClientRequest/initialize' || eventName === 'ClientRequest/launch' || eventName === 'ClientRequest/attach';
const properties: IExecutionResultTelemetryProperties = {};
const telemetryPropertyCollector = new TelemetryPropertyCollector();
if (isSequentialRequest) {
this.events.emitStepStarted(eventName);
}
let failed = false;
const sendTelemetry = () => {
const timeTakenInMilliseconds = utils.calculateElapsedTime(startProcessingTime);
properties.timeTakenInMilliseconds = timeTakenInMilliseconds.toString();
if (isSequentialRequest) {
this.events.emitStepCompleted(eventName);
} else {
this.events.emitRequestCompleted(eventName, startTime, timeTakenInMilliseconds);
}
Object.assign(properties, telemetryPropertyCollector.getProperties());
// GDPR annotations go with each individual request type
telemetry.reportEvent(eventName, properties);
};
const reportFailure = e => {
failed = true;
properties.successful = 'false';
properties.exceptionType = 'firstChance';
utils.fillErrorDetails(properties, e);
sendTelemetry();
};
// We use the reportFailure callback because the client might exit immediately after the first failed request, so we need to send the telemetry before that, if not it might get dropped
await action(reportFailure, telemetryPropertyCollector);
if (!failed) {
properties.successful = 'true';
sendTelemetry();
}
}
private isEvaluateRequest(requestType: string, error: RequestHandleError): boolean {
return !isMessage(error) && (requestType === 'evaluate');
}
private failedRequest(requestType: string, response: DebugProtocol.Response, error: RequestHandleError): void {
if (isMessage(error)) {
this.sendErrorResponse(response, error as DebugProtocol.Message);
return;
}
if (this.isEvaluateRequest(requestType, error)) {
// Errors from evaluate show up in the console or watches pane. Doesn't seem right
// as it's not really a failed request. So it doesn't need the [extensionName] tag and worth special casing.
response.message = error ? error.message : 'Unknown error';
response.success = false;
this.sendResponse(response);
return;
}
const errUserMsg = isChromeError(error) ?
error.message + ': ' + error.data :
(error.message || error.stack);
const errDiagnosticMsg = isChromeError(error) ?
errUserMsg : (error.stack || error.message);
logger.error(`Error processing "${requestType}": ${errDiagnosticMsg}`);
// These errors show up in the message bar at the top (or nowhere), sometimes not obvious that they
// come from the adapter, so add extensionName
this.sendErrorResponse(
response,
1104,
'[{_extensionName}] Error processing "{_requestType}": {_stack}',
{ _extensionName: this._extensionName, _requestType: requestType, _stack: errUserMsg },
ErrorDestination.Telemetry);
}
private sendUnknownCommandResponse(response: DebugProtocol.Response, command: string): void {
this.sendErrorResponse(response, 1014, `[${this._extensionName}] Unrecognized request: ${command}`, null, ErrorDestination.Telemetry);
}
public reportTimingsWhileStartingUpIfNeeded(requestedContentWasDetected: boolean, reasonForNotDetected?: string): void {
if (!this.haveTimingsWhileStartingUpBeenReported) {
const report = this.reporter.generateReport();
const telemetryData = { RequestedContentWasDetected: requestedContentWasDetected.toString() } as {[key: string]: string};
for (const reportProperty in report) {
telemetryData[reportProperty] = JSON.stringify(report[reportProperty]);
}
if (!requestedContentWasDetected && typeof reasonForNotDetected !== 'undefined') {
telemetryData.RequestedContentWasNotDetectedReason = reasonForNotDetected;
}
/* __GDPR__
"report-start-up-timings" : {
"RequestedContentWasNotDetectedReason" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"${include}": [
"${ReportProps}",
"${DebugCommonProperties}"
]
}
*/
telemetry.reportEvent('report-start-up-timings', telemetryData);
this.haveTimingsWhileStartingUpBeenReported = true;
}
}
private configureExecutionTimingsReporting(): void {
this.reporter.subscribeTo(this.events);
this._debugAdapter.events.once(ChromeDebugSession.FinishedStartingUpEventName, args => {
this.reportTimingsWhileStartingUpIfNeeded(args ? args.requestedContentWasDetected : true, args && args.reasonForNotDetected);
});
setTimeout(() => this.reportTimingsWhileStartingUpIfNeeded(/*requestedContentWasDetected*/false, /*reasonForNotDetected*/'timeout'), this._readyForUserTimeoutInMilliseconds);
}
public shutdown(): void {
process.removeAllListeners('uncaughtException');
process.removeAllListeners('unhandledRejection');
this.reportTimingsWhileStartingUpIfNeeded(/*requestedContentWasDetected*/false, /*reasonForNotDetected*/'shutdown');
super.shutdown();
}
public sendResponse(response: DebugProtocol.Response): void {
const originalLogVerbose = logger.verbose;
try {
logger.verbose = textToLog => {
if (response && response.command === 'source' && response.body && response.body.content) {
const clonedResponse = Object.assign({}, response);
clonedResponse.body = Object.assign({}, response.body);
clonedResponse.body.content = '<removed script source for logs>';
return originalLogVerbose.call(logger, `To client: ${JSON.stringify(clonedResponse)}`);
} else {
return originalLogVerbose.call(logger, textToLog);
}
};
super.sendResponse(response);
} finally {
logger.verbose = originalLogVerbose;
}
}
}
function logVersionInfo(): void {
logger.log(`OS: ${os.platform()} ${os.arch()}`);
logger.log(`Adapter node: ${process.version} ${process.arch}`);
const coreVersion = require('../../../package.json').version;
logger.log('vscode-chrome-debug-core: ' + coreVersion);
/* __GDPR__FRAGMENT__
"DebugCommonProperties" : {
"Versions.DebugAdapterCore" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
telemetry.addCustomGlobalProperty( { 'Versions.DebugAdapterCore': coreVersion });
} | the_stack |
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { AppHead, AppFooter } from 'components';
import { useNavigate } from 'react-router-dom';
import {
Button,
Row,
Divider,
Breadcrumb,
Form,
Radio,
RadioGroup,
Input,
Toggle,
IconButton,
Message,
toaster,
Modal,
} from 'rsuite';
import TrashIcon from '@rsuite/icons/Trash';
import ExpandOutlineIcon from '@rsuite/icons/ExpandOutline';
import { axios } from 'api';
// 获取选项序号字符串
const getSerialStr = (i: number) => {
return String.fromCharCode(65 + i);
};
// 选择题 Item 组件
const OptionsItem = (props: any) => {
const {
data,
index,
onValueChange = (id: number, item: any) => {},
onDeleteValue = (id: number, item: any) => {},
} = props;
const [inputCotent, setinputCotent] = useState(data?.content);
return data ? (
<div style={{ display: 'flex', alignItems: 'center', marginTop: 25 }}>
<IconButton icon={<TrashIcon />} onClick={() => onDeleteValue(index, data)} />
<p style={{ marginLeft: 15 }}>{getSerialStr(index)}.</p>
<Input
style={{ flex: 1, margin: '0 10px' }}
defaultValue={inputCotent}
onBlur={() => {
// console.log('失去焦点', index);
onValueChange(index, {
...data,
content: inputCotent,
});
}}
onChange={(value) => setinputCotent(value)}
/>
<Toggle
checked={data?.isanswer}
checkedChildren="正确答案"
unCheckedChildren="错误答案"
onChange={(value) => {
onValueChange(index, {
...data,
isanswer: value,
});
}}
/>
</div>
) : null;
};
// 选项数据处理组件
interface OptionViewProps {
type: number;
onChange?: (value: string) => void;
}
const OptionView = (props: OptionViewProps) => {
const { type, onChange = (value: string) => {} } = props;
const [callBackData, setcallBackData] = useState('');
const [radioValue, setradioValue] = useState<any>(1);
const [optionsValue, setoptionsValue] = useState<Array<any>>([
{ name: 'A', content: '', isanswer: false },
{ name: 'B', content: '', isanswer: false },
{ name: 'C', content: '', isanswer: false },
{ name: 'D', content: '', isanswer: false },
]);
// 处理判断题选项数据格式
const getJudgmentData = useCallback((value: any) => {
const data = {
answer: value === 1 ? true : false,
};
return JSON.stringify(data);
}, []);
// 处理选择题数据
const getSelectData = useCallback((data: Array<any>) => {
const newData: Array<any> = [];
// 处理空选项数据
data.map((item: any, index: number) => {
// Bin: 更多数据校对规则可以添加到这里
if (!item || !item?.content) {
// 判断选项为空或者选项数据内容为空
return null;
}
newData.push(item);
return item;
});
return JSON.stringify(newData);
}, []);
// 选择题型选项数据改变监听
useEffect(() => {
if (optionsValue) {
const data = getSelectData(optionsValue);
setcallBackData(data);
}
}, [optionsValue, getSelectData]);
// 组件数据改变回调
useEffect(() => {
if (callBackData) {
onChange(callBackData);
}
}, [callBackData, onChange]);
// 组件数据初始化,实现切换组件类型也能回调数据改变
useEffect(() => {
if (type == null || (!radioValue && !optionsValue)) {
return;
}
if (type === 3) {
setcallBackData(getJudgmentData(radioValue));
}
if (type === 0 || type === 1) {
setcallBackData(getSelectData(optionsValue));
}
}, [type, setcallBackData, radioValue, optionsValue, getJudgmentData, getSelectData]);
// 判断题
if (type === 3) {
return (
<Form.Group>
<RadioGroup
onChange={(value) => {
setradioValue(value);
const data = getJudgmentData(value);
setcallBackData(data);
}}
inline
value={radioValue}
>
<Radio value={1}>正确</Radio>
<Radio value={0}>错误</Radio>
</RadioGroup>
</Form.Group>
);
}
// 选择题(包括多选和单选)
return (
<div>
{optionsValue?.map((item: any, index: number) =>
item ? (
<OptionsItem
key={JSON.stringify(item) + '_' + index}
data={item}
index={index}
onValueChange={(id: number, data: any) => {
// id 为数据序号,data 为改变后的数据
optionsValue[id] = {
...optionsValue[id],
...data,
};
setoptionsValue([...optionsValue]);
// console.log('数据改变', id, data);
}}
onDeleteValue={(id: number, item: any) => {
let data: Array<any> = optionsValue;
const start = data.slice(0, id);
const end = data.slice(id + 1, data.length);
data = [...start, ...end];
// 处理序号名称
data = data.map((item: any, index: number) => {
return {
...item,
name: getSerialStr(index),
};
});
setoptionsValue([...data]);
}}
/>
) : null
)}
<Button
style={{ width: '100%', marginTop: 25 }}
onClick={() => {
setoptionsValue([
...optionsValue,
{ name: getSerialStr(optionsValue?.length), content: '', isanswer: false },
]);
}}
>
<ExpandOutlineIcon style={{ marginRight: 10 }} />
增加选项
</Button>
</div>
);
};
export default function QuestionCreate() {
const navigate = useNavigate();
const [createConfig, setcreateConfig] = useState<any>({
content: '',
type: 0,
netLoading: false,
});
const refOptionsData = useRef<any>('');
const __APIcreateQuestion = (type: number, content: string, options: string) => {
if (createConfig?.netLoading) {
return;
}
if (!content || !options) {
toaster.push(<Message>题目内容或选项数据不完整。</Message>);
return;
}
setcreateConfig({
...createConfig,
netLoading: true,
});
const msgTitle = '提交题目';
const params = {
type,
content,
options,
};
axios
.post('/api/question/add', params, {})
.then((res: any) => {
setcreateConfig({
...createConfig,
netLoading: false,
});
const { data } = res;
if (data?.code !== 200 || !data?.data) {
toaster.push(<Message>{data?.msg || msgTitle + '失败,请稍后重试!'}</Message>);
} else {
// console.log('成功', data);
toaster.push(<Message>{msgTitle + '成功。'}</Message>);
// 成功,关闭弹窗,刷新列表数据,
setcreateConfig({
content: '',
type: createConfig?.type,
netLoading: false,
});
// 清空编辑框数据
__emptyCreateConfig();
}
})
.catch((error: any) => {
setcreateConfig({
...createConfig,
netLoading: false,
});
toaster.push(<Message>{error + '' || msgTitle + '失败,请稍后重试!'}</Message>);
});
};
/**
* @description: 清空 CreateConfig 已输入数据
* @param {*}
* @return {*}
*/
const __emptyCreateConfig = () => {
const typeOld = createConfig?.type;
setcreateConfig({
type: null,
});
refOptionsData.current = null;
setTimeout(() => {
setcreateConfig({
content: '',
type: typeOld,
netLoading: false,
});
}, 100);
};
const [emptyModalConfig, setemptyModalConfig] = useState({
showModal: false,
});
/**
* @description: 检查选项数据是否合规,通过返回 null,不合规则返回提示信息
* @param {number} type
* @param {string} options
* @return @return {null | string}
*/
const __checkOptionsCompliance = (type: number, options: string) => {
if (!options) {
return '选项数据为空';
}
// 判断题暂不判断数据合格性
if (type === 3) {
return null;
}
// 选择题选项数据监测
try {
const optionsObj = JSON.parse(options);
if (typeof optionsObj !== 'object') {
return '选项数据异常';
}
let warningStr = null;
let existCorrectOption = false;
optionsObj.map((item: any, index: number) => {
if (item?.isanswer) {
// 遍历选项后发现存在正确答案
existCorrectOption = true;
}
return item;
});
if (optionsObj?.length < 2) {
return '选项不得少于两个';
}
if (!existCorrectOption) {
return '必须有至少一个正确选项';
}
if (warningStr) {
return warningStr;
}
return null;
} catch (error: any) {
return '选项数据可能不是 JSON 格式';
}
};
return (
<div className="container">
<AppHead />
<div className="context control">
<div className="layout content">
<div className="content_app">
<div>
<Row style={{ display: 'flex', padding: 10 }}>
<h4 style={{ fontWeight: 300 }}>添加题目</h4>
<div style={{ flex: 1 }} />
<Button
style={{ marginRight: 10 }}
disabled={refOptionsData.current && createConfig?.content ? false : true}
onClick={() => {
setemptyModalConfig({
showModal: true,
});
}}
>
清空数据
</Button>
<Button
appearance="primary"
disabled={refOptionsData.current && createConfig?.content ? false : true}
onClick={() => {
// 题目数据 createConfig
// 选项数据 refOptionsData.current
// console.log('题目数据', createConfig);
// console.log('选项数据', refOptionsData.current);
const warningMsg = __checkOptionsCompliance(
createConfig?.type,
refOptionsData.current
);
if (warningMsg) {
toaster.push(<Message>{warningMsg}</Message>);
return;
}
__APIcreateQuestion(
createConfig?.type,
createConfig?.content,
refOptionsData.current
);
}}
>
确认提交
</Button>
</Row>
<Divider style={{ margin: 0 }} />
</div>
<div style={{ padding: '10px 0' }}>
<Breadcrumb>
<Breadcrumb.Item
onClick={() => {
navigate('/control/', {
replace: true,
});
}}
>
控制中心
</Breadcrumb.Item>
<Breadcrumb.Item active>添加题目</Breadcrumb.Item>
</Breadcrumb>
</div>
<div style={{ flex: 1, width: '100%', margin: '0 auto', paddingTop: 30, maxWidth: 700 }}>
<Form
fluid
onChange={(data) => {
setcreateConfig({
...setcreateConfig,
...data,
});
}}
formValue={createConfig}
>
<Form.Group>
<Form.ControlLabel>
<b>题目类型</b>
</Form.ControlLabel>
<Form.Control name="type" accepter={RadioGroup} inline>
<Radio value={3}>判断题</Radio>
<Radio value={0}>选择题</Radio>
<Radio value={1}>多选题</Radio>
</Form.Control>
</Form.Group>
<Form.Group>
<Form.ControlLabel>
<b>题目内容</b>
</Form.ControlLabel>
<Form.Control name="content" type="content" style={{ width: '100%' }} />
</Form.Group>
<Form.Group>
<Form.ControlLabel>
<b>题目选项</b>
</Form.ControlLabel>
{createConfig?.type !== null ? (
<div>
<OptionView
type={createConfig?.type}
onChange={(value: string) => {
// 选项数据不能直接写入 createConfig ,不然会导致组件刷新死循环
refOptionsData.current = value;
}}
/>
</div>
) : null}
</Form.Group>
</Form>
</div>
</div>
<Modal
backdrop="static"
role="alertdialog"
open={emptyModalConfig.showModal}
onClose={() =>
setemptyModalConfig({
showModal: false,
})
}
size="xs"
>
<Modal.Body>你确定要清空输入的题目数据吗?清空之后需要重新填写全部内容,不可恢复。</Modal.Body>
<Modal.Footer>
<Button
onClick={() =>
setemptyModalConfig({
showModal: false,
})
}
appearance="subtle"
>
取消
</Button>
<Button
onClick={() => {
__emptyCreateConfig();
setemptyModalConfig({
showModal: false,
});
}}
appearance="primary"
>
确定
</Button>
</Modal.Footer>
</Modal>
</div>
</div>
<AppFooter />
</div>
);
} | the_stack |
import assert = require('assert');
import { clone, copy } from '../src/clone';
import { detectType } from '../src/detector';
const supportsSymbol =
typeof Symbol === 'function' && typeof Symbol() === 'symbol';
describe('clone', function () {
describe('clone', function () {
describe('should return deep copied value', function () {
it('ArrayBuffer', function () {
if (
typeof ArrayBuffer === 'undefined' ||
typeof Uint8Array === 'undefined'
) {
return this.skip();
}
const data = new ArrayBuffer(3);
const result = clone(data, detectType(data)) as ArrayBuffer;
assert(result instanceof ArrayBuffer);
assert(result !== data);
const a = new Uint8Array(data);
const b = new Uint8Array(result);
b[0] = 1;
b[1] = 2;
b[2] = 3;
a[0] = 4;
a[1] = 5;
a[2] = 6;
assert(b[0] === 1);
assert(b[1] === 2);
assert(b[2] === 3);
});
it('Boolean', function () {
const data = new Boolean(false);
// eslint-disable-next-line @typescript-eslint/ban-types
const result = clone(data, detectType(data)) as Boolean;
assert(result instanceof Boolean);
assert(result !== data);
assert(data.valueOf() === result.valueOf());
});
it('Buffer', function () {
if (typeof Buffer === 'undefined') {
return this.skip();
}
const data = Buffer.from([0xe5, 0xaf, 0xbf, 0xe5, 0x8f, 0xb8]);
const result = clone(data, detectType(data)) as Buffer;
assert(result instanceof Buffer);
assert(result !== data);
assert(data.toString('utf8') === result.toString('utf8'));
data[0] = 0xe5;
data[1] = 0xae;
data[2] = 0xae;
assert(data.toString('utf8') !== result.toString('utf8'));
});
it('DataView', function () {
if (
typeof DataView === 'undefined' ||
typeof ArrayBuffer === 'undefined'
) {
return this.skip();
}
const data = new DataView(new ArrayBuffer(5));
const result = clone(data, detectType(data)) as DataView;
assert(result instanceof DataView);
assert(result !== data);
});
it('Date', function () {
const data = new Date();
const result = clone(data, detectType(data)) as Date;
assert(result instanceof Date);
assert(result !== data);
assert(data.getTime() === result.getTime());
});
it('Number', function () {
const data = new Number(65535);
// eslint-disable-next-line @typescript-eslint/ban-types
const result = clone(data, detectType(data)) as Number;
assert(result instanceof Number);
assert(result !== data);
assert(data.valueOf() === result.valueOf());
});
it('RegExp', function () {
const data = new RegExp('', 'i');
const result = clone(data, detectType(data)) as RegExp;
assert(result instanceof RegExp);
assert(result !== data);
assert(result.source === data.source);
assert(result.flags === data.flags);
});
it('String', function () {
const data = new String('Hello!');
// eslint-disable-next-line @typescript-eslint/ban-types
const result = clone(data, detectType(data)) as String;
assert(result instanceof String);
assert(result !== data);
assert(data.valueOf() === result.valueOf());
});
it('Float32Array', function () {
if (typeof Float32Array === 'undefined') {
return this.skip();
}
const data = new Float32Array([1, 2, 3]);
const result = clone(data, detectType(data)) as Float32Array;
assert(result instanceof Float32Array);
assert(result !== data);
data[0] = 4;
data[1] = 5;
data[2] = 6;
assert(result[0] === 1);
assert(result[1] === 2);
assert(result[2] === 3);
});
it('Float64Array', function () {
if (typeof Float64Array === 'undefined') {
return this.skip();
}
const data = new Float64Array([1, 2, 3]);
const result = clone(data, detectType(data)) as Float64Array;
assert(result instanceof Float64Array);
assert(result !== data);
data[0] = 4;
data[1] = 5;
data[2] = 6;
assert(result[0] === 1);
assert(result[1] === 2);
assert(result[2] === 3);
});
it('Int16Array', function () {
if (typeof Int16Array === 'undefined') {
return this.skip();
}
const data = new Int16Array([1, 2, 3]);
const result = clone(data, detectType(data)) as Int16Array;
assert(result instanceof Int16Array);
assert(result !== data);
data[0] = 4;
data[1] = 5;
data[2] = 6;
assert(result[0] === 1);
assert(result[1] === 2);
assert(result[2] === 3);
});
it('Int32Array', function () {
if (typeof Int32Array === 'undefined') {
return this.skip();
}
const data = new Int32Array([1, 2, 3]);
const result = clone(data, detectType(data)) as Int32Array;
assert(result instanceof Int32Array);
assert(result !== data);
data[0] = 4;
data[1] = 5;
data[2] = 6;
assert(result[0] === 1);
assert(result[1] === 2);
assert(result[2] === 3);
});
it('Int8Array', function () {
if (typeof Int8Array === 'undefined') {
return this.skip();
}
const data = new Int8Array([1, 2, 3]);
const result = clone(data, detectType(data)) as Int8Array;
assert(result instanceof Int8Array);
assert(result !== data);
data[0] = 4;
data[1] = 5;
data[2] = 6;
assert(result[0] === 1);
assert(result[1] === 2);
assert(result[2] === 3);
});
it('Uint16Array', function () {
if (typeof Uint16Array === 'undefined') {
return this.skip();
}
const data = new Uint16Array([1, 2, 3]);
const result = clone(data, detectType(data)) as Uint16Array;
assert(result instanceof Uint16Array);
assert(result !== data);
data[0] = 4;
data[1] = 5;
data[2] = 6;
assert(result[0] === 1);
assert(result[1] === 2);
assert(result[2] === 3);
});
it('Uint32Array', function () {
if (typeof Uint32Array === 'undefined') {
return this.skip();
}
const data = new Uint32Array([1, 2, 3]);
const result = clone(data, detectType(data)) as Uint32Array;
assert(result instanceof Uint32Array);
assert(result !== data);
data[0] = 4;
data[1] = 5;
data[2] = 6;
assert(result[0] === 1);
assert(result[1] === 2);
assert(result[2] === 3);
});
it('Uint8Array', function () {
if (typeof Uint8Array === 'undefined') {
return this.skip();
}
const data = new Uint8Array([1, 2, 3]);
const result = clone(data, detectType(data)) as Uint8Array;
assert(result instanceof Uint8Array);
assert(result !== data);
data[0] = 4;
data[1] = 5;
data[2] = 6;
assert(result[0] === 1);
assert(result[1] === 2);
assert(result[2] === 3);
});
it('Uint8ClampedArray', function () {
if (typeof Uint8ClampedArray === 'undefined') {
return this.skip();
}
const data = new Uint8ClampedArray([1, 2, 3]);
const result = clone(data, detectType(data)) as Uint8ClampedArray;
assert(result instanceof Uint8ClampedArray);
assert(result !== data);
data[0] = 4;
data[1] = 5;
data[2] = 6;
assert(result[0] === 1);
assert(result[1] === 2);
assert(result[2] === 3);
});
});
describe('should return shallow copied value', function () {
it('Array Iterator', function () {
if (!supportsSymbol) {
return this.skip();
}
const data = [1, 2, 3][Symbol.iterator]();
const result = clone(
data,
detectType(data)
) as IterableIterator<number>;
assert(result === data);
});
it('Map Iterator', function () {
if (!supportsSymbol) {
return this.skip();
}
const data = new Map<number, number>([
[0, 1],
[1, 2],
[2, 3]
])[Symbol.iterator]();
const result = clone(data, detectType(data)) as IterableIterator<
[number, number]
>;
assert(result === data);
});
it('Promise', function () {
const data = new Promise<number>(function (resolve): void {
return resolve(1);
});
const result = clone(data, detectType(data)) as Promise<number>;
assert(result === data);
});
it('Set Iterator', function () {
if (!supportsSymbol) {
return this.skip();
}
const data = new Set<number>([1, 2, 3])[Symbol.iterator]();
const result = clone(
data,
detectType(data)
) as IterableIterator<number>;
assert(result === data);
});
it('String Iterator', function () {
if (!supportsSymbol) {
return this.skip();
}
const data = '寿司'[Symbol.iterator]();
const result = clone(
data,
detectType(data)
) as IterableIterator<string>;
assert(result === data);
});
it('function', function () {
const data = function (): void {
return;
};
const result = clone(data, detectType(data)) as () => void;
assert(result === data);
});
it('global', function () {
if (typeof globalThis !== 'undefined') {
assert(globalThis === clone(globalThis, detectType(globalThis)));
} else if (typeof self !== 'undefined') {
assert(self === clone(self, detectType(self)));
} else if (typeof global !== 'undefined') {
assert(global === clone(global, detectType(global)));
} else {
assert(false);
}
});
it('WeakMap', function () {
const data = new WeakMap<Record<string, unknown>, unknown>();
const result = clone(data, detectType(data)) as WeakMap<
Record<string, unknown>,
unknown
>;
assert(result === data);
});
it('WeakSet', function () {
const data = new WeakSet<Record<string, unknown>>();
const result = clone(data, detectType(data)) as WeakSet<
Record<string, unknown>
>;
assert(result === data);
});
it('boolean', function () {
assert(clone(true, detectType(true)) === true);
assert(clone(false, detectType(false)) === false);
});
it('null', function () {
assert(clone(null, detectType(null)) === null);
});
it('number', function () {
assert(clone(0, detectType(0)) === 0);
assert(
clone(
Number.MAX_SAFE_INTEGER,
detectType(Number.MAX_SAFE_INTEGER)
) === Number.MAX_SAFE_INTEGER
);
assert(
clone(
Number.MIN_SAFE_INTEGER,
detectType(Number.MIN_SAFE_INTEGER)
) === Number.MIN_SAFE_INTEGER
);
assert(
clone(
Number.POSITIVE_INFINITY,
detectType(Number.POSITIVE_INFINITY)
) === Number.POSITIVE_INFINITY
);
assert(
clone(
Number.NEGATIVE_INFINITY,
detectType(Number.NEGATIVE_INFINITY)
) === Number.NEGATIVE_INFINITY
);
assert(Number.isNaN(clone(NaN, detectType(NaN)) as number));
});
it('string', function () {
assert(clone('寿司', detectType('寿司')) === '寿司');
});
it('symbol', function () {
if (!supportsSymbol) {
return this.skip();
}
const data = Symbol();
const result = clone(data, detectType(data)) as symbol;
assert(result === data);
});
it('undefined', function () {
assert(clone(undefined, detectType(undefined)) === undefined);
});
});
describe('should return empty collection', function () {
it('Arguments', function () {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
(function (one: number, two: number, three: number): void {
const result = clone(
// eslint-disable-next-line prefer-rest-params
arguments,
// eslint-disable-next-line prefer-rest-params
detectType(arguments)
) as Array<number>;
assert(Array.isArray(result));
assert(result.length === 0);
})(1, 2, 3);
});
it('Array', function () {
const data = [1, 2, 3];
const result = clone(data, detectType(data)) as Array<number>;
assert(Array.isArray(result));
assert(result.length === 0);
});
it('Map', function () {
const data = new Map<number, number>([
[0, 1],
[1, 2],
[2, 3]
]);
const result = clone(data, detectType(data)) as Map<number, number>;
assert(result instanceof Map);
assert(result.size === 0);
});
it('Object', function () {
const data = { a: 1, b: 2, c: 3 };
const result = clone(data, detectType(data)) as Record<string, number>;
assert(result instanceof Object);
assert(Object.keys(result).length === 0);
});
it('Set', function () {
const data = new Set<number>([1, 2, 3]);
const result = clone(data, detectType(data)) as Set<number>;
assert(result instanceof Set);
assert(result.size === 0);
});
});
});
describe('copy', function () {
it('should return customized value', function () {
class A {
isA(): void {
console.log('Hello!');
}
}
const data = new A();
function customizer(value: unknown): A | undefined {
if (value instanceof A) {
return new A();
}
}
const result = copy(data, detectType(data), customizer) as A;
assert(result instanceof A);
assert(result !== data);
assert(typeof result.isA === 'function');
});
});
}); | the_stack |
import {
computeDataSeriesExtent,
getRendererType,
} from './line_chart_internal_utils';
import * as libUtils from './lib/utils';
import {RendererType, ScaleType} from './lib/public_types';
import {buildSeries, buildMetadata} from './lib/testing';
import {createScale} from './lib/scale';
function isFinite(x: number): boolean {
return Number.isFinite(x);
}
describe('line_chart_v2/line_chart_internal_utils test', () => {
describe('#computeDataSeriesExtent', () => {
it('returns min and max from all series', () => {
const actual = computeDataSeriesExtent(
[
buildSeries({
id: 'foo',
points: [
{x: 1, y: 100},
{x: 2, y: -10},
{x: 3, y: -100},
],
}),
buildSeries({
id: 'bar',
points: [
{x: -100, y: 0},
{x: 0, y: -1},
{x: -1000, y: 1},
],
}),
],
{
foo: buildMetadata({id: 'foo', visible: true}),
bar: buildMetadata({id: 'bar', visible: true}),
},
false,
isFinite,
isFinite
);
expect(actual).toEqual({x: [-1000, 3], y: [-100, 100]});
});
it('handles single dataSeries point', () => {
const actual = computeDataSeriesExtent(
[
buildSeries({
id: 'foo',
points: [{x: 1, y: -1}],
}),
],
{
foo: buildMetadata({id: 'foo', visible: true}),
},
false,
isFinite,
isFinite
);
expect(actual).toEqual({x: [1, 1], y: [-1, -1]});
});
it('handles two dataSeries point', () => {
const actual = computeDataSeriesExtent(
[
buildSeries({
id: 'foo',
points: [{x: 1, y: -1}],
}),
buildSeries({
id: 'bar',
points: [{x: -10, y: 10}],
}),
],
{
foo: buildMetadata({id: 'foo', visible: true}),
bar: buildMetadata({id: 'bar', visible: true}),
},
false,
isFinite,
isFinite
);
expect(actual).toEqual({x: [-10, 1], y: [-1, 10]});
});
it('ignores dataseries that is visibility=false', () => {
const actual = computeDataSeriesExtent(
[
buildSeries({
id: 'foo',
points: [
{x: 1, y: -1},
{x: 2, y: -10},
{x: 3, y: 100},
],
}),
buildSeries({
id: 'bar',
points: [
{x: -100, y: 0},
{x: -1000, y: 1},
],
}),
],
{
foo: buildMetadata({id: 'foo', visible: true}),
bar: buildMetadata({id: 'bar', visible: false}),
},
false,
isFinite,
isFinite
);
expect(actual).toEqual({x: [1, 3], y: [-10, 100]});
});
it('ignores dataseries that is aux', () => {
const actual = computeDataSeriesExtent(
[
buildSeries({
id: 'foo',
points: [
{x: 1, y: -1},
{x: 2, y: -10},
{x: 3, y: 100},
],
}),
buildSeries({
id: 'bar',
points: [
{x: -100, y: 0},
{x: -1000, y: 1},
],
}),
],
{
foo: buildMetadata({id: 'foo', visible: true, aux: true}),
bar: buildMetadata({id: 'bar'}),
},
false,
isFinite,
isFinite
);
expect(actual).toEqual({x: [-1000, -100], y: [0, 1]});
});
it('ignores dataseries without metadata', () => {
const actual = computeDataSeriesExtent(
[
buildSeries({id: 'foo', points: [{x: 1, y: -1}]}),
buildSeries({
id: 'bar',
points: [
{x: -100, y: 0},
{x: -1000, y: 1},
],
}),
],
{
bar: buildMetadata({id: 'bar'}),
},
false,
isFinite,
isFinite
);
expect(actual).toEqual({x: [-1000, -100], y: [0, 1]});
});
it('filters out NaN and infinity', () => {
const actual = computeDataSeriesExtent(
[
buildSeries({
id: 'foo',
points: [
{x: 1, y: -1},
{x: 2, y: Infinity},
{x: 3, y: NaN},
{x: 4, y: -1},
],
}),
],
{
foo: buildMetadata({id: 'foo'}),
},
false,
isFinite,
isFinite
);
expect(actual).toEqual({x: [1, 4], y: [-1, -1]});
});
it('returns undefined when nothing is visible', () => {
const actual = computeDataSeriesExtent(
[
buildSeries({
id: 'foo',
points: [
{x: 1, y: -1},
{x: 2, y: -10},
{x: 3, y: 100},
],
}),
buildSeries({
id: 'bar',
points: [
{x: -100, y: 0},
{x: -1000, y: 1},
],
}),
],
{
foo: buildMetadata({id: 'foo', visible: false}),
bar: buildMetadata({id: 'bar', visible: false}),
},
false,
isFinite,
isFinite
);
expect(actual).toEqual({
x: undefined,
y: undefined,
});
});
it('returns undefined when dataSeries is empty', () => {
const actual = computeDataSeriesExtent([], {}, false, isFinite, isFinite);
expect(actual).toEqual({
x: undefined,
y: undefined,
});
});
it('returns undefined when dataSeries is all NaN', () => {
const actual = computeDataSeriesExtent(
[
buildSeries({
id: 'foo',
points: [
{x: NaN, y: NaN},
{x: NaN, y: NaN},
],
}),
],
{
foo: buildMetadata({id: 'foo', visible: true}),
},
false,
isFinite,
isFinite
);
expect(actual).toEqual({
x: undefined,
y: undefined,
});
});
describe('ignoreOutlier', () => {
it('filters out outliers in y-extent', () => {
const actual = computeDataSeriesExtent(
[
buildSeries({
id: 'bar',
points: [
{x: 1, y: -100},
{x: 2, y: 100},
{x: 3, y: -5},
],
}),
buildSeries({
id: 'foo',
points: [
{x: 3, y: -5},
{x: 4, y: 0},
{x: 5, y: 5},
],
}),
],
{
foo: buildMetadata({id: 'foo', visible: true}),
bar: buildMetadata({id: 'bar', visible: true}),
},
true,
isFinite,
isFinite
);
expect(actual).toEqual({
x: [1, 5],
y: [-5, 5],
});
});
it('does not filter out values when we have two values', () => {
const actual = computeDataSeriesExtent(
[
buildSeries({
id: 'foo',
points: [
{x: 0, y: NaN},
{x: 1, y: -100},
{x: 2, y: 100},
],
}),
],
{
foo: buildMetadata({id: 'foo', visible: true}),
},
true,
isFinite,
isFinite
);
expect(actual).toEqual({
x: [0, 2],
y: [-100, 100],
});
});
it('does not filter out values when they are constant', () => {
const actual = computeDataSeriesExtent(
[
buildSeries({
id: 'foo',
points: [
{x: 0, y: 1},
{x: 1, y: 1},
{x: 2, y: 1},
],
}),
],
{
foo: buildMetadata({id: 'foo', visible: true}),
},
true,
isFinite,
isFinite
);
expect(actual).toEqual({
x: [0, 2],
y: [1, 1],
});
});
it('filter out single outlier in values of constant', () => {
const actual = computeDataSeriesExtent(
[
buildSeries({
id: 'foo',
points: [
{x: -1, y: 0},
{x: 0, y: 1},
{x: 1, y: 1},
{x: 2, y: 1},
],
}),
],
{
foo: buildMetadata({id: 'foo', visible: true}),
},
true,
isFinite,
isFinite
);
expect(actual).toEqual({
x: [-1, 2],
y: [1, 1],
});
});
});
describe('filter for safe value', () => {
it('calculates extent after filtering based on safeValue predicate', () => {
const actual = computeDataSeriesExtent(
[
buildSeries({
id: 'foo',
points: [
{x: -1, y: 0},
{x: 0, y: 1},
{x: 1, y: 2},
{x: 2, y: 3},
],
}),
],
{
foo: buildMetadata({id: 'foo', visible: true}),
},
true,
(x: number) => x > 0,
(y: number) => y < 1
);
expect(actual).toEqual({
x: [1, 2],
y: [0, 0],
});
});
it('supports usages with line chart scale', () => {
const xScale = createScale(ScaleType.LOG10);
const yScale = createScale(ScaleType.LINEAR);
const actual = computeDataSeriesExtent(
[
buildSeries({
id: 'foo',
points: [
{x: -Infinity, y: -100},
{x: -100, y: NaN},
{x: 0, y: Infinity},
{x: 1, y: 2},
{x: 2, y: 3},
],
}),
],
{
foo: buildMetadata({id: 'foo', visible: true}),
},
false,
xScale.isSafeNumber,
yScale.isSafeNumber
);
expect(actual).toEqual({
// Filtered out non-positive values when calculating the extent
x: [1, 2],
// Filtered out NaN and non-finite values.
y: [-100, 3],
});
});
});
});
describe('#getRendererType', () => {
it('returns svg when preferred svg', () => {
expect(getRendererType(RendererType.SVG)).toBe(RendererType.SVG);
});
it('returns webgl if webgl2 is supported', () => {
spyOn(libUtils, 'isWebGl2Supported').and.returnValue(true);
expect(getRendererType(RendererType.WEBGL)).toBe(RendererType.WEBGL);
});
it('returns svg if webgl2 is not supported', () => {
spyOn(libUtils, 'isWebGl2Supported').and.returnValue(false);
expect(getRendererType(RendererType.WEBGL)).toBe(RendererType.SVG);
});
});
}); | the_stack |
import { ProviderSettings, SecureStorageProvider, Tenant, AADResource, LoginResponse, Deferred, AzureAccount, Logger, MessageDisplayer, ErrorLookup, CachingProvider, RefreshTokenPostData, AuthorizationCodePostData, TokenPostData, AccountKey, StringLookup, DeviceCodeStartPostData, DeviceCodeCheckPostData, AzureAuthType, AccountType, UserInteraction } from '../models';
import { AzureAuthError } from '../errors/AzureAuthError';
import { ErrorCodes } from '../errors/errors';
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { AccessToken, Token, TokenClaims, RefreshToken, OAuthTokenResponse } from '../models/auth';
import * as qs from 'qs';
import * as url from 'url';
export abstract class AzureAuth {
public static readonly ACCOUNT_VERSION = '2.0';
protected readonly commonTenant: Tenant = {
id: 'common',
displayName: 'common'
};
protected readonly clientId: string;
protected readonly loginEndpointUrl: string;
constructor(
protected readonly providerSettings: ProviderSettings,
protected readonly secureStorage: SecureStorageProvider,
protected readonly cachingProvider: CachingProvider,
protected readonly logger: Logger,
protected readonly messageDisplayer: MessageDisplayer,
protected readonly errorLookup: ErrorLookup,
protected readonly userInteraction: UserInteraction,
protected readonly stringLookup: StringLookup,
protected readonly azureAuthType: AzureAuthType
) {
this.clientId = providerSettings.clientId;
this.loginEndpointUrl = providerSettings.loginEndpoint;
}
protected abstract async login(tenant: Tenant, resource: AADResource): Promise<LoginResponse>;
public async startLogin(): Promise<AzureAccount | undefined> {
let loginComplete: Deferred<void> | undefined;
try {
const result = await this.login(this.commonTenant, this.providerSettings.resources.windowsManagementResource);
loginComplete = result?.authComplete;
if (!result?.response) {
this.logger.error('Authentication failed');
return undefined;
}
const account = await this.hydrateAccount(result.response.accessToken, result.response.tokenClaims);
loginComplete?.resolve();
return account;
} catch (ex) {
if (ex instanceof AzureAuthError) {
loginComplete?.reject(ex.getPrintableString());
// Let the caller deal with the error too.
throw ex;
}
this.logger.error(ex);
return undefined;
}
}
public getHomeTenant(account: AzureAccount): Tenant {
// Home is defined by the API
// Lets pick the home tenant - and fall back to commonTenant if they don't exist
return account.properties.tenants.find(t => t.tenantCategory === 'Home') ?? account.properties.tenants[0] ?? this.commonTenant;
}
public async refreshAccess(account: AzureAccount): Promise<AzureAccount> {
// Deprecated account - delete it.
if (account.key.accountVersion !== AzureAuth.ACCOUNT_VERSION) {
account.delete = true;
return account;
}
try {
const tenant = this.getHomeTenant(account);
const tokenResult = await this.getAccountSecurityToken(account, tenant.id, this.providerSettings.resources.windowsManagementResource);
if (!tokenResult) {
account.isStale = true;
return account;
}
const tokenClaims = this.getTokenClaims(tokenResult.token);
if (!tokenClaims) {
account.isStale = true;
return account;
}
return await this.hydrateAccount(tokenResult, tokenClaims);
} catch (ex) {
account.isStale = true;
// Let caller deal with it too.
throw ex;
}
}
public async hydrateAccount(token: Token | AccessToken, tokenClaims: TokenClaims): Promise<AzureAccount> {
const tenants = await this.getTenants({ ...token });
const account = this.createAccount(tokenClaims, token.key, tenants);
return account;
}
public async getAccountSecurityToken(account: AzureAccount, tenantId: string, azureResource: AADResource): Promise<Token | undefined> {
if (account.isStale === true) {
this.logger.log('Account was stale. No tokens being fetched.');
return undefined;
}
const tenant = account.properties.tenants.find(t => t.id === tenantId);
if (!tenant) {
throw new AzureAuthError(ErrorCodes.Tenant, this.errorLookup.getTenantNotFoundError({ tenantId }), undefined);
}
const cachedTokens = await this.getSavedToken(tenant, azureResource, account.key);
// Let's check to see if we can just use the cached tokens to return to the user
if (cachedTokens?.accessToken) {
let expiry = Number(cachedTokens.expiresOn);
if (Number.isNaN(expiry)) {
this.logger.log('Expiration time was not defined. This is expected on first launch');
expiry = 0;
}
const currentTime = new Date().getTime() / 1000;
let accessToken = cachedTokens.accessToken;
const remainingTime = expiry - currentTime;
const maxTolerance = 2 * 60; // two minutes
if (remainingTime < maxTolerance) {
const result = await this.refreshToken(tenant, azureResource, cachedTokens.refreshToken);
if (!result) {
return undefined;
}
accessToken = result.accessToken;
}
// Let's just return here.
if (accessToken) {
return {
...accessToken,
tokenType: 'Bearer'
};
}
}
// User didn't have any cached tokens, or the cached tokens weren't useful.
// For most users we can use the refresh token from the general microsoft resource to an access token of basically any type of resource we want.
const baseTokens = await this.getSavedToken(this.commonTenant, this.providerSettings.resources.windowsManagementResource, account.key);
if (!baseTokens) {
this.logger.error('User had no base tokens for the basic resource registered. This should not happen and indicates something went wrong with the authentication cycle');
account.isStale = true;
// Something failed with the authentication, or your tokens have been deleted from the system. Please try adding your account to Azure Data Studio again
throw new AzureAuthError(ErrorCodes.AuthError, this.errorLookup.getSimpleError(ErrorCodes.AuthError));
}
// Let's try to convert the access token type, worst case we'll have to prompt the user to do an interactive authentication.
const result = await this.refreshToken(tenant, azureResource, baseTokens.refreshToken);
if (result?.accessToken) {
return {
...result.accessToken,
tokenType: 'Bearer'
};
}
return undefined;
}
/**
* Refreshes a token, if a refreshToken is passed in then we use that. If it is not passed in then we will prompt the user for consent.
* @param tenant
* @param resource
* @param refreshToken
*/
public async refreshToken(tenant: Tenant, resource: AADResource, refreshToken: RefreshToken | undefined): Promise<OAuthTokenResponse | undefined> {
if (refreshToken) {
const postData: RefreshTokenPostData = {
grant_type: 'refresh_token',
client_id: this.clientId,
refresh_token: refreshToken.token,
tenant: tenant.id,
resource: resource.endpoint
};
return this.getToken(tenant, resource, postData);
}
return this.handleInteractionRequired(tenant, resource);
}
public async getToken(tenant: Tenant, resource: AADResource, postData: AuthorizationCodePostData | TokenPostData | RefreshTokenPostData): Promise<OAuthTokenResponse | undefined> {
const tokenUrl = `${this.loginEndpointUrl}${tenant.id}/oauth2/token`;
const response = await this.makePostRequest(tokenUrl, postData);
if (response.data.error === 'interaction_required') {
return this.handleInteractionRequired(tenant, resource);
}
if (response.data.error) {
this.logger.error('Response error!', response.data);
// Token retrival failed with an error. Open developer tools to view the error
throw new AzureAuthError(ErrorCodes.TokenRetrieval, this.errorLookup.getSimpleError(ErrorCodes.TokenRetrieval));
}
const accessTokenString = response.data.access_token;
const refreshTokenString = response.data.refresh_token;
const expiresOnString = response.data.expires_on;
return this.getTokenHelper(tenant, resource, accessTokenString, refreshTokenString, expiresOnString);
}
public getUserKey(tokenClaims: TokenClaims): string {
// Personal accounts don't have an oid when logging into the `common` tenant, but when logging into their home tenant they end up having an oid.
// This makes the key for the same account be different.
// We need to special case personal accounts.
let userKey: string;
if (tokenClaims.idp === 'live.com') { // Personal account
userKey = tokenClaims.unique_name ?? tokenClaims.email ?? tokenClaims.sub;
} else {
userKey = tokenClaims.home_oid ?? tokenClaims.oid ?? tokenClaims.unique_name ?? tokenClaims.email ?? tokenClaims.sub;
}
if (!userKey) {
this.logger.pii(tokenClaims);
throw new AzureAuthError(ErrorCodes.UserKey, this.errorLookup.getSimpleError(ErrorCodes.UserKey));
}
return userKey;
}
public async getTokenHelper(tenant: Tenant, resource: AADResource, accessTokenString: string, refreshTokenString: string, expiresOnString: string): Promise<OAuthTokenResponse | undefined> {
if (!accessTokenString) {
// No access token returned from Microsoft OAuth
throw new AzureAuthError(ErrorCodes.NoAccessTokenReturned, this.errorLookup.getSimpleError(ErrorCodes.NoAccessTokenReturned));
}
const tokenClaims = this.getTokenClaims(accessTokenString);
if (!tokenClaims) {
return undefined;
}
const userKey = this.getUserKey(tokenClaims);
if (!userKey) {
// The user had no unique identifier within AAD
throw new AzureAuthError(ErrorCodes.UniqueIdentifier, this.errorLookup.getSimpleError(ErrorCodes.UniqueIdentifier));
}
const accessToken: AccessToken = {
token: accessTokenString,
key: userKey
};
let refreshToken: RefreshToken | undefined = undefined;
if (refreshTokenString) {
refreshToken = {
token: refreshTokenString,
key: userKey
};
}
const result: OAuthTokenResponse = {
accessToken,
refreshToken,
tokenClaims,
expiresOn: expiresOnString
};
const accountKey: AccountKey = {
providerId: this.providerSettings.id,
id: userKey
};
await this.saveToken(tenant, resource, accountKey, result);
return result;
}
//#region tenant calls
public async getTenants(token: AccessToken): Promise<Tenant[]> {
interface TenantResponse { // https://docs.microsoft.com/en-us/rest/api/resources/tenants/list
id: string;
tenantId: string;
displayName?: string;
tenantCategory?: string;
}
const tenantUri = url.resolve(this.providerSettings.resources.azureManagementResource.endpoint, 'tenants?api-version=2019-11-01');
try {
const tenantResponse = await this.makeGetRequest(tenantUri, token.token);
this.logger.pii('getTenants', tenantResponse.data);
const tenants: Tenant[] = tenantResponse.data.value.map((tenantInfo: TenantResponse) => {
return {
id: tenantInfo.tenantId,
displayName: tenantInfo.displayName ?? tenantInfo.tenantId,
userId: token.key,
tenantCategory: tenantInfo.tenantCategory
} as Tenant;
});
const homeTenantIndex = tenants.findIndex(tenant => tenant.tenantCategory === 'Home');
if (homeTenantIndex >= 0) {
const homeTenant = tenants.splice(homeTenantIndex, 1);
tenants.unshift(homeTenant[0]);
}
return tenants;
} catch (ex) {
// Error retrieving tenant information
throw new AzureAuthError(ErrorCodes.Tenant, this.errorLookup.getSimpleError(ErrorCodes.Tenant), ex);
}
}
//#endregion
//#region token management
private async saveToken(tenant: Tenant, resource: AADResource, accountKey: AccountKey, { accessToken, refreshToken, expiresOn }: OAuthTokenResponse) {
if (!tenant.id || !resource.id) {
this.logger.pii('Tenant ID or resource ID was undefined', tenant, resource);
// Error when adding your account to the cache
throw new AzureAuthError(ErrorCodes.AddAccount, this.errorLookup.getSimpleError(ErrorCodes.AddAccount));
}
try {
await this.cachingProvider.set(`${accountKey.id}_access_${resource.id}_${tenant.id}`, JSON.stringify(accessToken));
await this.cachingProvider.set(`${accountKey.id}_refresh_${resource.id}_${tenant.id}`, JSON.stringify(refreshToken));
await this.cachingProvider.set(`${accountKey.id}_${tenant.id}_${resource.id}`, expiresOn);
} catch (ex) {
this.logger.error(ex);
// Error when adding your account to the cache
throw new AzureAuthError(ErrorCodes.AddAccount, this.errorLookup.getSimpleError(ErrorCodes.AddAccount));
}
}
public async getSavedToken(tenant: Tenant, resource: AADResource, accountKey: AccountKey): Promise<{ accessToken: AccessToken; refreshToken: RefreshToken; expiresOn: string; } | undefined> {
if (!tenant.id || !resource.id) {
this.logger.pii('Tenant ID or resource ID was undefined', tenant, resource);
// Error when getting your account from the cache
throw new AzureAuthError(ErrorCodes.GetAccount, this.errorLookup.getSimpleError(ErrorCodes.GetAccount));
}
let accessTokenString: string;
let refreshTokenString: string;
let expiresOn: string;
try {
accessTokenString = await this.cachingProvider.get(`${accountKey.id}_access_${resource.id}_${tenant.id}`);
refreshTokenString = await this.cachingProvider.get(`${accountKey.id}_refresh_${resource.id}_${tenant.id}`);
expiresOn = await this.cachingProvider.get(`${accountKey.id}_${tenant.id}_${resource.id}`);
} catch (ex) {
this.logger.error(ex);
// Error when getting your account from the cache
throw new AzureAuthError(ErrorCodes.GetAccount, this.errorLookup.getSimpleError(ErrorCodes.GetAccount));
}
try {
if (!accessTokenString) {
return undefined;
}
const accessToken: AccessToken = JSON.parse(accessTokenString);
let refreshToken: RefreshToken;
if (refreshTokenString) {
refreshToken = JSON.parse(refreshTokenString);
} else {
return undefined;
}
return {
accessToken, refreshToken, expiresOn
};
} catch (ex) {
this.logger.error(ex);
// Error when parsing your account from the cache
throw new AzureAuthError(ErrorCodes.ParseAccount, this.errorLookup.getSimpleError(ErrorCodes.ParseAccount));
}
}
public async deleteAccountCache(accountKey: AccountKey): Promise<void> {
const results = await this.cachingProvider.findCredentials(accountKey.id);
for (let { account } of results) {
await this.cachingProvider.remove(account);
}
}
//#endregion
//#region interaction handling
public async handleInteractionRequired(tenant: Tenant, resource: AADResource): Promise<OAuthTokenResponse | undefined> {
const shouldOpen = await this.askUserForInteraction(tenant, resource);
if (shouldOpen) {
const result = await this.login(tenant, resource);
result?.authComplete?.resolve();
return result?.response;
}
return undefined;
}
/**
* Asks the user if they would like to do the interaction based authentication as required by OAuth2
* @param tenant
* @param resource
*/
private async askUserForInteraction(tenant: Tenant, resource: AADResource): Promise<boolean> {
return this.userInteraction.askForConsent(this.stringLookup.getInteractionRequiredString({ tenant, resource }));
}
//#endregion
//#region data modeling
public createAccount(tokenClaims: TokenClaims, key: string, tenants: Tenant[]): AzureAccount {
// Determine if this is a microsoft account
let accountType: AccountType;
if (tokenClaims?.idp === 'live.com') {
accountType = AccountType.Microsoft;
} else {
accountType = AccountType.WorkSchool;
}
const name = tokenClaims.name ?? tokenClaims.email ?? tokenClaims.unique_name;
const email = tokenClaims.email ?? tokenClaims.unique_name;
let displayName = name;
if (email) {
displayName = `${displayName} - ${email}`;
}
const account: AzureAccount = {
key: {
providerId: this.providerSettings.id,
id: key,
accountVersion: AzureAuth.ACCOUNT_VERSION,
},
displayInfo: {
accountType,
userId: key,
displayName,
email,
name,
},
properties: {
providerSettings: this.providerSettings,
isMsAccount: accountType === AccountType.Microsoft,
tenants,
azureAuthType: this.azureAuthType
},
isStale: false
};
return account;
}
//#endregion
//#region network functions
public async makePostRequest(url: string, postData: AuthorizationCodePostData | TokenPostData | DeviceCodeStartPostData | DeviceCodeCheckPostData): Promise<AxiosResponse<any>> {
const config: AxiosRequestConfig = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
validateStatus: () => true // Never throw
};
// Intercept response and print out the response for future debugging
const response = await axios.post(url, qs.stringify(postData), config);
this.logger.pii(url, postData, response.data);
return response;
}
private async makeGetRequest(url: string, token: string): Promise<AxiosResponse<any>> {
const config: AxiosRequestConfig = {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
validateStatus: () => true // Never throw
};
const response = await axios.get(url, config);
this.logger.pii(url, response.data);
return response;
}
//#endregion
//#region utils
protected getTokenClaims(accessToken: string): TokenClaims | undefined {
try {
const split = accessToken.split('.');
return JSON.parse(Buffer.from(split[1], 'base64').toString('binary'));
} catch (ex) {
throw new Error('Unable to read token claims: ' + JSON.stringify(ex));
}
}
protected toBase64UrlEncoding(base64string: string): string {
return base64string.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_'); // Need to use base64url encoding
}
public async deleteAllCache(): Promise<void> {
await this.secureStorage.clear();
}
//#endregion
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* Manages a Snowflake Dataset inside an Azure Data Factory.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as azure from "@pulumi/azure";
*
* const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"});
* const exampleFactory = new azure.datafactory.Factory("exampleFactory", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* });
* const exampleLinkedServiceSnowflake = new azure.datafactory.LinkedServiceSnowflake("exampleLinkedServiceSnowflake", {
* resourceGroupName: exampleResourceGroup.name,
* dataFactoryId: exampleFactory.id,
* connectionString: "jdbc:snowflake://account.region.snowflakecomputing.com/?user=user&db=db&warehouse=wh",
* });
* const exampleDatasetSnowflake = new azure.datafactory.DatasetSnowflake("exampleDatasetSnowflake", {
* resourceGroupName: azurerm_resource_group.test.name,
* dataFactoryId: azurerm_data_factory.test.id,
* linkedServiceName: azurerm_data_factory_linked_service_snowflake.test.name,
* schemaName: "foo_schema",
* tableName: "foo_table",
* });
* ```
*
* ## Import
*
* Data Factory Snowflake Datasets can be imported using the `resource id`,
*
* e.g.
*
* ```sh
* $ pulumi import azure:datafactory/datasetSnowflake:DatasetSnowflake example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example/providers/Microsoft.DataFactory/factories/example/datasets/example
* ```
*/
export class DatasetSnowflake extends pulumi.CustomResource {
/**
* Get an existing DatasetSnowflake 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?: DatasetSnowflakeState, opts?: pulumi.CustomResourceOptions): DatasetSnowflake {
return new DatasetSnowflake(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'azure:datafactory/datasetSnowflake:DatasetSnowflake';
/**
* Returns true if the given object is an instance of DatasetSnowflake. 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 DatasetSnowflake {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === DatasetSnowflake.__pulumiType;
}
/**
* A map of additional properties to associate with the Data Factory Dataset Snowflake.
*/
public readonly additionalProperties!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* List of tags that can be used for describing the Data Factory Dataset Snowflake.
*/
public readonly annotations!: pulumi.Output<string[] | undefined>;
/**
* The Data Factory ID in which to associate the Linked Service with. Changing this forces a new resource.
*/
public readonly dataFactoryId!: pulumi.Output<string>;
/**
* The Data Factory name in which to associate the Linked Service with. Changing this forces a new resource.
*
* @deprecated `data_factory_name` is deprecated in favour of `data_factory_id` and will be removed in version 3.0 of the AzureRM provider
*/
public readonly dataFactoryName!: pulumi.Output<string>;
/**
* The description for the Data Factory Dataset Snowflake.
*/
public readonly description!: pulumi.Output<string | undefined>;
/**
* The folder that this Dataset is in. If not specified, the Dataset will appear at the root level.
*/
public readonly folder!: pulumi.Output<string | undefined>;
/**
* The Data Factory Linked Service name in which to associate the Dataset with.
*/
public readonly linkedServiceName!: pulumi.Output<string>;
/**
* Specifies the name of the Data Factory Dataset Snowflake. Changing this forces a new resource to be created. Must be globally unique. See the [Microsoft documentation](https://docs.microsoft.com/en-us/azure/data-factory/naming-rules) for all restrictions.
*/
public readonly name!: pulumi.Output<string>;
/**
* A map of parameters to associate with the Data Factory Dataset Snowflake.
*/
public readonly parameters!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* The name of the resource group in which to create the Data Factory Dataset Snowflake. Changing this forces a new resource
*/
public readonly resourceGroupName!: pulumi.Output<string>;
/**
* A `schemaColumn` block as defined below.
*/
public readonly schemaColumns!: pulumi.Output<outputs.datafactory.DatasetSnowflakeSchemaColumn[] | undefined>;
/**
* The schema name of the Data Factory Dataset Snowflake.
*/
public readonly schemaName!: pulumi.Output<string | undefined>;
/**
* @deprecated This block has been deprecated in favour of `schema_column` and will be removed.
*/
public readonly structureColumns!: pulumi.Output<outputs.datafactory.DatasetSnowflakeStructureColumn[] | undefined>;
/**
* The table name of the Data Factory Dataset Snowflake.
*/
public readonly tableName!: pulumi.Output<string | undefined>;
/**
* Create a DatasetSnowflake 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: DatasetSnowflakeArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: DatasetSnowflakeArgs | DatasetSnowflakeState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as DatasetSnowflakeState | undefined;
inputs["additionalProperties"] = state ? state.additionalProperties : undefined;
inputs["annotations"] = state ? state.annotations : undefined;
inputs["dataFactoryId"] = state ? state.dataFactoryId : undefined;
inputs["dataFactoryName"] = state ? state.dataFactoryName : undefined;
inputs["description"] = state ? state.description : undefined;
inputs["folder"] = state ? state.folder : undefined;
inputs["linkedServiceName"] = state ? state.linkedServiceName : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["parameters"] = state ? state.parameters : undefined;
inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined;
inputs["schemaColumns"] = state ? state.schemaColumns : undefined;
inputs["schemaName"] = state ? state.schemaName : undefined;
inputs["structureColumns"] = state ? state.structureColumns : undefined;
inputs["tableName"] = state ? state.tableName : undefined;
} else {
const args = argsOrState as DatasetSnowflakeArgs | undefined;
if ((!args || args.linkedServiceName === undefined) && !opts.urn) {
throw new Error("Missing required property 'linkedServiceName'");
}
if ((!args || args.resourceGroupName === undefined) && !opts.urn) {
throw new Error("Missing required property 'resourceGroupName'");
}
inputs["additionalProperties"] = args ? args.additionalProperties : undefined;
inputs["annotations"] = args ? args.annotations : undefined;
inputs["dataFactoryId"] = args ? args.dataFactoryId : undefined;
inputs["dataFactoryName"] = args ? args.dataFactoryName : undefined;
inputs["description"] = args ? args.description : undefined;
inputs["folder"] = args ? args.folder : undefined;
inputs["linkedServiceName"] = args ? args.linkedServiceName : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["parameters"] = args ? args.parameters : undefined;
inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined;
inputs["schemaColumns"] = args ? args.schemaColumns : undefined;
inputs["schemaName"] = args ? args.schemaName : undefined;
inputs["structureColumns"] = args ? args.structureColumns : undefined;
inputs["tableName"] = args ? args.tableName : undefined;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(DatasetSnowflake.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering DatasetSnowflake resources.
*/
export interface DatasetSnowflakeState {
/**
* A map of additional properties to associate with the Data Factory Dataset Snowflake.
*/
additionalProperties?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* List of tags that can be used for describing the Data Factory Dataset Snowflake.
*/
annotations?: pulumi.Input<pulumi.Input<string>[]>;
/**
* The Data Factory ID in which to associate the Linked Service with. Changing this forces a new resource.
*/
dataFactoryId?: pulumi.Input<string>;
/**
* The Data Factory name in which to associate the Linked Service with. Changing this forces a new resource.
*
* @deprecated `data_factory_name` is deprecated in favour of `data_factory_id` and will be removed in version 3.0 of the AzureRM provider
*/
dataFactoryName?: pulumi.Input<string>;
/**
* The description for the Data Factory Dataset Snowflake.
*/
description?: pulumi.Input<string>;
/**
* The folder that this Dataset is in. If not specified, the Dataset will appear at the root level.
*/
folder?: pulumi.Input<string>;
/**
* The Data Factory Linked Service name in which to associate the Dataset with.
*/
linkedServiceName?: pulumi.Input<string>;
/**
* Specifies the name of the Data Factory Dataset Snowflake. Changing this forces a new resource to be created. Must be globally unique. See the [Microsoft documentation](https://docs.microsoft.com/en-us/azure/data-factory/naming-rules) for all restrictions.
*/
name?: pulumi.Input<string>;
/**
* A map of parameters to associate with the Data Factory Dataset Snowflake.
*/
parameters?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* The name of the resource group in which to create the Data Factory Dataset Snowflake. Changing this forces a new resource
*/
resourceGroupName?: pulumi.Input<string>;
/**
* A `schemaColumn` block as defined below.
*/
schemaColumns?: pulumi.Input<pulumi.Input<inputs.datafactory.DatasetSnowflakeSchemaColumn>[]>;
/**
* The schema name of the Data Factory Dataset Snowflake.
*/
schemaName?: pulumi.Input<string>;
/**
* @deprecated This block has been deprecated in favour of `schema_column` and will be removed.
*/
structureColumns?: pulumi.Input<pulumi.Input<inputs.datafactory.DatasetSnowflakeStructureColumn>[]>;
/**
* The table name of the Data Factory Dataset Snowflake.
*/
tableName?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a DatasetSnowflake resource.
*/
export interface DatasetSnowflakeArgs {
/**
* A map of additional properties to associate with the Data Factory Dataset Snowflake.
*/
additionalProperties?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* List of tags that can be used for describing the Data Factory Dataset Snowflake.
*/
annotations?: pulumi.Input<pulumi.Input<string>[]>;
/**
* The Data Factory ID in which to associate the Linked Service with. Changing this forces a new resource.
*/
dataFactoryId?: pulumi.Input<string>;
/**
* The Data Factory name in which to associate the Linked Service with. Changing this forces a new resource.
*
* @deprecated `data_factory_name` is deprecated in favour of `data_factory_id` and will be removed in version 3.0 of the AzureRM provider
*/
dataFactoryName?: pulumi.Input<string>;
/**
* The description for the Data Factory Dataset Snowflake.
*/
description?: pulumi.Input<string>;
/**
* The folder that this Dataset is in. If not specified, the Dataset will appear at the root level.
*/
folder?: pulumi.Input<string>;
/**
* The Data Factory Linked Service name in which to associate the Dataset with.
*/
linkedServiceName: pulumi.Input<string>;
/**
* Specifies the name of the Data Factory Dataset Snowflake. Changing this forces a new resource to be created. Must be globally unique. See the [Microsoft documentation](https://docs.microsoft.com/en-us/azure/data-factory/naming-rules) for all restrictions.
*/
name?: pulumi.Input<string>;
/**
* A map of parameters to associate with the Data Factory Dataset Snowflake.
*/
parameters?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* The name of the resource group in which to create the Data Factory Dataset Snowflake. Changing this forces a new resource
*/
resourceGroupName: pulumi.Input<string>;
/**
* A `schemaColumn` block as defined below.
*/
schemaColumns?: pulumi.Input<pulumi.Input<inputs.datafactory.DatasetSnowflakeSchemaColumn>[]>;
/**
* The schema name of the Data Factory Dataset Snowflake.
*/
schemaName?: pulumi.Input<string>;
/**
* @deprecated This block has been deprecated in favour of `schema_column` and will be removed.
*/
structureColumns?: pulumi.Input<pulumi.Input<inputs.datafactory.DatasetSnowflakeStructureColumn>[]>;
/**
* The table name of the Data Factory Dataset Snowflake.
*/
tableName?: pulumi.Input<string>;
} | the_stack |
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { MatDialogRef } from '@angular/material/dialog';
import { NodesApiService, setupTestBed } from '@alfresco/adf-core';
import { FolderDialogComponent } from './folder.dialog';
import { of, throwError } from 'rxjs';
import { ContentTestingModule } from '../testing/content.testing.module';
import { By } from '@angular/platform-browser';
import { TranslateModule } from '@ngx-translate/core';
describe('FolderDialogComponent', () => {
let fixture: ComponentFixture<FolderDialogComponent>;
let component: FolderDialogComponent;
let nodesApi: NodesApiService;
const dialogRef = {
close: jasmine.createSpy('close')
};
setupTestBed({
imports: [
TranslateModule.forRoot(),
ContentTestingModule
],
providers: [
{ provide: MatDialogRef, useValue: dialogRef }
]
});
beforeEach(() => {
dialogRef.close.calls.reset();
fixture = TestBed.createComponent(FolderDialogComponent);
component = fixture.componentInstance;
nodesApi = TestBed.inject(NodesApiService);
});
afterEach(() => {
fixture.destroy();
});
describe('Edit', () => {
beforeEach(() => {
component.data = {
folder: {
id: 'node-id',
name: 'folder-name',
properties: {
['cm:title']: 'folder-title',
['cm:description']: 'folder-description'
}
}
};
fixture.detectChanges();
});
it('should init form with folder name and description', () => {
expect(component.name).toBe('folder-name');
expect(component.title).toBe('folder-title');
expect(component.description).toBe('folder-description');
});
it('should have the proper title', () => {
const title = fixture.debugElement.query(By.css('[mat-dialog-title]'));
expect(title === null).toBe(false);
expect(title.nativeElement.innerText.trim()).toBe('CORE.FOLDER_DIALOG.EDIT_FOLDER_TITLE');
});
it('should update form input', () => {
component.form.controls['name'].setValue('folder-name-update');
component.form.controls['title'].setValue('folder-title-update');
component.form.controls['description'].setValue('folder-description-update');
expect(component.name).toBe('folder-name-update');
expect(component.title).toBe('folder-title-update');
expect(component.description).toBe('folder-description-update');
});
it('should submit updated values if form is valid', () => {
spyOn(nodesApi, 'updateNode').and.returnValue(of(null));
component.form.controls['name'].setValue('folder-name-update');
component.form.controls['title'].setValue('folder-title-update');
component.form.controls['description'].setValue('folder-description-update');
component.submit();
expect(nodesApi.updateNode).toHaveBeenCalledWith(
'node-id',
{
name: 'folder-name-update',
properties: {
'cm:title': 'folder-title-update',
'cm:description': 'folder-description-update'
}
}
);
});
it('should call dialog to close with form data when submit is successfully', () => {
const folder: any = {
data: 'folder-data'
};
spyOn(nodesApi, 'updateNode').and.returnValue(of(folder));
component.submit();
expect(dialogRef.close).toHaveBeenCalledWith(folder);
});
it('should emit success output event with folder when submit is successful', async () => {
const folder: any = { data: 'folder-data' };
let expectedNode = null;
spyOn(nodesApi, 'updateNode').and.returnValue(of(folder));
component.success.subscribe((node) => { expectedNode = node; });
component.submit();
fixture.detectChanges();
await fixture.whenStable();
expect(expectedNode).toBe(folder);
});
it('should not submit if form is invalid', () => {
spyOn(nodesApi, 'updateNode');
component.form.controls['name'].setValue('');
component.form.controls['description'].setValue('');
component.submit();
expect(component.form.valid).toBe(false);
expect(nodesApi.updateNode).not.toHaveBeenCalled();
});
it('should not call dialog to close if submit fails', () => {
spyOn(nodesApi, 'updateNode').and.returnValue(throwError('error'));
spyOn(component, 'handleError').and.callFake((val) => val);
component.submit();
expect(component.handleError).toHaveBeenCalled();
expect(dialogRef.close).not.toHaveBeenCalled();
});
});
describe('Create', () => {
beforeEach(() => {
component.data = {
parentNodeId: 'parentNodeId',
folder: null
};
fixture.detectChanges();
});
it('should have the proper title', () => {
const title = fixture.debugElement.query(By.css('[mat-dialog-title]'));
expect(title === null).toBe(false);
expect(title.nativeElement.innerText.trim()).toBe('CORE.FOLDER_DIALOG.CREATE_FOLDER_TITLE');
});
it('should init form with empty inputs', () => {
expect(component.name).toBe('');
expect(component.description).toBe('');
});
it('should update form input', () => {
component.form.controls['name'].setValue('folder-name-update');
component.form.controls['description'].setValue('folder-description-update');
expect(component.name).toBe('folder-name-update');
expect(component.description).toBe('folder-description-update');
});
it('should submit updated values if form is valid', () => {
spyOn(nodesApi, 'createFolder').and.returnValue(of(null));
component.form.controls['name'].setValue('folder-name-update');
component.form.controls['title'].setValue('folder-title-update');
component.form.controls['description'].setValue('folder-description-update');
component.submit();
expect(nodesApi.createFolder).toHaveBeenCalledWith(
'parentNodeId',
{
name: 'folder-name-update',
properties: {
'cm:title': 'folder-title-update',
'cm:description': 'folder-description-update'
},
nodeType: 'cm:folder'
}
);
});
it('should submit updated values if form is valid (with custom nodeType)', () => {
spyOn(nodesApi, 'createFolder').and.returnValue(of(null));
component.form.controls['name'].setValue('folder-name-update');
component.form.controls['title'].setValue('folder-title-update');
component.form.controls['description'].setValue('folder-description-update');
component.nodeType = 'cm:sushi';
component.submit();
expect(nodesApi.createFolder).toHaveBeenCalledWith(
'parentNodeId',
{
name: 'folder-name-update',
properties: {
'cm:title': 'folder-title-update',
'cm:description': 'folder-description-update'
},
nodeType: 'cm:sushi'
}
);
});
it('should call dialog to close with form data when submit is successfully', () => {
const folder: any = {
data: 'folder-data'
};
component.form.controls['name'].setValue('name');
component.form.controls['title'].setValue('title');
component.form.controls['description'].setValue('description');
spyOn(nodesApi, 'createFolder').and.returnValue(of(folder));
component.submit();
expect(dialogRef.close).toHaveBeenCalledWith(folder);
});
it('should not submit if form is invalid', () => {
spyOn(nodesApi, 'createFolder');
component.form.controls['name'].setValue('');
component.form.controls['description'].setValue('');
component.submit();
expect(component.form.valid).toBe(false);
expect(nodesApi.createFolder).not.toHaveBeenCalled();
});
it('should not call dialog to close if submit fails', () => {
spyOn(nodesApi, 'createFolder').and.returnValue(throwError('error'));
spyOn(component, 'handleError').and.callFake((val) => val);
component.form.controls['name'].setValue('name');
component.form.controls['description'].setValue('description');
component.submit();
expect(component.handleError).toHaveBeenCalled();
expect(dialogRef.close).not.toHaveBeenCalled();
});
describe('Error events ', () => {
it('should raise error for 409', (done) => {
const error = {
message: '{ "error": { "statusCode" : 409 } }'
};
component.error.subscribe((message) => {
expect(message).toBe('CORE.MESSAGES.ERRORS.EXISTENT_FOLDER');
done();
});
spyOn(nodesApi, 'createFolder').and.returnValue(throwError(error));
component.form.controls['name'].setValue('name');
component.form.controls['description'].setValue('description');
component.submit();
});
it('should raise generic error', (done) => {
const error = {
message: '{ "error": { "statusCode" : 123 } }'
};
component.error.subscribe((message) => {
expect(message).toBe('CORE.MESSAGES.ERRORS.GENERIC');
done();
});
spyOn(nodesApi, 'createFolder').and.returnValue(throwError(error));
component.form.controls['name'].setValue('name');
component.form.controls['description'].setValue('description');
component.submit();
});
});
});
}); | the_stack |
import {Component, OnInit, ViewChild, ViewEncapsulation, ChangeDetectorRef, Inject, LOCALE_ID} from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { ToastrService } from 'ngx-toastr';
import * as _moment from 'moment';
import 'moment-timezone';
import { SchedulerService } from '../../core/services';
import { SchedulerModel, WeekdaysModel } from './scheduler.model';
import { SchedulerCalculations } from './scheduler.calculations';
import { HTTP_STATUS_CODES, CheckUtils } from '../../core/util';
import { ScheduleSchema } from './scheduler.model';
@Component({
selector: 'datalab-scheduler',
templateUrl: './scheduler.component.html',
styleUrls: ['./scheduler.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class SchedulerComponent implements OnInit {
readonly CheckUtils = CheckUtils;
public model: SchedulerModel;
public selectedStartWeekDays: WeekdaysModel = WeekdaysModel.setDefault();
public selectedStopWeekDays: WeekdaysModel = WeekdaysModel.setDefault();
public notebook: any;
public infoMessage: boolean = false;
public timeReqiered: boolean = false;
public terminateDataReqiered: boolean = false;
public inherit: boolean = false;
public allowInheritView: boolean = false;
public parentInherit: boolean = false;
public enableSchedule: boolean = false;
public enableIdleTime: boolean = false;
public enableIdleTimeView: boolean = false;
public considerInactivity: boolean = false;
public date_format: string = 'YYYY-MM-DD';
public timeFormat: string = 'HH:mm';
public weekdays: string[] = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
public schedulerForm: FormGroup;
public destination: any;
public zones: {};
public tzOffset: string = _moment().format('Z');
public startTime = SchedulerCalculations.convertTimeFormat('09:00');
public startTimeMilliseconds: number = SchedulerCalculations.setTimeInMiliseconds(this.startTime);
public endTime = SchedulerCalculations.convertTimeFormat('20:00');
public endTimeMilliseconds: number = SchedulerCalculations.setTimeInMiliseconds(this.endTime);
public terminateTime = null;
public terminateTimeMilliseconds: number;
public inactivityLimits = { min: 120, max: 10080 };
public integerRegex: string = '^[0-9]*$';
@ViewChild('resourceSelect') resource_select;
constructor(
@Inject(MAT_DIALOG_DATA) public data: any,
public toastr: ToastrService,
public dialogRef: MatDialogRef<SchedulerComponent>,
private formBuilder: FormBuilder,
private schedulerService: SchedulerService,
private changeDetector: ChangeDetectorRef
) { }
ngOnInit() {
this.open(this.data.notebook, this.data.type, this.data.resource);
}
public open(notebook, type, resource?): void {
this.notebook = notebook;
this.zones = _moment.tz.names()
.map(item => [_moment.tz(item).format('Z'), item])
.sort()
.reduce((memo, item) => {
memo[item[0]] ? memo[item[0]] += `, ${item[1]}` : memo[item[0]] = item[1];
return memo;
}, {});
this.model = new SchedulerModel(
response => {
if (response.status === HTTP_STATUS_CODES.OK) {
this.toastr.success('Schedule data were successfully saved', 'Success!');
this.dialogRef.close();
}
},
error => this.toastr.error(error.message || 'Scheduler configuration failed!', 'Oops!'),
() => {
this.formInit();
this.changeDetector.detectChanges();
this.destination = (type === 'EXPLORATORY') ? this.notebook : resource;
this.destination.type = type;
this.selectedStartWeekDays.reset();
this.selectedStopWeekDays.reset();
this.allowInheritView = false;
if (this.destination.type === 'СOMPUTATIONAL') {
this.allowInheritView = true;
this.getExploratorySchedule(this.notebook.project, this.notebook.name, this.destination.computational_name);
this.checkParentInherit();
} else if (this.destination.type === 'EXPLORATORY') {
this.allowInheritView = this.checkIsActiveSpark();
this.getExploratorySchedule(this.notebook.project, this.notebook.name);
}
},
this.schedulerService
);
}
public onDaySelect($event, day, action) {
if (action === 'start') {
this.selectedStartWeekDays[day.toLowerCase()] = $event.source.checked;
} else if (action === 'stop') {
this.selectedStopWeekDays[day.toLowerCase()] = $event.source.checked;
}
}
public toggleInherit($event) {
this.inherit = $event.checked;
if (this.destination.type === 'СOMPUTATIONAL' && this.inherit) {
this.getExploratorySchedule(this.notebook.project, this.notebook.name);
this.schedulerForm.get('startDate').disable();
this.schedulerForm.get('finishDate').disable();
} else {
this.schedulerForm.get('startDate').enable();
this.schedulerForm.get('finishDate').enable();
}
}
public toggleSchedule($event) {
this.enableSchedule = $event.checked;
this.timeReqiered = false;
this.allowInheritView = this.destination.type === 'СOMPUTATIONAL' || this.checkIsActiveSpark();
this.enableSchedule && this.enableIdleTime && this.toggleIdleTimes({ checked: false });
(this.enableSchedule && !(this.destination.type === 'СOMPUTATIONAL' && this.inherit))
? this.schedulerForm.get('startDate').enable()
: this.schedulerForm.get('startDate').disable();
this.enableSchedule && this.destination.type !== 'СOMPUTATIONAL' ?
this.schedulerForm.get('finishDate').enable() : this.schedulerForm.get('finishDate').disable();
this.enableSchedule ?
this.schedulerForm.get('terminateDate').enable() : this.schedulerForm.get('terminateDate').disable();
if (this.enableSchedule && $event.source) this.enableIdleTimeView = false;
}
public toggleIdleTimes($event) {
const control = this.schedulerForm.controls.inactivityTime;
this.enableIdleTime = $event.checked;
this.enableIdleTime && this.enableSchedule && this.toggleSchedule({ checked: false });
this.allowInheritView = false;
if (!this.enableIdleTime) {
this.allowInheritView = this.destination.type === 'СOMPUTATIONAL' || this.checkIsActiveSpark();
control.setValue('');
} else {
!control.value && control.setValue(this.inactivityLimits.min);
this.enableIdleTimeView = true;
}
}
public setInactivity(...params) {
this.model.setInactivityTime(params).subscribe((response: any) => {
if (response.status === HTTP_STATUS_CODES.OK) {
this.toastr.success('Schedule data were successfully saved', 'Success!');
this.dialogRef.close();
}
},
error => this.toastr.error(error.message || 'Scheduler configuration failed!', 'Oops!'));
}
public inactivityCounter($event, action: string): void {
$event.preventDefault();
const value = this.schedulerForm.controls.inactivityTime.value;
const newValue = (action === 'increment' ? Number(value) + 10 : Number(value) - 10);
this.schedulerForm.controls.inactivityTime.setValue(newValue);
}
public scheduleInstance_btnClick() {
if (this.enableIdleTimeView) {
this.enableIdleTime ? this.setScheduleByInactivity() : this.resetScheduler();
} else {
this.enableSchedule ? this.setScheduleByTime() : this.resetScheduler();
}
}
private resetScheduler() {
const resource = this.destination.type === 'СOMPUTATIONAL' ? this.destination.computational_name : null;
this.model.resetSchedule(this.notebook.name, resource)
.subscribe(() => {
this.resetDialog();
this.toastr.success('Schedule data were successfully deleted', 'Success!');
this.dialogRef.close();
});
}
private setScheduleByTime() {
const data = {
startDate: this.schedulerForm.controls.startDate.value,
finishDate: this.schedulerForm.controls.finishDate.value,
terminateDate: this.schedulerForm.controls.terminateDate.value
};
const terminateDateTime = (data.terminateDate && this.terminateTime)
? `${_moment(data.terminateDate).format(this.date_format)} ${SchedulerCalculations.convertTimeFormat(this.terminateTime)}`
: null;
if (!this.startTime && !this.endTime && !this.terminateTime && this.enableSchedule) {
this.timeReqiered = true;
return false;
}
if ((data.terminateDate && !this.terminateTime) || (!data.terminateDate && this.terminateTime)) {
this.terminateDataReqiered = true;
return false;
}
const selectedDays = Object.keys(this.selectedStartWeekDays);
const parameters: ScheduleSchema = {
begin_date: data.startDate ? _moment(data.startDate).format(this.date_format) : null,
finish_date: data.finishDate ? _moment(data.finishDate).format(this.date_format) : null,
start_time: this.startTime ? SchedulerCalculations.convertTimeFormat(this.startTime) : null,
end_time: this.endTime ? SchedulerCalculations.convertTimeFormat(this.endTime) : null,
start_days_repeat: selectedDays.filter(el => Boolean(this.selectedStartWeekDays[el])).map(day => day.toUpperCase()),
stop_days_repeat: selectedDays.filter(el => Boolean(this.selectedStopWeekDays[el])).map(day => day.toUpperCase()),
timezone_offset: this.tzOffset,
sync_start_required: this.inherit,
check_inactivity_required: this.enableIdleTime,
terminate_datetime: terminateDateTime
};
if (this.destination.type === 'СOMPUTATIONAL') {
this.model.confirmAction(this.notebook.project, this.notebook.name, parameters, this.destination.computational_name);
} else {
parameters['consider_inactivity'] = this.considerInactivity;
this.model.confirmAction(this.notebook.project, this.notebook.name, parameters);
}
}
private setScheduleByInactivity() {
const data = {
sync_start_required: this.parentInherit,
check_inactivity_required: this.enableIdleTime,
max_inactivity: this.schedulerForm.controls.inactivityTime.value
};
(this.destination.type === 'СOMPUTATIONAL')
? this.setInactivity(this.notebook.project, this.notebook.name, data, this.destination.computational_name)
: this.setInactivity(this.notebook.project, this.notebook.name, { ...data, consider_inactivity: this.considerInactivity });
}
private formInit(start?: string, end?: string, terminate?: string) {
this.schedulerForm = this.formBuilder.group({
startDate: { disabled: this.inherit, value: start ? _moment(start).format() : null },
finishDate: { disabled: this.inherit, value: end ? _moment(end).format() : null },
terminateDate: { disabled: false, value: terminate ? _moment(terminate).format() : null },
inactivityTime: [this.inactivityLimits.min,
[Validators.compose([Validators.pattern(this.integerRegex), this.validInactivityRange.bind(this)])]]
});
}
private getExploratorySchedule(project, resource, resource2?) {
this.schedulerService.getExploratorySchedule(project, resource, resource2).subscribe(
(params: ScheduleSchema) => {
if (params) {
params.start_days_repeat.filter(key => (this.selectedStartWeekDays[key.toLowerCase()] = true));
params.stop_days_repeat.filter(key => (this.selectedStopWeekDays[key.toLowerCase()] = true));
this.inherit = params.sync_start_required;
this.tzOffset = params.timezone_offset && params.timezone_offset !== 'Z' ? params.timezone_offset : this.tzOffset;
this.startTime = params.start_time ? SchedulerCalculations.convertTimeFormat(params.start_time) : this.startTime;
this.startTimeMilliseconds = SchedulerCalculations.setTimeInMiliseconds(this.startTime);
this.endTime = params.end_time ? SchedulerCalculations.convertTimeFormat(params.end_time) : this.endTime;
this.endTimeMilliseconds = SchedulerCalculations.setTimeInMiliseconds(this.endTime);
this.formInit(params.begin_date, params.finish_date, params.terminate_datetime);
this.schedulerForm.controls.inactivityTime.setValue(params.max_inactivity || this.inactivityLimits.min);
this.enableIdleTime = params.check_inactivity_required;
this.considerInactivity = params.consider_inactivity || false;
if (params.terminate_datetime) {
const terminate_datetime = params.terminate_datetime.split(' ');
this.schedulerForm.controls.terminateDate.setValue(terminate_datetime[0]);
this.terminateTime = SchedulerCalculations.convertTimeFormat(terminate_datetime[1]);
this.terminateTimeMilliseconds = SchedulerCalculations.setTimeInMiliseconds(this.terminateTime);
}
(this.enableIdleTime && params.max_inactivity)
? this.toggleIdleTimes({ checked: true })
: this.toggleSchedule({ checked: true });
}
},
error => this.resetDialog());
}
private checkParentInherit() {
this.schedulerService.getExploratorySchedule(this.notebook.project, this.notebook.name)
.subscribe((res: any) => this.parentInherit = res.sync_start_required);
}
private validInactivityRange(control) {
if (control)
return this.enableIdleTime
? (control.value
&& control.value >= this.inactivityLimits.min
&& control.value <= this.inactivityLimits.max ? null : { valid: false })
: control.value;
}
private checkIsActiveSpark() {
return this.notebook.resources.length > 0 && this.notebook.resources.some(el => el.image === 'docker.datalab-dataengine'
&& (el.status !== 'terminated' && el.status !== 'terminating' && el.status !== 'failed'));
}
private resetDialog() {
this.infoMessage = false;
this.timeReqiered = false;
this.terminateDataReqiered = false;
this.inherit = false;
this.enableSchedule = false;
this.considerInactivity = false;
this.enableIdleTime = false;
this.tzOffset = _moment().format('Z');
this.startTime = SchedulerCalculations.convertTimeFormat('09:00');
this.endTime = SchedulerCalculations.convertTimeFormat('20:00');
this.terminateTime = null;
this.schedulerForm.get('startDate').disable();
this.schedulerForm.get('finishDate').disable();
this.schedulerForm.get('terminateDate').disable();
}
} | the_stack |
import * as React from 'react';
import {fullscreen} from './styles/index';
import CinemaEffect from './game/CinemaEffect';
import TextBox from './game/TextBox';
import AskChoice from './game/AskChoice';
import TextInterjections from './game/TextInterjections';
import FoundObject from './game/FoundObject';
import Loader from './game/Loader';
import Video from './game/Video';
import Menu from './game/Menu';
import TeleportMenu from './game/TeleportMenu';
import Ribbon from './game/Ribbon';
import {KeyHelpIcon, KeyHelpScreen} from './game/KeyboardHelp';
import { getVideoPath } from '../resources';
import BehaviourMenu from './game/BehaviourMenu';
import Inventory from './game/Inventory';
import NoAudio from './game/NoAudio';
import UIState from './UIState';
import { SceneManager } from '../game/SceneManager';
import Renderer from '../renderer';
import Game from '../game/Game';
import { ControlsState } from '../game/ControlsState';
interface GameUIProps {
uiState: UIState;
game: Game;
renderer: Renderer;
sceneManager: SceneManager;
setUiState: (state: any, callback?: Function) => void;
sharedState?: any;
stateHandler?: any;
showMenu: (inGameMenu?: boolean) => void;
hideMenu: (wasPaused?: boolean) => void;
}
interface GameUIState {
keyHelp: boolean;
}
export default class GameUI extends React.Component<GameUIProps, GameUIState> {
constructor(props) {
super(props);
this.listenerKeyDown = this.listenerKeyDown.bind(this);
this.listenerKeyUp = this.listenerKeyUp.bind(this);
this.openKeyHelp = this.openKeyHelp.bind(this);
this.closeKeyHelp = this.closeKeyHelp.bind(this);
this.startNewGameScene = this.startNewGameScene.bind(this);
this.onMenuItemChanged = this.onMenuItemChanged.bind(this);
this.closeInventory = this.closeInventory.bind(this);
this.textAnimEndedHandler = this.textAnimEndedHandler.bind(this);
this.noAudioClick = this.noAudioClick.bind(this);
this.onAskChoiceChanged = this.onAskChoiceChanged.bind(this);
this.gamepadListener = this.gamepadListener.bind(this);
this.state = {
keyHelp: false
};
}
componentWillMount() {
window.addEventListener('keydown', this.listenerKeyDown);
window.addEventListener('keyup', this.listenerKeyUp);
window.addEventListener('lbagamepadchanged', this.gamepadListener);
}
componentWillUnmount() {
window.removeEventListener('lbagamepadchanged', this.gamepadListener);
window.removeEventListener('keyup', this.listenerKeyUp);
window.removeEventListener('keydown', this.listenerKeyDown);
}
openKeyHelp() {
this.setState({keyHelp: true});
}
closeKeyHelp() {
this.setState({keyHelp: false});
}
closeInventory() {
this.props.setUiState({inventory: false});
this.props.game.resume(false);
}
isInventoryKey(key: string | number, controlsState: ControlsState) {
return key === 'ShiftLeft' || key === 'ShiftRight' ||
controlsState?.shift === 1;
}
isBehaviourKey(key: string | number, controlsState: ControlsState) {
const isMac = /^Mac/.test(navigator && navigator.platform);
if (isMac) {
return key === 'MetaLeft' || key === 'MetaRight' || controlsState?.control === 1;
}
return key === 'ControlLeft' || key === 'ControlRight' || controlsState?.control === 1;
}
showHideMenus(key: string | number, controlsState: ControlsState) {
const {
uiState,
game,
sceneManager,
stateHandler,
sharedState
} = this.props;
if (!uiState.video) {
if (key === 'Escape' || controlsState?.home === 1) {
if (sharedState && sharedState.objectToAdd) {
stateHandler.setAddingObject(null);
} else if (uiState.teleportMenu) {
this.props.setUiState({ teleportMenu: false });
} else if (!game.isPaused()) {
this.props.showMenu(true);
} else if (uiState.showMenu && uiState.inGameMenu) {
this.props.hideMenu();
}
}
const showBehaviourMenu =
!uiState.loading &&
uiState.ask.choices.length === 0 &&
uiState.text === null &&
uiState.foundObject === null &&
!(uiState.showMenu || uiState.inGameMenu) &&
!uiState.inventory &&
!uiState.cinema;
if (showBehaviourMenu && this.isBehaviourKey(key, controlsState)) {
this.props.setUiState({ behaviourMenu: true });
const scene = sceneManager.getScene();
if (!uiState.cinema && scene && scene.actors[0]) {
scene.actors[0].cancelAnims();
}
game.pause(false);
}
const showInventory =
!uiState.loading &&
uiState.ask.choices.length === 0 &&
uiState.text === null &&
uiState.foundObject === null &&
!(uiState.showMenu || uiState.inGameMenu) &&
!uiState.behaviourMenu &&
!uiState.cinema;
if (showInventory && this.isInventoryKey(key, controlsState)) {
this.props.setUiState({ inventory: !this.props.uiState.inventory });
if (game.isPaused()) {
game.resume(false);
} else {
game.pause(false);
}
}
}
}
hideBehaviourMenu(key: string | number, controlsState: ControlsState) {
const {
uiState,
game,
} = this.props;
if (!uiState.video) {
if (this.props.uiState.behaviourMenu && this.isBehaviourKey(key, controlsState)) {
this.props.setUiState({ behaviourMenu: false });
game.resume(false);
}
}
}
listenerKeyDown(event) {
this.showHideMenus(event.code, null);
}
listenerKeyUp(event) {
this.hideBehaviourMenu(event.code, null);
}
gamepadListener(event) {
const controlsState = event.detail as ControlsState;
this.showHideMenus(null, controlsState);
this.hideBehaviourMenu(null, controlsState);
}
startNewGameScene() {
const { game, sceneManager } = this.props;
game.resume();
game.resetState();
sceneManager.goto(0, true);
}
onMenuItemChanged(item) {
const { game } = this.props;
switch (item) {
case 70: { // Resume
this.props.hideMenu();
break;
}
case 71: { // New Game
this.props.hideMenu();
const onEnded = () => {
this.props.setUiState({video: null});
this.startNewGameScene();
game.controlsState.skipListener = null;
};
game.controlsState.skipListener = onEnded;
game.pause();
const videoPath = getVideoPath('INTRO');
if (videoPath !== undefined) {
this.props.setUiState({
video: {
path: videoPath,
onEnded
}
});
} else {
onEnded();
}
break;
}
case -1: { // Teleport
this.props.setUiState({teleportMenu: true});
break;
}
case -2: { // Editor Mode
const audio = game.getAudioManager();
audio.stopMusicTheme();
if ('exitPointerLock' in document) {
document.exitPointerLock();
}
if (window.location.hash) {
window.location.hash = `${window.location.hash}&editor=true`;
} else {
window.location.hash = 'editor=true';
}
break;
}
case -3: { // Exit editor
const audio = game.getAudioManager();
audio.stopMusicTheme();
if ('exitPointerLock' in document) {
document.exitPointerLock();
}
window.location.hash = '';
break;
}
case -4: { // Enable Iso 3d
if (window.location.hash) {
window.location.hash = `${window.location.hash}&iso3d=true`;
} else {
window.location.hash = 'iso3d=true';
}
location.reload();
break;
}
case -5: { // Disable Iso 3d
window.location.hash = window.location.hash.replace('iso3d=true', '');
location.reload();
break;
}
case -6: { // Switch to LBA1
window.location.hash = window.location.hash.replace('&game=lba2', '');
window.location.hash = window.location.hash.replace('#game=lba2', '');
if (window.location.hash) {
window.location.hash = `${window.location.hash}&game=lba1`;
} else {
window.location.hash = 'game=lba1';
}
location.reload();
break;
}
case -7: { // Switch to LBA2
window.location.hash = window.location.hash.replace('&game=lba1', '');
window.location.hash = window.location.hash.replace('#game=lba1', '');
if (window.location.hash) {
window.location.hash = `${window.location.hash}&game=lba2`;
} else {
window.location.hash = 'game=lba2';
}
location.reload();
break;
}
case -8: { // Enable 3d Audio
if (window.location.hash) {
window.location.hash = `${window.location.hash}&audio3d=true`;
} else {
window.location.hash = 'audio3d=true';
}
location.reload();
break;
}
case -9: { // Disable 3d Audio
window.location.hash = window.location.hash.replace('audio3d=true', '');
location.reload();
break;
}
}
}
onAskChoiceChanged(choice) {
this.props.setUiState({choice});
}
textAnimEndedHandler() {
this.props.setUiState({ skip: true });
}
async noAudioClick() {
const { uiState } = this.props;
const audio = this.props.game.getAudioManager();
audio.resumeContext();
this.props.setUiState({ noAudio: false }, () => {
if (uiState.showMenu) {
audio.playMusicTheme();
}
});
}
render() {
const {
game,
renderer,
sceneManager,
uiState
} = this.props;
const {
cinema,
interjections,
video,
behaviourMenu,
inventory,
showMenu,
teleportMenu,
inGameMenu,
loading,
text,
skip,
foundObject,
ask,
noAudio
} = uiState;
const { keyHelp } = this.state;
const scene = sceneManager.getScene();
return <React.Fragment>
<CinemaEffect enabled={cinema} />
<TextInterjections
scene={scene}
renderer={renderer}
interjections={interjections}
/>
<Video video={video} renderer={renderer} />
{behaviourMenu ?
<BehaviourMenu
game={game}
scene={scene}
/>
: null }
{inventory ?
<Inventory
game={game}
scene={scene}
closeInventory={this.closeInventory}
/>
: null }
<Menu
showMenu={showMenu && !teleportMenu}
inGameMenu={inGameMenu}
onItemChanged={this.onMenuItemChanged}
/>
{showMenu && !teleportMenu
&& <KeyHelpIcon open={this.openKeyHelp}/>}
<Ribbon mode={showMenu ? 'menu' : 'game'} />
{teleportMenu
&& <TeleportMenu
inGameMenu={inGameMenu}
game={game}
sceneManager={sceneManager}
exit={(e) => {
e.preventDefault();
e.stopPropagation();
this.props.setUiState({teleportMenu: false});
}}
/>}
<div id="stats" style={{position: 'absolute', top: 0, left: 0, width: '50%'}}/>
{loading ? <Loader/> : null}
{!showMenu ? <TextBox
text={text}
skip={skip}
textAnimEnded={this.textAnimEndedHandler}
/> : null}
{!showMenu ? <AskChoice
ask={ask}
onChoiceChanged={this.onAskChoiceChanged}
/> : null}
{foundObject !== null && !showMenu ? <FoundObject foundObject={foundObject} /> : null}
{this.renderNewObjectPickerOverlay()}
{keyHelp && <KeyHelpScreen close={this.closeKeyHelp}/>}
{noAudio && (
<NoAudio onClick={this.noAudioClick} />
)}
</React.Fragment>;
}
renderNewObjectPickerOverlay() {
const { sharedState } = this.props;
if (sharedState && sharedState.objectToAdd) {
const baseBannerStyle = {
...fullscreen,
height: 30,
lineHeight: '30px',
fontSize: 16,
background: 'rgba(0, 0, 128, 0.5)',
color: 'white'
};
const headerStyle = { ...baseBannerStyle, bottom: 'initial' };
const footerStyle = { ...baseBannerStyle, top: 'initial' };
return <React.Fragment>
<div style={headerStyle}>
Pick a location for the new {sharedState.objectToAdd.type}...
</div>
<div style={footerStyle}/>
</React.Fragment>;
}
}
} | the_stack |
import {Ng2StateDeclaration, StateService} from "@uirouter/angular";
import {catchError} from "rxjs/operators/catchError";
import {first} from "rxjs/operators/first";
import {DefineFeedComponent} from "./define-feed.component";
import {DefineFeedSelectTemplateComponent} from "./select-template/define-feed-select-template.component";
import {DefineFeedService} from "./services/define-feed.service";
import {DefineFeedContainerComponent} from "./steps/define-feed-container/define-feed-container.component";
import {DefineFeedStepFeedDetailsComponent} from "./steps/feed-details/define-feed-step-feed-details.component";
import {DefineFeedTableComponent} from "./steps/define-table/define-feed-table.component";
import {FEED_DEFINITION_SECTION_STATE_NAME, FEED_DEFINITION_STATE_NAME, FEED_DEFINITION_SUMMARY_STATE_NAME, FEED_OVERVIEW_STATE_NAME} from "../../model/feed/feed-constants";
import {DefineFeedStepWranglerComponent} from "./steps/wrangler/define-feed-step-wrangler.component";
import {ProfileComponent} from './summary/profile/profile.component';
import {OverviewComponent} from './summary/overview/overview.component';
import {FeedLineageComponment} from "./summary/feed-lineage/feed-lineage.componment";
import {ProfileContainerComponent} from './summary/profile/container/profile-container.component';
import {ProfileHistoryComponent} from './summary/profile/history/profile-history.component';
import {DefineFeedPermissionsComponent} from "./steps/permissions/define-feed-permissions.component";
import {DefineFeedPropertiesComponent} from "./steps/properties/define-feed-properties.component";
import {FeedSlaComponent} from './summary/sla/feed-sla.component';
import {DefineFeedStepSourceComponent} from "./steps/source/define-feed-step-source.component";
import {FeedActivitySummaryComponent} from "./summary/feed-activity-summary/feed-activity-summary.component";
import {SetupGuideSummaryComponent} from "./summary/setup-guide-summary/setup-guide-summary.component";
import {FeedSummaryContainerComponent} from "./summary/feed-summary-container.component";
import {LoadMode} from "../../model/feed/feed.model";
import {ImportFeedComponent} from "../define-feed-ng2/import/import-feed.component";
import {FeedVersionsComponent} from "./summary/versions/feed-versions.component";
import {SlaListComponent} from "../../sla/list/sla-list.componment";
import {SlaDetailsComponent} from "../../sla/details/sla-details.componment";
import {Observable} from "rxjs/Observable";
import AccessConstants from "../../../constants/AccessConstants";
import {AccessDeniedComponent} from "../../../common/access-denied/access-denied.component";
const resolveFeed = {
token: 'feed',
deps: [StateService, DefineFeedService],
resolveFn: loadFeed
};
export const defineFeedStates: Ng2StateDeclaration[] = [
{
name: FEED_DEFINITION_STATE_NAME,
url: "/"+FEED_DEFINITION_STATE_NAME,
redirectTo: FEED_DEFINITION_STATE_NAME+".select-template",
views: {
"content": {
component: DefineFeedComponent
}
},
data: {
breadcrumbRoot: true,
displayName: ""
}
},
{
name: FEED_DEFINITION_STATE_NAME+".import-feed",
url: "/import-feed",
component:ImportFeedComponent,
data: {
breadcrumbRoot: true,
displayName: "",
permissionsKey:"IMPORT_FEED"
}
},
{
name: FEED_DEFINITION_STATE_NAME+".select-template",
url: "/select-template",
component: DefineFeedSelectTemplateComponent
},
{
name: FEED_DEFINITION_SECTION_STATE_NAME,
url: "/section",
redirectTo: FEED_DEFINITION_SECTION_STATE_NAME+".setup-guide",
component: DefineFeedContainerComponent,
resolve: [
{
token: 'stateParams',
deps: [StateService],
resolveFn: resolveParams
}
]
},
{
name: FEED_DEFINITION_SECTION_STATE_NAME+".setup-guide",
url: "/:feedId/setup-guide",
component: SetupGuideSummaryComponent,
params:{feedId:{type:"string"},
loadMode:LoadMode.LATEST, squash: true},
resolve: [
{
token: 'stateParams',
deps: [StateService],
resolveFn: resolveParams
}
],
data: {
permissionsKey:"FEED_DETAILS"
}
},
{
name: FEED_DEFINITION_SECTION_STATE_NAME+".deployed-setup-guide",
url: "/:feedId/deployed-setup-guide",
component: SetupGuideSummaryComponent,
params:{feedId:{type:"string"},
loadMode:LoadMode.DEPLOYED,
refresh:false},
resolve: [
{
token: 'stateParams',
deps: [StateService],
resolveFn: resolveParams
},
{
token: 'loadMode',
resolveFn: resolveLoadModeDeployed
},
{
token: 'refresh',
resolveFn: resolveFalse
}
],
data: {
permissionsKey:"FEED_DETAILS"
}
},
{
name: FEED_DEFINITION_SECTION_STATE_NAME+".access-denied",
url: "/:feedId/access-denied",
params:{feedId:null, attemptedState:null},
resolve: [
{
token: 'stateParams',
deps: [StateService],
resolveFn: resolveParams
}],
component: AccessDeniedComponent
},
{
name: FEED_DEFINITION_SECTION_STATE_NAME+".feed-permissions",
url: "/:feedId/feed-permissions",
component: DefineFeedPermissionsComponent
},
{
name: FEED_DEFINITION_SECTION_STATE_NAME+".feed-properties",
url: "/:feedId/feed-properties",
component: DefineFeedPropertiesComponent
},
{
name: FEED_DEFINITION_SECTION_STATE_NAME+".feed-details",
url: "/:feedId/feed-details",
component: DefineFeedStepFeedDetailsComponent
},
{
name: FEED_DEFINITION_SECTION_STATE_NAME+".feed-table",
url: "/:feedId/feed-table",
component: DefineFeedTableComponent
},
{
name: FEED_DEFINITION_SECTION_STATE_NAME+".wrangler",
url: "/:feedId/wrangler",
component: DefineFeedStepWranglerComponent,
data:{
permissionsKey:"FEED_STEP_WRANGLER",
accessRedirect:"feed-definition.section.access-denied",
}
},
{
name: FEED_DEFINITION_SECTION_STATE_NAME + ".datasources",
url: "/:feedId/source-sample",
component: DefineFeedStepSourceComponent,
},
{
name: FEED_DEFINITION_SUMMARY_STATE_NAME,
url: "/:feedId/summary",
component: FeedSummaryContainerComponent,
params: {feedId:{type:"string"},
refresh:false},
resolve: [
{
token: 'stateParams',
deps: [StateService],
resolveFn: resolveParams
}
]
},
/*
{
name: FEED_DEFINITION_SUMMARY_STATE_NAME,
url: "/:feedId/summary",
redirectTo: (trans:Transition) => {
// const uiInjector = trans.injector();
// const $injector = uiInjector.get('$injector'); // native injector
return trans.injector().getAsync('redirectState');
},
component: FeedSummaryContainerComponent,
resolve: [
{
token: 'stateParams',
deps: [StateService],
resolveFn: (state: StateService) => state.transition.params()
},
{
token: "redirectState",
deps: [DefineFeedService, StateService],
resolveFn: (defineFeedService:DefineFeedService, state:StateService) => {
let feedId = state.transition.params().feedId;
return defineFeedService.loadFeed(feedId).toPromise().then((feed:Feed) => {
console.log("Loaded it ... lets go ",feed)
if(true) {//(feed.hasBeenDeployed()){
return FEED_OVERVIEW_STATE_NAME;
}
else {
return FEED_DEFINITION_SECTION_STATE_NAME+".setup-guide";
}
});
}
}
]
},
*/
{
name: FEED_OVERVIEW_STATE_NAME,
url: "/:feedId/overview",
component: OverviewComponent
},
{
name: FEED_DEFINITION_SUMMARY_STATE_NAME+".access-denied",
url: "/access-denied",
params:{attemptedState:null},
resolve: [
{
token: 'stateParams',
deps: [StateService],
resolveFn: resolveParams
}],
component: AccessDeniedComponent
},
{
name: FEED_DEFINITION_SUMMARY_STATE_NAME+".setup-guide",
url: "/:feedId/summary-setup-guide",
component: SetupGuideSummaryComponent,
params:{feedId:{type:"string"},
loadMode:LoadMode.LATEST,
refresh:false},
resolve: [
{
token: 'showHeader',
resolveFn: resolveTrue
},
{
token: 'stateParams',
deps: [StateService],
resolveFn: resolveParams
},
{
token: 'loadMode',
resolveFn: resolveLoadModeLatest
},
{
token: 'refresh',
resolveFn: resolveFalse
}
]
},
{
name: FEED_DEFINITION_SUMMARY_STATE_NAME+".feed-activity",
url: "/:feedId/feed-activity",
component: FeedActivitySummaryComponent,
params:{feedId:{type:"string"},
loadMode:LoadMode.DEPLOYED,
refresh:false},
resolve: [
{
token: 'stateParams',
deps: [StateService],
resolveFn: resolveParams
},
{
token: 'loadMode',
resolveFn: resolveLoadModeDeployed
},
{
token: 'refresh',
resolveFn: resolveFalse
}
]
},
/**
{
name: FEED_DEFINITION_SECTION_STATE_NAME+".datasources",
url: "/:feedId/source-sample",
component: DefineFeedStepSourceSampleComponent,
resolve: [
{
token: "datasources",
deps: [CatalogService, TdLoadingService],
resolveFn: (catalog: CatalogService,loading: TdLoadingService) => {
loading.register(DefineFeedStepSourceSampleComponent.LOADER);
return catalog.getDataSources()
.pipe(finalize(() => loading.resolve(DefineFeedStepSourceSampleComponent.LOADER)))
.pipe(catchError((err) => {
console.error('Failed to load catalog', err);
return [];
}))
.toPromise();
}
},
{
token: 'stateParams',
deps: [StateService],
resolveFn: (state: StateService) => state.transition.params()
}
]
},
{
name:FEED_DEFINITION_SECTION_STATE_NAME+".datasource",
url:"/:feedId/source-sample/:datasourceId/:path",
component: DefineFeedStepSourceSampleDatasourceComponent,
params: {
path:{value:''}
},
resolve: [
{
token: "datasource",
deps: [CatalogService, StateService, TdLoadingService, DefineFeedService],
resolveFn: (catalog: CatalogService, state: StateService, loading: TdLoadingService, defineFeedService:DefineFeedService) => {
loading.register(DefineFeedStepSourceSampleDatasourceComponent.LOADER);
let datasourceId = state.transition.params().datasourceId;
let feed = defineFeedService.getFeed();
if(feed && feed.sourceDataSets && feed.sourceDataSets.length >0 && feed.sourceDataSets[0].dataSource.id == datasourceId){
return feed.sourceDataSets[0].dataSource;
}
else {
return catalog.getDataSource(datasourceId)
.pipe(finalize(() => loading.resolve(DefineFeedStepSourceSampleDatasourceComponent.LOADER)))
.pipe(catchError(() => {
return state.go(".datasources")
}))
.toPromise();
}
}
},
{
token: "connectorPlugin",
deps: [CatalogService, StateService, TdLoadingService],
resolveFn: (catalog: CatalogService, state: StateService, loading: TdLoadingService) => {
let datasourceId = state.transition.params().datasourceId;
return catalog.getDataSourceConnectorPlugin(datasourceId)
.pipe(catchError(() => {
return state.go("catalog")
}))
.toPromise();
}
},
{
token:"params",
deps:[StateService],
resolveFn: (state: StateService) => {
let params = state.transition.params();
if(params && params.path) {
return {"path":params.path}
}
else {
return {};
}
}
}
]
},*/
{
name: FEED_DEFINITION_SUMMARY_STATE_NAME+".profile",
url: "/:feedId/profile",
redirectTo: FEED_DEFINITION_SUMMARY_STATE_NAME+".profile.history",
component: ProfileComponent,
resolve: [
{
token: 'stateParams',
deps: [StateService],
resolveFn: resolveParams
}
]
},
{
name: FEED_DEFINITION_SUMMARY_STATE_NAME+".profile.history",
url: "/history",
component: ProfileHistoryComponent,
resolve: [
{
token: 'stateParams',
deps: [StateService],
resolveFn: resolveParams
},
]
},
{
name: FEED_DEFINITION_SUMMARY_STATE_NAME+".profile.results",
url: "/:processingdttm?t=:type",
component: ProfileContainerComponent,
resolve: [
{
token: 'stateParams',
deps: [StateService],
resolveFn: resolveParams
},
]
},
{
name: FEED_DEFINITION_SUMMARY_STATE_NAME+".feed-lineage",
url: "/:feedId/feed-lineage",
component: FeedLineageComponment,
resolve: [
{
token: 'stateParams',
deps: [StateService],
resolveFn: resolveParams
}
]
},
{
name: FEED_DEFINITION_SUMMARY_STATE_NAME+".sla",
url: "/:feedId/sla",
redirectTo: FEED_DEFINITION_SUMMARY_STATE_NAME+".sla.list",
component: FeedSlaComponent,
resolve: [
{
token: 'stateParams',
deps: [StateService],
resolveFn: resolveParams
},
resolveFeed
],
data:{
permissionsKey:"SERVICE_LEVEL_AGREEMENTS",
accessRedirect:"feed-definition.summary.access-denied",
}
},
{
name: FEED_DEFINITION_SUMMARY_STATE_NAME+".sla.list",
url: "/list",
component: SlaListComponent,
resolve: [
{
token: 'stateParams',
deps: [StateService],
resolveFn: resolveParams
},
resolveFeed
]
},
{
name: FEED_DEFINITION_SUMMARY_STATE_NAME+".sla.new",
url: "/new",
component: SlaDetailsComponent,
resolve: [
{
token: 'stateParams',
deps: [StateService],
resolveFn: resolveParams
},
resolveFeed
]
},
{
name: FEED_DEFINITION_SUMMARY_STATE_NAME+".sla.edit",
url: "/:slaId",
component: SlaDetailsComponent,
resolve: [
{
token: 'stateParams',
deps: [StateService],
resolveFn: resolveParams
},
resolveFeed
]
},
{
name: FEED_DEFINITION_SUMMARY_STATE_NAME+".version-history",
url: "/:feedId/versions",
component: FeedVersionsComponent,
resolve: [
{
token: 'stateParams',
deps: [StateService],
resolveFn: resolveParams
}
]
}
];
export function loadFeed(state: StateService, feedService:DefineFeedService) {
let feedId = state.transition.params().feedId;
return feedService.loadFeed(feedId)
.pipe(catchError((err: any, o: Observable<any>) => {
console.error('Failed to load feed', err);
return Observable.of({});
}))
.pipe(first()).toPromise();
}
export function resolveParams(state: StateService) {
return state.transition.params();
}
export function resolveFalse() {
return false;
}
export function resolveTrue() {
return true;
}
export function resolveLoadModeDeployed() {
return LoadMode.DEPLOYED;
}
export function resolveLoadModeLatest() {
return LoadMode.LATEST;
} | the_stack |
import { EmitType } from '@syncfusion/ej2-base';
import { createElement, remove } from '@syncfusion/ej2-base';
import { Grid } from '../../../src/grid/base/grid';
import { Sort } from '../../../src/grid/actions/sort';
import { Group } from '../../../src/grid/actions/group';
import { Selection } from '../../../src/grid/actions/selection';
import { Filter } from '../../../src/grid/actions/filter';
import { Page } from '../../../src/grid/actions/page';
import {RowDD } from "../../../src/grid/actions/row-reorder";
import { DetailRow } from '../../../src/grid/actions/detail-row';
import { filterData, employeeData, customerData } from '../base/datasource.spec';
import '../../../node_modules/es6-promise/dist/es6-promise';
import { Edit } from '../../../src/grid/actions/edit';
import { createGrid, destroy } from '../base/specutil.spec';
import {profile , inMB, getMemoryProfile} from '../base/common.spec';
Grid.Inject(Sort, Page, Filter, DetailRow, Group, Selection, Edit,RowDD);
describe('Detail template module', () => {
function detail(e: any): void {
let data: any = [];
for (let i = 0; i < filterData.length; i++) {
if (filterData[i]['EmployeeID'] === e.data.EmployeeID) {
data.push(filterData[i]);
}
}
let grid1: Grid = new Grid(
{
dataSource: filterData,
selectionSettings: { type: 'Multiple', mode: 'Row' },
allowSorting: true,
allowPaging: true,
pageSettings: { pageSize: 3 },
allowGrouping: true,
allowReordering: true,
allowTextWrap: true,
allowFiltering: true,
columns: [
{ field: 'OrderID', headerText: 'Order ID', width: 120, textAlign: 'Right' },
{ field: 'CustomerID', headerText: 'Customer ID', width: 125 },
{ field: 'Freight', width: 120, format: 'C', textAlign: 'Right' },
{ field: 'ShipCity', headerText: 'Ship City', width: 150 }
],
});
grid1.appendTo((e.detailElement as Element).querySelector('#detailgrid') as HTMLElement);
}
describe('Render with invalid id testing', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
}
gridObj = createGrid(
{
dataSource: filterData,
allowPaging: true,
detailTemplate: '#detailtemplate1',
detailDataBound: detail,
allowGrouping: true,
selectionSettings: { type: 'Multiple', mode: 'Row' },
allowFiltering: true,
allowSorting: true,
allowReordering: true,
columns: [
{ field: 'OrderID', headerText: 'Order ID', width: 120, textAlign: 'Right' },
{ field: 'CustomerID', headerText: 'Customer ID', width: 125 },
{ field: 'Freight', width: 120, format: 'C', textAlign: 'Right' },
{ field: 'ShipCity', headerText: 'Ship City', width: 150 }
]
}, done);
});
it('Detail row render testing', () => {
expect(gridObj.getContentTable().querySelectorAll('.e-detailrowcollapse').length).toBe(12);
expect(gridObj.getHeaderTable().querySelectorAll('.e-detailheadercell').length).toBe(1);
expect(gridObj.getHeaderTable().querySelectorAll('.e-mastercell').length).toBe(1);
expect(gridObj.getHeaderTable().querySelectorAll('.e-mastercell')[0].classList.contains('e-filterbarcell')).toBeTruthy();
});
it('Detail row expand testing', () => {
(gridObj.getDataRows()[0].querySelector('.e-detailrowcollapse') as HTMLElement).click();
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(0);
expect(gridObj.getDataRows()[0].querySelectorAll('.e-detailrowexpand').length).toBe(1);
});
it('Detail collapse testing', () => {
(gridObj.getDataRows()[0].querySelector('.e-detailrowexpand') as HTMLElement).click();
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(0);
expect(gridObj.getDataRows()[0].querySelectorAll('.e-detailrowcollapse').length).toBe(1);
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('Render testing', () => {
let gridObj: Grid;
let template: HTMLElement = createElement('script', { id: 'detailtemplate' });
template.appendChild(createElement('div', { id: 'detailgrid' }));
document.body.appendChild(template);
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData.map(data => data),
allowPaging: true,
detailTemplate: '#detailtemplate',
detailDataBound: detail,
allowGrouping: true,
editSettings: { allowAdding: true, allowDeleting: true, allowEditing: true },
toolbar: ['Add', 'Edit', 'Delete', 'Update', 'Cancel'],
selectionSettings: { type: 'Multiple', mode: 'Row' },
allowFiltering: true,
allowSorting: true,
allowReordering: true,
actionComplete: actionComplete,
columns: [
{ field: 'OrderID', headerText: 'Order ID', width: 120, textAlign: 'Right' },
{ field: 'CustomerID', headerText: 'Customer ID', width: 125 },
{ field: 'Freight', width: 120, format: 'C', textAlign: 'Right' },
{ field: 'ShipCity', headerText: 'Ship City', width: 150 }
],
}, done);
});
it('Detail row render testing', () => {
expect(gridObj.getContentTable().querySelectorAll('.e-detailrowcollapse').length).toBe(12);
expect(gridObj.getHeaderTable().querySelectorAll('.e-detailheadercell').length).toBe(1);
expect(gridObj.getHeaderTable().querySelectorAll('.e-mastercell').length).toBe(1);
expect(gridObj.getHeaderTable().querySelectorAll('.e-mastercell')[0].classList.contains('e-filterbarcell')).toBeTruthy();
});
it('Detail row expand testing', () => {
expect(gridObj.getDataRows()[0].querySelectorAll('.e-detailrowcollapse')[0].getAttribute('aria-expanded')).toBe("false");
(gridObj.getDataRows()[0].querySelector('.e-detailrowcollapse') as HTMLElement).click();
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(1);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[0] as HTMLElement).style.display).toBe('');
expect(gridObj.getDataRows()[0].querySelectorAll('.e-detailrowexpand').length).toBe(1);
expect(gridObj.getDataRows()[0].querySelectorAll('.e-detailrowcollapse').length).toBe(0);
expect(gridObj.getDataRows()[0].querySelectorAll('.e-detailrowexpand')[0].getAttribute('aria-expanded')).toBe("true");
});
it('Detail collapse testing', () => {
(gridObj.getDataRows()[0].querySelector('.e-detailrowexpand') as HTMLElement).click();
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(1);
expect(gridObj.getDataRows()[0].querySelectorAll('.e-detailrowcollapse').length).toBe(1);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[0] as HTMLElement).style.display).toBe('none');
expect(gridObj.getDataRows()[0].querySelectorAll('.e-detailrowexpand').length).toBe(0);
expect(gridObj.getDataRows()[0].querySelectorAll('.e-detailrowcollapse')[0].getAttribute('aria-expanded')).toBe("false");
});
it('Expand method testing', () => {
gridObj.detailRowModule.expand(gridObj.getDataRows()[1].querySelector('.e-detailrowcollapse'));
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(2);
expect(gridObj.getDataRows()[1].querySelectorAll('.e-detailrowexpand').length).toBe(1);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[1] as HTMLElement).style.display).toBe('');
gridObj.detailRowModule.expand(gridObj.getDataRows()[1].querySelector('.e-detailrowexpand'));
expect(gridObj.getDataRows()[1].querySelectorAll('.e-detailrowexpand').length).toBe(1);
});
it('EJ2-7253- expand and collapse button is not working well after edit', () => {
gridObj.detailRowModule.expand(gridObj.getDataRows()[1].querySelector('.e-detailrowcollapse'));
expect(gridObj.getDataRows()[1].querySelectorAll('.e-detailrowexpand').length).toBe(1);
gridObj.selectRow(1);
gridObj.startEdit();
gridObj.endEdit();
expect(gridObj.getDataRows()[1].querySelectorAll('.e-detailrowexpand').length).toBeGreaterThan(0);
});
it('Collapse method testing', () => {
gridObj.detailRowModule.collapse(gridObj.getDataRows()[1].querySelector('.e-detailrowexpand'));
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(2);
expect(gridObj.getDataRows()[1].querySelectorAll('.e-detailrowcollapse').length).toBe(1);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[1] as HTMLElement).style.display).toBe('none');
gridObj.detailRowModule.collapse(gridObj.getDataRows()[1].querySelector('.e-detailrowcollapse'));
expect(gridObj.getDataRows()[1].querySelectorAll('.e-detailrowcollapse').length).toBe(1);
});
it('Alt Down shortcut testing', (done: Function) => {
gridObj.element.focus();
let args: any = { action: 'altDownArrow', preventDefault: () => { }, target: createElement('div') };
let leftArgs: any = { action: 'rightArrow', preventDefault: () => { }, target: createElement('div') };
gridObj.rowSelected = () => {
gridObj.keyboardModule.keyAction(leftArgs);
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(3);
expect(gridObj.getDataRows()[2].querySelectorAll('.e-detailrowexpand').length).toBe(1);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[2] as HTMLElement).style.display).toBe('');
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getDataRows()[2].querySelectorAll('.e-detailrowexpand').length).toBe(1);
gridObj.rowSelected = null;
done();
};
gridObj.selectRow(2, true);
});
it('Alt Up shortcut testing', () => {
let args: any = { action: 'altUpArrow', preventDefault: () => { }, target: createElement('div') };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(3);
expect(gridObj.getDataRows()[2].querySelectorAll('.e-detailrowcollapse').length).toBe(1);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[2] as HTMLElement).style.display).toBe('none');
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getDataRows()[2].querySelectorAll('.e-detailrowcollapse').length).toBe(1);
});
it('ctrlDownArrow shortcut testing', () => {
let args: any = { action: 'ctrlDownArrow', preventDefault: () => { }, target: createElement('div') };
gridObj.selectRow(3, true);
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(12);
expect(gridObj.getDataRows()[3].querySelectorAll('.e-detailrowexpand').length).toBe(1);
expect(gridObj.getDataRows()[4].querySelectorAll('.e-detailrowexpand').length).toBe(1);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[3] as HTMLElement).style.display).toBe('');
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[4] as HTMLElement).style.display).toBe('');
});
it('ctrlUpArrow shortcut testing', () => {
let args: any = { action: 'ctrlUpArrow', preventDefault: () => { }, target: createElement('div') };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(12);
expect(gridObj.getDataRows()[3].querySelectorAll('.e-detailrowcollapse').length).toBe(1);
expect(gridObj.getDataRows()[4].querySelectorAll('.e-detailrowcollapse').length).toBe(1);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[3] as HTMLElement).style.display).toBe('none');
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[4] as HTMLElement).style.display).toBe('none');
});
it('Alt Down shortcut with selection disabled testing', () => {
gridObj.allowSelection = false;
gridObj.dataBind();
let leftArgs: any = { action: 'rightArrow', preventDefault: () => { }, target: createElement('div') };
gridObj.keyboardModule.keyAction(leftArgs);
let args: any = { action: 'altDownArrow', preventDefault: () => { }, target: createElement('div') };
gridObj.keyboardModule.keyAction(args);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[2] as HTMLElement).style.display).toBe('none');
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getDataRows()[2].querySelectorAll('.e-detailrowexpand').length).toBe(0);
});
it('Single column group testing', (done: Function) => {
actionComplete = (args?: any): void => {
if (args.requestType === 'grouping') {
let grpHIndent = gridObj.getHeaderContent().querySelectorAll('.e-grouptopleftcell');
let content = gridObj.getContent().querySelectorAll('tr');
expect(grpHIndent[0].querySelector('.e-headercelldiv').classList.contains('e-emptycell')).toBeTruthy();
expect(gridObj.getHeaderTable().querySelectorAll('.e-detailheadercell').length).toBe(1);
expect(content[1].querySelectorAll('.e-indentcell').length).toBe(1);
done();
}
};
gridObj.actionComplete = actionComplete;
gridObj.groupModule.groupColumn('OrderID');
});
it('Alt Down shortcut with grouping testing', (done: Function) => {
gridObj.element.focus();
gridObj.allowSelection = true;
gridObj.dataBind();
gridObj.rowSelected = () => {
let args: any = { action: 'altDownArrow', preventDefault: () => { }, target: createElement('div') };
let leftArgs: any = { action: 'rightArrow', preventDefault: () => { }, target: createElement('div') };
gridObj.keyboardModule.keyAction(leftArgs);
gridObj.keyboardModule.keyAction(args);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[0] as HTMLElement).style.display).toBe('');
done();
};
gridObj.selectRow(1, true);
});
it('Expand method with grouping testing', () => {
gridObj.detailRowModule.expand(gridObj.getDataRows()[0].querySelector('.e-detailrowcollapse'));
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(2);
expect(gridObj.getDataRows()[0].querySelectorAll('.e-detailrowexpand').length).toBe(1);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[0] as HTMLElement).style.display).toBe('');
});
it('expandcollapse group rows method testing', () => {
gridObj.groupModule.expandCollapseRows(gridObj.getContent().querySelectorAll('.e-recordplusexpand')[4]);
// expect(gridObj.getContent().querySelectorAll('tr:not([style*="display: none"])').length).toBe(33);
});
it('toogleExpandcollapse with invalid element testing', () => {
(gridObj.detailRowModule as any).toogleExpandcollapse(gridObj.getDataRows()[1].querySelector('.e-rowcell'));
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(2);
expect(gridObj.getDataRows()[1].querySelectorAll('.e-detailrowexpand').length).toBe(1);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[1] as HTMLElement).style.display).toBe('');
});
afterAll(() => {
remove(document.getElementById('detailtemplate'));
destroy(gridObj);
gridObj = template = actionComplete = null;
});
});
describe('Hierarchy Render testing', () => {
let gridObj: Grid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: employeeData,
allowPaging: true,
allowGrouping: true,
selectionSettings: { type: 'Multiple', mode: 'Row' },
allowFiltering: true,
allowSorting: true,
allowReordering: true,
actionComplete: actionComplete,
columns: [
{ field: 'EmployeeID', headerText: 'Employee ID', textAlign: 'Right', width: 75 },
{ field: 'FirstName', headerText: 'First Name', textAlign: 'Left', width: 100 },
{ field: 'Title', headerText: 'Title', textAlign: 'Left', width: 120 },
{ field: 'City', headerText: 'City', textAlign: 'Left', width: 100 },
{ field: 'Country', headerText: 'Country', textAlign: 'Left', width: 100 }
],
childGrid: {
dataSource: filterData, queryString: 'EmployeeID',
allowPaging: true,
allowGrouping: true,
selectionSettings: { type: 'Multiple', mode: 'Row' },
pageSettings: { pageCount: 5, pageSize: 5 },
allowFiltering: true,
allowSorting: true,
groupSettings: { showGroupedColumn: false },
allowReordering: true,
allowTextWrap: true,
columns: [
{ field: 'OrderID', headerText: 'Order ID', textAlign: 'Right', width: 75 },
{ field: 'EmployeeID', headerText: 'Employee ID', textAlign: 'Right', width: 75 },
{ field: 'ShipCity', headerText: 'Ship City', textAlign: 'Left', width: 100 },
{ field: 'Freight', headerText: 'Freight', textAlign: 'Left', width: 120 },
{ field: 'ShipName', headerText: 'Ship Name', textAlign: 'Left', width: 100 }
],
childGrid: {
dataSource: customerData,
allowPaging: true,
allowGrouping: true,
selectionSettings: { type: 'Multiple', mode: 'Row' },
pageSettings: { pageCount: 5, pageSize: 5 },
allowFiltering: true,
allowSorting: true,
groupSettings: { showGroupedColumn: false },
allowReordering: true,
allowTextWrap: true,
queryString: 'CustomerID',
columns: [
{ field: 'CustomerID', headerText: 'Customer ID', textAlign: 'Right', width: 75 },
{ field: 'Phone', headerText: 'Phone', textAlign: 'Left', width: 100 },
{ field: 'Address', headerText: 'Address', textAlign: 'Left', width: 120 },
{ field: 'Country', headerText: 'Country', textAlign: 'Left', width: 100 }
],
},
},
}, done);
});
it('Hierarchy row render testing', () => {
expect(gridObj.getContentTable().querySelectorAll('.e-detailrowcollapse').length).toBe(9);
expect(gridObj.getHeaderTable().querySelectorAll('.e-detailheadercell').length).toBe(1);
expect(gridObj.getHeaderTable().querySelectorAll('.e-mastercell').length).toBe(1);
expect(gridObj.getHeaderTable().querySelectorAll('.e-mastercell')[0].classList.contains('e-filterbarcell')).toBeTruthy();
});
it('Hierarchy row expand testing', () => {
expect(gridObj.getDataRows()[0].querySelectorAll('.e-detailrowcollapse')[0].getAttribute('aria-expanded')).toBe('false');
(gridObj.getDataRows()[0].querySelector('.e-detailrowcollapse') as HTMLElement).click();
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(1);
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow')[0].querySelectorAll('.e-grid').length).toBe(1);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[0] as HTMLElement).style.display).toBe('');
expect(gridObj.getDataRows()[0].querySelectorAll('.e-detailrowexpand').length).toBe(1);
expect(gridObj.getDataRows()[0].querySelectorAll('.e-detailrowcollapse').length).toBe(0);
expect(gridObj.getDataRows()[0].querySelectorAll('.e-detailrowexpand')[0].getAttribute('aria-expanded')).toBe('true');
});
it('Hierarchy collapse testing', () => {
(gridObj.getDataRows()[0].querySelector('.e-detailrowexpand') as HTMLElement).click();
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(1);
expect(gridObj.getDataRows()[0].querySelectorAll('.e-detailrowcollapse').length).toBe(1);
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow')[0].querySelectorAll('.e-grid').length).toBe(1);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[0] as HTMLElement).style.display).toBe('none');
expect(gridObj.getDataRows()[0].querySelectorAll('.e-detailrowexpand').length).toBe(0);
expect(gridObj.getDataRows()[0].querySelectorAll('.e-detailrowcollapse')[0].getAttribute('aria-expanded')).toBe('false');
});
it('Expand method testing', () => {
gridObj.detailRowModule.expand(gridObj.getDataRows()[1].querySelector('.e-detailrowcollapse'));
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(2);
expect(gridObj.getDataRows()[1].querySelectorAll('.e-detailrowexpand').length).toBe(1);
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow')[1].querySelectorAll('.e-grid').length).toBe(1);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[1] as HTMLElement).style.display).toBe('');
gridObj.detailRowModule.expand(gridObj.getDataRows()[1].querySelector('.e-detailrowexpand'));
expect(gridObj.getDataRows()[1].querySelectorAll('.e-detailrowexpand').length).toBe(1);
});
it('Collapse method testing', () => {
gridObj.detailRowModule.collapse(gridObj.getDataRows()[1].querySelector('.e-detailrowexpand'));
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(2);
expect(gridObj.getDataRows()[1].querySelectorAll('.e-detailrowcollapse').length).toBe(1);
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow')[1].querySelectorAll('.e-grid').length).toBe(1);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[1] as HTMLElement).style.display).toBe('none');
gridObj.detailRowModule.collapse(gridObj.getDataRows()[1].querySelector('.e-detailrowcollapse'));
expect(gridObj.getDataRows()[1].querySelectorAll('.e-detailrowcollapse').length).toBe(1);
});
it('Expand method with number args testing', () => {
gridObj.detailRowModule.expand(1);
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(2);
expect(gridObj.getDataRows()[1].querySelectorAll('.e-detailrowexpand').length).toBe(1);
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow')[1].querySelectorAll('.e-grid').length).toBe(1);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[1] as HTMLElement).style.display).toBe('');
gridObj.detailRowModule.expand(gridObj.getDataRows()[1].querySelector('.e-detailrowexpand'));
expect(gridObj.getDataRows()[1].querySelectorAll('.e-detailrowexpand').length).toBe(1);
});
it('Collapse method with number args testing', () => {
gridObj.detailRowModule.collapse(1);
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(2);
expect(gridObj.getDataRows()[1].querySelectorAll('.e-detailrowcollapse').length).toBe(1);
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow')[1].querySelectorAll('.e-grid').length).toBe(1);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[1] as HTMLElement).style.display).toBe('none');
gridObj.detailRowModule.collapse(gridObj.getDataRows()[1].querySelector('.e-detailrowcollapse'));
expect(gridObj.getDataRows()[1].querySelectorAll('.e-detailrowcollapse').length).toBe(1);
});
it('Alt Down shortcut testing', () => {
let args: any = { action: 'altDownArrow', preventDefault: () => { }, target: createElement('div') };
gridObj.selectRow(2, true);
let leftArgs: any = { action: 'rightArrow', preventDefault: () => { }, target: createElement('div') };
gridObj.keyboardModule.keyAction(leftArgs);
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(3);
expect(gridObj.getDataRows()[2].querySelectorAll('.e-detailrowexpand').length).toBe(1);
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow')[2].querySelectorAll('.e-grid').length).toBe(1);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[2] as HTMLElement).style.display).toBe('');
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getDataRows()[2].querySelectorAll('.e-detailrowexpand').length).toBe(1);
});
it('Alt Up shortcut testing', () => {
let args: any = { action: 'altUpArrow', preventDefault: () => { }, target: createElement('div') };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(3);
expect(gridObj.getDataRows()[2].querySelectorAll('.e-detailrowcollapse').length).toBe(1);
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow')[2].querySelectorAll('.e-grid').length).toBe(1);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[2] as HTMLElement).style.display).toBe('none');
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getDataRows()[2].querySelectorAll('.e-detailrowcollapse').length).toBe(1);
});
it('ctrlDownArrow shortcut testing', () => {
let args: any = { action: 'ctrlDownArrow', preventDefault: () => { }, target: createElement('div') };
gridObj.selectRow(3, true);
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(9);
expect(gridObj.getDataRows()[3].querySelectorAll('.e-detailrowexpand').length).toBe(1);
expect(gridObj.getDataRows()[4].querySelectorAll('.e-detailrowexpand').length).toBe(1);
expect(gridObj.getContentTable().querySelectorAll('.e-grid').length).toBe(9);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[3] as HTMLElement).style.display).toBe('');
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[4] as HTMLElement).style.display).toBe('');
});
it('ctrlUpArrow shortcut testing', () => {
let args: any = { action: 'ctrlUpArrow', preventDefault: () => { }, target: createElement('div') };
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(9);
expect(gridObj.getDataRows()[3].querySelectorAll('.e-detailrowcollapse').length).toBe(1);
expect(gridObj.getDataRows()[4].querySelectorAll('.e-detailrowcollapse').length).toBe(1);
expect(gridObj.getContentTable().querySelectorAll('.e-grid').length).toBe(9);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[3] as HTMLElement).style.display).toBe('none');
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[4] as HTMLElement).style.display).toBe('none');
});
it('Alt Down shortcut with selection disabled testing', () => {
gridObj.allowSelection = false;
gridObj.dataBind();
let leftArgs: any = { action: 'rightArrow', preventDefault: () => { }, target: createElement('div') };
gridObj.keyboardModule.keyAction(leftArgs);
let args: any = { action: 'altDownArrow', preventDefault: () => { }, target: createElement('div') };
gridObj.keyboardModule.keyAction(args);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[2] as HTMLElement).style.display).toBe('none');
gridObj.keyboardModule.keyAction(args);
expect(gridObj.getDataRows()[2].querySelectorAll('.e-detailrowexpand').length).toBe(0);
});
it('Single column group testing', (done: Function) => {
actionComplete = (args?: any): void => {
if (args.requestType === 'grouping') {
let grpHIndent = gridObj.getHeaderContent().querySelectorAll('.e-grouptopleftcell');
let content = gridObj.getContent().querySelectorAll('tr');
expect(grpHIndent[0].querySelector('.e-headercelldiv').classList.contains('e-emptycell')).toBeTruthy();
expect(gridObj.getHeaderTable().querySelectorAll('.e-detailheadercell').length).toBe(1);
expect(content[1].querySelectorAll('.e-indentcell').length).toBe(1);
done();
}
};
gridObj.actionComplete = actionComplete;
gridObj.groupModule.groupColumn('EmployeeID');
});
it('Alt Down shortcut with grouping testing', () => {
gridObj.allowSelection = true;
gridObj.dataBind();
gridObj.selectRow(1, true);
let leftArgs: any = { action: 'rightArrow', preventDefault: () => { }, target: createElement('div') };
gridObj.keyboardModule.keyAction(leftArgs);
let args: any = { action: 'altDownArrow', preventDefault: () => { }, target: createElement('div') };
gridObj.keyboardModule.keyAction(args);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[0] as HTMLElement).style.display).toBe('');
});
it('Expand method with grouping testing', () => {
gridObj.detailRowModule.expand(gridObj.getDataRows()[0].querySelector('.e-detailrowcollapse'));
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(2);
expect(gridObj.getDataRows()[0].querySelectorAll('.e-detailrowexpand').length).toBe(1);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[0] as HTMLElement).style.display).toBe('');
});
it('expandcollapse group rows method testing', () => {
gridObj.groupModule.expandCollapseRows(gridObj.getContent().querySelectorAll('.e-recordplusexpand')[4]);
//expect(gridObj.getContent().querySelectorAll('tr:not([style*="display: none"])').length).toBe(27);
});
it('toogleExpandcollapse with invalid element testing', () => {
(gridObj.detailRowModule as any).toogleExpandcollapse(gridObj.getDataRows()[1].querySelector('.e-rowcell'));
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(2);
expect(gridObj.getDataRows()[1].querySelectorAll('.e-detailrowexpand').length).toBe(1);
expect((gridObj.getContentTable().querySelectorAll('.e-detailrow')[1] as HTMLElement).style.display).toBe('');
});
afterAll(() => {
(gridObj.detailRowModule as any).destroy();
destroy(gridObj);
gridObj = actionComplete = null;
});
});
describe('Keyboard operation', () => {
let gridObj: Grid;
let elem: HTMLElement = createElement('div', { id: 'Grid' });
beforeAll((done: Function) => {
let dataBound: EmitType<Object> = () => {
gridObj.element.focus();
gridObj.dataBound = null;
done();
};
document.body.appendChild(elem);
gridObj = new Grid(
{
dataSource: filterData,
allowPaging: true,
detailTemplate: '#detailtemplate',
detailDataBound: detail,
allowGrouping: true,
selectionSettings: { type: 'Multiple', mode: 'Row' },
allowFiltering: true,
allowSorting: true,
allowReordering: true,
columns: [
{ field: 'OrderID', headerText: 'Order ID', width: 120, textAlign: 'Right' },
{ field: 'CustomerID', headerText: 'Customer ID', width: 125 },
{ field: 'Freight', width: 120, format: 'C', textAlign: 'Right' },
{ field: 'ShipCity', headerText: 'Ship City', width: 150 }
],
dataBound: dataBound
});
gridObj.appendTo('#Grid');
});
it('Detail expand testing', () => {
let target: any = (gridObj.getDataRows()[0].querySelector('.e-detailrowcollapse') as HTMLElement);
gridObj.keyboardModule.keyAction(<any>{ action: 'enter', target: target, preventDefault: () => { } });
expect(target.classList.contains('e-detailrowexpand')).toBeTruthy();
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
});
afterAll(() => {
elem.remove();
gridObj = elem = null;
});
});
describe('Action Complete event for expandAll and collapseAll=> ', () => {
let gridObj: Grid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData,
detailTemplate: '#detailtemplate',
allowPaging: true,
columns: [
{ field: 'OrderID', headerText: 'Order ID', width: 120, textAlign: 'Right' },
{ field: 'CustomerID', headerText: 'Customer ID', width: 125 },
{ field: 'Freight', width: 120, format: 'C', textAlign: 'Right' },
{ field: 'ShipCity', headerText: 'Ship City', width: 150 }
],
actionComplete: actionComplete
}, done);
});
it('actionComplete event triggerred for expandAll action complete', () => {
actionComplete = (args?: any): void => {
expect(args.requestType).toBe('expandAllComplete');
}
gridObj.actionComplete = actionComplete;
gridObj.detailRowModule.expandAll();
});
it('actionComplete event triggerred for collapseAll action complete', () => {
actionComplete = (args?: any): void => {
expect(args.requestType).toBe('collapseAllComplete');
}
gridObj.actionComplete = actionComplete;
gridObj.detailRowModule.collapseAll();
});
afterAll(() => {
destroy(gridObj);
gridObj = actionComplete = null;
});
});
describe('Hierarchy Render testing', () => {
let gridObj: Grid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: employeeData,
allowPaging: true,
allowGrouping: true,
selectionSettings: { type: 'Multiple', mode: 'Row' },
allowFiltering: true,
allowSorting: true,
allowReordering: true,
actionComplete: actionComplete,
allowRowDragAndDrop: true,
columns: [
{ field: 'EmployeeID', headerText: 'Employee ID', textAlign: 'Right', width: 75 },
{ field: 'FirstName', headerText: 'First Name', textAlign: 'Left', width: 100 },
{ field: 'Title', headerText: 'Title', textAlign: 'Left', width: 120 },
{ field: 'City', headerText: 'City', textAlign: 'Left', width: 100 },
{ field: 'Country', headerText: 'Country', textAlign: 'Left', width: 100 }
],
childGrid: {
dataSource: filterData, queryString: 'EmployeeID',
allowPaging: true,
allowGrouping: true,
allowRowDragAndDrop: true,
selectionSettings: { type: 'Multiple', mode: 'Row' },
pageSettings: { pageCount: 5, pageSize: 5 },
allowFiltering: true,
allowSorting: true,
groupSettings: { showGroupedColumn: false },
allowReordering: true,
allowTextWrap: true,
columns: [
{ field: 'OrderID', headerText: 'Order ID', textAlign: 'Right', width: 75 },
{ field: 'EmployeeID', headerText: 'Employee ID', textAlign: 'Right', width: 75 },
{ field: 'ShipCity', headerText: 'Ship City', textAlign: 'Left', width: 100 },
{ field: 'Freight', headerText: 'Freight', textAlign: 'Left', width: 120 },
{ field: 'ShipName', headerText: 'Ship Name', textAlign: 'Left', width: 100 }
]
},
}, done);
});
it('Hierarchy row with expand-RowDD', () => {
gridObj.detailRowModule.expand(gridObj.getDataRows()[1].querySelector('.e-detailrowcollapse'));
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow').length).toBe(1);
expect(gridObj.getDataRows()[1].querySelectorAll('.e-detailrowexpand').length).toBe(1);
expect(gridObj.getContentTable().querySelectorAll('.e-detailrow')[0].children[1].getAttribute('colspan')).toBe('6');
});
afterAll(() => {
destroy(gridObj);
gridObj = actionComplete = null;
});
});
describe('indent cell width check for autogenerated cols', () => {
let gridObj: Grid;
let rowDataBound: (args: any) => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: filterData.slice(0, 30),
allowFiltering: true,
filterSettings: { type: 'Excel' },
detailTemplate:'#detailTemp',
}, done);
});
it('indent width checking:', () => {
rowDataBound = (args: any) =>{
expect(((gridObj.element.querySelectorAll('.e-detailrowcollapse')[0])as HTMLElement).offsetWidth).toBe(30);
expect(((gridObj.element.querySelectorAll('.e-detailheadercell')[0])as HTMLElement).offsetWidth).toBe(30);
}
gridObj.rowDataBound = rowDataBound;
});
afterAll(() => {
destroy(gridObj);
gridObj = rowDataBound = null;
});
});
describe('EJ2-48397 - getRowIndexByPrimaryKey thrown script error while render child grid', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
}
gridObj = createGrid(
{
dataSource: filterData,
allowPaging: true,
detailTemplate: `<div>Hello</div>`,
columns: [
{ field: 'OrderID', headerText: 'Order ID', width: 120, textAlign: 'Right', isPrimaryKey: true },
{ field: 'CustomerID', headerText: 'Customer ID', width: 125 },
{ field: 'Freight', width: 120, format: 'C', textAlign: 'Right' },
{ field: 'ShipCity', headerText: 'Ship City', width: 150 }
]
}, done);
});
it('Test script error', (done: Function) => {
let detailDataBound = (e: any) => {
gridObj.getRowIndexByPrimaryKey(10249);
gridObj.detailDataBound = null;
done();
}
gridObj.detailDataBound = detailDataBound;
(gridObj.getDataRows()[0].querySelector('.e-detailrowcollapse') as HTMLElement).click();
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('EJ2-49020 - minWidth is not working', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
}
gridObj = createGrid(
{
dataSource: filterData,
allowPaging: true,
detailTemplate: `<div>Hello</div>`,
width:600,
columns: [
{ field: 'OrderID', headerText: 'Order ID', minWidth: 100, textAlign: 'Right' },
{ field: 'CustomerID', headerText: 'Customer ID', width: 150, showInColumnChooser: false },
{ field: 'OrderDate', headerText: 'Order Date', format: 'yMd', width: 150, textAlign: 'Right' },
{ field: 'Freight', format: 'C2', minWidth: 120, textAlign: 'Right' },
{ field: 'ShippedDate', headerText: 'Shipped Date', width: 150, format: 'yMd', textAlign: 'Right' },
{ field: 'ShipCountry', headerText: 'Ship Country', width: 150 }
]
}, done);
});
it('Test script error', (done: Function) => {
expect(gridObj.getHeaderTable().querySelectorAll('col')[1].style.width).toBe('100px');
expect(gridObj.getHeaderTable().querySelectorAll('col')[4].style.width).toBe('120px');
expect(gridObj.getContentTable().querySelectorAll('col')[1].style.width).toBe('100px');
expect(gridObj.getContentTable().querySelectorAll('col')[4].style.width).toBe('120px');
done();
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
}); | the_stack |
* @fileoverview Implements the SVG OutputJax object
*
* @author dpvc@mathjax.org (Davide Cervone)
*/
import {CommonOutputJax, UnknownBBox} from './common/OutputJax.js';
import {OptionList} from '../util/Options.js';
import {MathDocument} from '../core/MathDocument.js';
import {MathItem} from '../core/MathItem.js';
import {MmlNode} from '../core/MmlTree/MmlNode.js';
import {SVGWrapper} from './svg/Wrapper.js';
import {SVGWrapperFactory} from './svg/WrapperFactory.js';
import {SVGFontData} from './svg/FontData.js';
import {TeXFont} from './svg/fonts/tex.js';
import {StyleList as CssStyleList} from '../util/StyleList.js';
import {FontCache} from './svg/FontCache.js';
import {unicodeChars} from '../util/string.js';
import {percent} from '../util/lengths.js';
export const SVGNS = 'http://www.w3.org/2000/svg';
export const XLINKNS = 'http://www.w3.org/1999/xlink';
/*****************************************************************/
/**
* Implements the CHTML class (extends AbstractOutputJax)
*
* @template N The HTMLElement node class
* @template T The Text node class
* @template D The Document class
*/
export class SVG<N, T, D> extends
CommonOutputJax<N, T, D, SVGWrapper<N, T, D>, SVGWrapperFactory<N, T, D>, SVGFontData, typeof SVGFontData> {
/**
* The name of the output jax
*/
public static NAME: string = 'SVG';
/**
* @override
*/
public static OPTIONS: OptionList = {
...CommonOutputJax.OPTIONS,
internalSpeechTitles: true, // insert <title> tags with speech content
titleID: 0, // initial id number to use for aria-labeledby titles
fontCache: 'local', // or 'global' or 'none'
localID: null, // ID to use for local font cache (for single equation processing)
};
/**
* The default styles for SVG
*/
public static commonStyles: CssStyleList = {
'mjx-container[jax="SVG"]': {
direction: 'ltr'
},
'mjx-container[jax="SVG"] > svg': {
overflow: 'visible',
'min-height': '1px',
'min-width': '1px'
},
'mjx-container[jax="SVG"] > svg a': {
fill: 'blue', stroke: 'blue'
}
};
/**
* The ID for the SVG element that stores the cached font paths
*/
public static FONTCACHEID = 'MJX-SVG-global-cache';
/**
* The ID for the stylesheet element for the styles for the SVG output
*/
public static STYLESHEETID = 'MJX-SVG-styles';
/**
* Stores the CHTMLWrapper factory
*/
public factory: SVGWrapperFactory<N, T, D>;
/**
* Stores the information about the cached character glyphs
*/
public fontCache: FontCache<N, T, D>;
/**
* Minimum width for tables with labels,
*/
public minwidth: number = 0;
/**
* The shift for the main equation
*/
public shift: number = 0;
/**
* The container element for the math
*/
public container: N = null;
/**
* The SVG stylesheet, once it is constructed
*/
public svgStyles: N = null;
/**
* @override
* @constructor
*/
constructor(options: OptionList = null) {
super(options, SVGWrapperFactory as any, TeXFont);
this.fontCache = new FontCache(this);
}
/**
* @override
*/
public initialize() {
if (this.options.fontCache === 'global') {
this.fontCache.clearCache();
}
}
/**
* Clear the font cache (use for resetting the global font cache)
*/
public clearFontCache() {
this.fontCache.clearCache();
}
/**
* @override
*/
public reset() {
this.clearFontCache();
}
/**
* @override
*/
protected setScale(node: N) {
if (this.options.scale !== 1) {
this.adaptor.setStyle(node, 'fontSize', percent(this.options.scale));
}
}
/**
* @override
*/
public escaped(math: MathItem<N, T, D>, html: MathDocument<N, T, D>) {
this.setDocument(html);
return this.html('span', {}, [this.text(math.math)]);
}
/**
* @override
*/
public styleSheet(html: MathDocument<N, T, D>) {
if (this.svgStyles) {
return this.svgStyles; // stylesheet is already added to the document
}
const sheet = this.svgStyles = super.styleSheet(html);
this.adaptor.setAttribute(sheet, 'id', SVG.STYLESHEETID);
return sheet;
}
/**
* @override
*/
public pageElements(html: MathDocument<N, T, D>) {
if (this.options.fontCache === 'global' && !this.findCache(html)) {
return this.svg('svg', {id: SVG.FONTCACHEID, style: {display: 'none'}}, [this.fontCache.getCache()]);
}
return null as N;
}
/**
* Checks if there is already a font-cache element in the page
*
* @param {MathDocument} html The document to search
* @return {boolean} True if a font cache already exists in the page
*/
protected findCache(html: MathDocument<N, T, D>): boolean {
const adaptor = this.adaptor;
const svgs = adaptor.tags(adaptor.body(html.document), 'svg');
for (let i = svgs.length - 1; i >= 0; i--) {
if (this.adaptor.getAttribute(svgs[i], 'id') === SVG.FONTCACHEID) {
return true;
}
}
return false;
}
/**
* @param {MmlNode} math The MML node whose SVG is to be produced
* @param {N} parent The HTML node to contain the SVG
*/
protected processMath(math: MmlNode, parent: N) {
//
// Cache the container (tooltips process into separate containers)
//
const container = this.container;
this.container = parent;
//
// Get the wrapped math element and the SVG container
// Then typeset the math into the SVG
//
const wrapper = this.factory.wrap(math);
const [svg, g] = this.createRoot(wrapper);
this.typesetSVG(wrapper, svg, g);
//
// Put back the original container
//
this.container = container;
}
/**
* @param {SVGWrapper} wrapper The wrapped math to process
* @return {[N, N]} The svg and g nodes for the math
*/
protected createRoot(wrapper: SVGWrapper<N, T, D>): [N, N] {
const {w, h, d, pwidth} = wrapper.getBBox();
const px = wrapper.metrics.em / 1000;
const W = Math.max(w, px); // make sure we are at least one unitpx wide (needed for e.g. \llap)
const H = Math.max(h + d, px); // make sure we are at least one px tall (needed for e.g., \smash)
//
// The container that flips the y-axis and sets the colors to inherit from the surroundings
//
const g = this.svg('g', {
stroke: 'currentColor', fill: 'currentColor',
'stroke-width': 0, transform: 'scale(1,-1)'
}) as N;
//
// The svg element with its viewBox, size and alignment
//
const adaptor = this.adaptor;
const svg = adaptor.append(this.container, this.svg('svg', {
xmlns: SVGNS,
width: this.ex(W), height: this.ex(H),
role: 'img', focusable: false,
style: {'vertical-align': this.ex(-d)},
viewBox: [0, this.fixed(-h * 1000, 1), this.fixed(W * 1000, 1), this.fixed(H * 1000, 1)].join(' ')
}, [g])) as N;
if (W === .001) {
adaptor.setAttribute(svg, 'preserveAspectRatio', 'xMidYMid slice');
if (w < 0) {
adaptor.setStyle(this.container, 'margin-right', this.ex(w));
}
}
if (pwidth) {
//
// Use width 100% with no viewbox, and instead scale and translate to achieve the same result
//
adaptor.setStyle(svg, 'min-width', this.ex(W));
adaptor.setAttribute(svg, 'width', pwidth);
adaptor.removeAttribute(svg, 'viewBox');
const scale = this.fixed(wrapper.metrics.ex / (this.font.params.x_height * 1000), 6);
adaptor.setAttribute(g, 'transform', `scale(${scale},-${scale}) translate(0, ${this.fixed(-h * 1000, 1)})`);
}
if (this.options.fontCache !== 'none') {
adaptor.setAttribute(svg, 'xmlns:xlink', XLINKNS);
}
return [svg, g];
}
/**
* Typeset the math and add minwidth (from mtables), or set the alignment and indentation
* of the finalized expression.
*
* @param {SVGWrapper} wrapper The wrapped math to typeset
* @param {N} svg The main svg element for the typeet math
* @param {N} g The group in which the math is typeset
*/
protected typesetSVG(wrapper: SVGWrapper<N, T, D>, svg: N, g: N) {
const adaptor = this.adaptor;
//
// Typeset the math and add minWidth (from mtables), or set the alignment and indentation
// of the finalized expression
//
this.minwidth = this.shift = 0;
if (this.options.fontCache === 'local') {
this.fontCache.clearCache();
this.fontCache.useLocalID(this.options.localID);
adaptor.insert(this.fontCache.getCache(), g);
}
wrapper.toSVG(g);
this.fontCache.clearLocalID();
if (this.minwidth) {
adaptor.setStyle(svg, 'minWidth', this.ex(this.minwidth));
adaptor.setStyle(this.container, 'minWidth', this.ex(this.minwidth));
} else if (this.shift) {
const align = adaptor.getAttribute(this.container, 'justify') || 'center';
this.setIndent(svg, align, this.shift);
}
}
/**
* @param {N} svg The svg node whose indentation is to be adjusted
* @param {string} align The alignment for the node
* @param {number} shift The indent (positive or negative) for the node
*/
protected setIndent(svg: N, align: string, shift: number) {
if (align === 'center' || align === 'left') {
this.adaptor.setStyle(svg, 'margin-left', this.ex(shift));
}
if (align === 'center' || align === 'right') {
this.adaptor.setStyle(svg, 'margin-right', this.ex(-shift));
}
}
/**
* @param {number} m A number to be shown in ex
* @return {string} The number with units of ex
*/
public ex(m: number): string {
m /= this.font.params.x_height;
return (Math.abs(m) < .001 ? '0' : m.toFixed(3).replace(/\.?0+$/, '') + 'ex');
}
/**
* @param {string} kind The kind of node to create
* @param {OptionList} properties The properties to set for the element
* @param {(N|T)[]} children The child nodes for this node
* @return {N} The newly created node in the SVG namespace
*/
public svg(kind: string, properties: OptionList = {}, children: (N | T)[] = []): N {
return this.html(kind, properties, children, SVGNS);
}
/**
* @param {string} text The text to be displayed
* @param {string} variant The name of the variant for the text
* @return {N} The text element containing the text
*/
public unknownText(text: string, variant: string): N {
const metrics = this.math.metrics;
const scale = this.font.params.x_height / metrics.ex * metrics.em * 1000;
const svg = this.svg('text', {
'data-variant': variant,
transform: 'scale(1,-1)', 'font-size': this.fixed(scale, 1) + 'px'
}, [this.text(text)]);
const adaptor = this.adaptor;
if (variant !== '-explicitFont') {
const c = unicodeChars(text);
if (c.length !== 1 || c[0] < 0x1D400 || c[0] > 0x1D7FF) {
const [family, italic, bold] = this.font.getCssFont(variant);
adaptor.setAttribute(svg, 'font-family', family);
if (italic) {
adaptor.setAttribute(svg, 'font-style', 'italic');
}
if (bold) {
adaptor.setAttribute(svg, 'font-weight', 'bold');
}
}
}
return svg;
}
/**
* Measure the width of a text element by placing it in the page
* and looking up its size (fake the height and depth, since we can't measure that)
*
* @param {N} text The text element to measure
* @return {Object} The width, height and depth for the text
*/
public measureTextNode(text: N): UnknownBBox {
const adaptor = this.adaptor;
text = adaptor.clone(text);
adaptor.removeAttribute(text, 'transform');
const ex = this.fixed(this.font.params.x_height * 1000, 1);
const svg = this.svg('svg', {
position: 'absolute', visibility: 'hidden',
width: '1ex', height: '1ex',
viewBox: [0, 0, ex, ex].join(' ')
}, [text]);
adaptor.append(adaptor.body(adaptor.document), svg);
let w = adaptor.nodeSize(text, 1000, true)[0];
adaptor.remove(svg);
return {w: w, h: .75, d: .2};
}
} | the_stack |
import Conditions from '../../../../../resources/conditions';
import NetRegexes from '../../../../../resources/netregexes';
import Outputs from '../../../../../resources/outputs';
import { Responses } from '../../../../../resources/responses';
import ZoneId from '../../../../../resources/zone_id';
import { RaidbossData } from '../../../../../types/data';
import { TriggerSet } from '../../../../../types/trigger';
export interface Data extends RaidbossData {
primordialCrust?: boolean;
entropyCount?: number;
phaseType?: string;
wind?: string;
head?: string;
blazeCount?: number;
}
// O9S - Alphascape 1.0 Savage
const triggerSet: TriggerSet<Data> = {
zoneId: ZoneId.AlphascapeV10Savage,
timelineFile: 'o9s.txt',
triggers: [
// General actions
{
id: 'O9S Chaotic Dispersion',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3170', source: 'Chaos' }),
netRegexDe: NetRegexes.startsUsing({ id: '3170', source: 'Chaos' }),
netRegexFr: NetRegexes.startsUsing({ id: '3170', source: 'Chaos' }),
netRegexJa: NetRegexes.startsUsing({ id: '3170', source: 'カオス' }),
netRegexCn: NetRegexes.startsUsing({ id: '3170', source: '卡奥斯' }),
netRegexKo: NetRegexes.startsUsing({ id: '3170', source: '카오스' }),
response: Responses.tankBuster(),
},
{
id: 'O9S Longitudinal Implosion',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3172', source: 'Chaos', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '3172', source: 'Chaos', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '3172', source: 'Chaos', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '3172', source: 'カオス', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '3172', source: '卡奥斯', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '3172', source: '카오스', capture: false }),
alertText: (data, _matches, output) => {
if (data.primordialCrust)
return output.dieOnFrontBack!();
},
infoText: (data, _matches, output) => {
if (!data.primordialCrust)
return output.sides!();
},
outputStrings: {
sides: {
en: 'Sides -> Front/Back',
de: 'Seiten -> Vorne/Hinten',
fr: 'Côtés puis Devant/Derrière',
ja: '横 -> 縦',
cn: '左右 -> 前后',
ko: '양옆 -> 앞뒤',
},
dieOnFrontBack: {
en: 'Die on Front/Back -> Sides',
de: 'Stirb Vorne/Hinten -> Seiten',
fr: 'Devant/Derrière puis Côtés',
ja: '縦 -> 横で死ぬ',
cn: '死:前后 -> 左右',
ko: '앞뒤 -> 양옆 (디버프)',
},
},
},
{
id: 'O9S Latitudinal Implosion',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3173', source: 'Chaos', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '3173', source: 'Chaos', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '3173', source: 'Chaos', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '3173', source: 'カオス', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '3173', source: '卡奥斯', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '3173', source: '카오스', capture: false }),
alertText: (data, _matches, output) => {
if (data.primordialCrust)
return output.dieOnSides!();
},
infoText: (data, _matches, output) => {
if (!data.primordialCrust)
return output.frontBack!();
},
outputStrings: {
frontBack: {
en: 'Front/Back -> Sides',
de: 'Vorne/Hinten -> Seiten',
fr: 'Devant/Derrière puis Côtés',
ja: '縦 -> 横',
cn: '前后 -> 左右',
ko: '앞뒤 -> 양옆',
},
dieOnSides: {
en: 'Die on Sides -> Front/Back',
de: 'Stirb an Seiten -> Vorne/Hinten',
fr: 'Devant/Derrière puis Côtés',
ja: '横 -> 縦で死ぬ',
cn: '死:左右 -> 前后',
ko: '양옆 -> 앞뒤 (디버프)',
},
},
},
{
id: 'O9S Damning Edict',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3171', source: 'Chaos', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '3171', source: 'Chaos', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '3171', source: 'Chaos', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '3171', source: 'カオス', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '3171', source: '卡奥斯', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '3171', source: '카오스', capture: false }),
response: Responses.getBehind(),
},
{
id: 'O9S Orbs Fiend',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '317D', source: 'Chaos', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '317D', source: 'Chaos', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '317D', source: 'Chaos', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '317D', source: 'カオス', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '317D', source: '卡奥斯', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '317D', source: '카오스', capture: false }),
alarmText: (data, _matches, output) => {
if (data.role === 'tank')
return output.orbTethers!();
},
infoText: (data, _matches, output) => {
if (data.role === 'healer')
return output.orbTethers!();
},
outputStrings: {
orbTethers: {
en: 'Orb Tethers',
de: 'Kugel-Verbindungen',
fr: 'Récupérez l\'orbe',
ja: '線出たよ',
cn: '坦克接线注意治疗',
ko: '구슬 연결',
},
},
},
// Fire Path
{
id: 'O9S Fire Phase Tracking',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3186', source: 'Chaos', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '3186', source: 'Chaos', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '3186', source: 'Chaos', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '3186', source: 'カオス', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '3186', source: '卡奥斯', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '3186', source: '카오스', capture: false }),
run: (data) => {
if (data.phaseType !== 'enrage')
data.phaseType = 'fire';
},
},
{
id: 'O9S Entropy Spread',
type: 'GainsEffect',
netRegex: NetRegexes.gainsEffect({ effectId: '640' }),
condition: Conditions.targetIsYou(),
preRun: (data) => {
data.entropyCount = (data.entropyCount ?? 0) + 1;
},
delaySeconds: (data, matches) => {
// Warn dps earlier to stack.
if (data.role !== 'tank' && data.role !== 'healer' && data.entropyCount === 2)
return parseFloat(matches.duration) - 12;
return parseFloat(matches.duration) - 5;
},
alertText: (data, _matches, output) => {
if (data.phaseType === 'enrage' || data.phaseType === 'orb' || data.entropyCount === 1)
return output.spread!();
else if (data.role === 'tank' || data.role === 'healer')
return output.spreadAndStay!();
// DPS entropy #2
return output.stackAndStayOut!();
},
run: (data) => {
if (data.phaseType === 'orb' || data.entropyCount === 2)
delete data.entropyCount;
},
outputStrings: {
spread: Outputs.spread,
spreadAndStay: {
en: 'Spread and Stay',
de: 'Verteilen und bleiben',
fr: 'Écartez-vous et restez',
ja: '散開して待機',
cn: '分散并停留',
ko: '산개하고 가만히',
},
stackAndStayOut: {
en: 'Stack and Stay Out',
de: 'Stack und Bleiben',
fr: 'Packez-vous et restez',
ja: '中央に集合',
cn: '中间集合',
ko: '산개하고 바깥에 있기',
},
},
},
{
id: 'O9S Entropy Avoid Hit',
type: 'GainsEffect',
netRegex: NetRegexes.gainsEffect({ effectId: '640' }),
condition: (data, matches) => matches.target === data.me && data.phaseType === 'fire',
delaySeconds: (_data, matches) => {
// Folks get either the 24 second or the 10 second.
// So, delay for the opposite minus 5.
const seconds = parseFloat(matches.duration);
// Got 24 seconds (dps)
if (seconds > 11)
return 5;
// Got 10 seconds (tank)
return 19;
},
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Hide Middle',
de: 'Zur Mitte',
fr: 'Allez au centre',
ja: '中央へ',
cn: '中间躲避',
ko: '중앙으로 모이기',
},
},
},
{
id: 'O9S Fire Big Bang',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3180', source: 'Chaos', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '3180', source: 'Chaos', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '3180', source: 'Chaos', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '3180', source: 'カオス', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '3180', source: '卡奥斯', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '3180', source: '카오스', capture: false }),
condition: (data) => data.phaseType === 'fire',
// Each big bang has its own cast, so suppress.
suppressSeconds: 1,
alertText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Hide Middle',
de: 'Zur Mitte',
fr: 'Allez au centre',
ja: '中央へ',
cn: '中间躲避',
ko: '중앙으로 모이기',
},
},
},
// Water Path
{
id: 'O9S Water Phase Tracking',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3187', source: 'Chaos', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '3187', source: 'Chaos', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '3187', source: 'Chaos', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '3187', source: 'カオス', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '3187', source: '卡奥斯', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '3187', source: '카오스', capture: false }),
run: (data) => {
if (data.phaseType !== 'enrage')
data.phaseType = 'water';
},
},
{
id: 'O9S Dynamic Fluid 1',
type: 'GainsEffect',
netRegex: NetRegexes.gainsEffect({ effectId: '641', capture: false }),
condition: (data) => data.phaseType === 'water',
delaySeconds: 5,
suppressSeconds: 1,
// T/H get 10s & DPS get 17s
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Stack Donut',
de: 'Sammeln Donut',
fr: 'Packez-vous',
ja: 'スタック',
cn: '集合放月环',
ko: '도넛 쉐어',
},
},
},
{
id: 'O9S Dynamic Fluid 2',
type: 'GainsEffect',
netRegex: NetRegexes.gainsEffect({ effectId: '641', capture: false }),
condition: (data) => data.phaseType === 'water',
// T/H get 10s & DPS get 17s
delaySeconds: 12,
suppressSeconds: 1,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Stack Donut',
de: 'Sammeln Donut',
fr: 'Packez-vous',
ja: 'スタック',
cn: '集合放月环',
ko: '도넛 쉐어',
},
},
},
{
id: 'O9S Dynamic Fluid 3',
type: 'GainsEffect',
netRegex: NetRegexes.gainsEffect({ effectId: '641', capture: false }),
condition: (data) => data.phaseType === 'enrage',
// enrage -> 6s
delaySeconds: 1,
suppressSeconds: 1,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Stack Donut',
de: 'Sammeln Donut',
fr: 'Packez-vous',
ja: 'スタック',
cn: '集合放月环',
ko: '도넛 쉐어',
},
},
},
{
id: 'O9S Knock Down Marker',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '0057' }),
condition: Conditions.targetIsYou(),
alertText: (data, _matches, output) => {
if (data.phaseType === 'water')
return output.dropOutside!();
else if (data.phaseType === 'wind')
return output.dropOutsideKnockback!();
},
outputStrings: {
dropOutside: {
en: 'Drop Outside',
de: 'Gehe Nord / Süd',
fr: 'Allez au Nord/Sud',
ja: 'メテオ捨てて',
cn: '远离放点名',
ko: '바깥으로 빼기',
},
dropOutsideKnockback: {
en: 'Drop Outside + Knockback',
de: 'Geh nächste Ecke nah am Tornado',
fr: 'Déposez dans les coins + Poussée',
ja: 'メテオ捨てて + ノックバック',
cn: '远离放点名 + 冲回人群',
ko: '바깥으로 빼기 + 넉백',
},
},
},
// Wind Path
{
id: 'O9S Wind Phase Tracking',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3188', source: 'Chaos', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '3188', source: 'Chaos', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '3188', source: 'Chaos', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '3188', source: 'カオス', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '3188', source: '卡奥斯', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '3188', source: '카오스', capture: false }),
run: (data) => {
if (data.phaseType !== 'enrage')
data.phaseType = 'wind';
},
},
{
id: 'O9S Headwind',
type: 'GainsEffect',
netRegex: NetRegexes.gainsEffect({ effectId: '642' }),
condition: Conditions.targetIsYou(),
run: (data) => data.wind = 'head',
},
{
id: 'O9S Tailwind',
type: 'GainsEffect',
netRegex: NetRegexes.gainsEffect({ effectId: '643' }),
condition: Conditions.targetIsYou(),
run: (data) => data.wind = 'tail',
},
{
id: 'O9S Cyclone Knockback',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '318F', source: 'Chaos', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '318F', source: 'Chaos', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '318F', source: 'Chaos', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '318F', source: 'カオス', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '318F', source: '卡奥斯', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '318F', source: '카오스', capture: false }),
alarmText: (data, _matches, output) => {
if (data.wind === 'head')
return output.backToTornado!();
if (data.wind === 'tail')
return output.faceTheTornado!();
},
run: (data) => delete data.wind,
outputStrings: {
backToTornado: {
en: 'Back to Tornado',
de: 'Rücken zum Tornado',
fr: 'Regardez vers l\'extérieur',
ja: '竜巻を見ない',
cn: '背对龙卷风',
ko: '토네이도 뒤돌기',
},
faceTheTornado: {
en: 'Face the Tornado',
de: 'Zum Tornado hin',
fr: 'Regardez la tornade',
ja: '竜巻を見る',
cn: '面对龙卷风',
ko: '토네이도 바라보기',
},
},
},
// Earth Path
{
id: 'O9S Earth Phase Tracking',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3189', source: 'Chaos', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '3189', source: 'Chaos', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '3189', source: 'Chaos', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '3189', source: 'カオス', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '3189', source: '卡奥斯', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '3189', source: '카오스', capture: false }),
run: (data) => {
if (data.phaseType !== 'enrage')
data.phaseType = 'earth';
},
},
{
id: 'O9S Accretion',
type: 'GainsEffect',
netRegex: NetRegexes.gainsEffect({ effectId: '644', capture: false }),
condition: (data) => data.role === 'healer',
suppressSeconds: 10,
infoText: (data, _matches, output) => {
if (data.phaseType !== 'earth')
return output.healAllToFull!();
return output.healTankshealersToFull!();
},
outputStrings: {
healAllToFull: {
en: 'Heal All to Full',
de: 'Alle vollheilen',
fr: 'Soignez tout le monde complètement',
ja: 'HP戻して',
cn: '奶满全队',
ko: '전원 체력 풀피로',
},
healTankshealersToFull: {
en: 'Heal Tanks/Healers to full',
de: 'Tanks/Heiler vollheilen',
fr: 'Soignez Heals/Tanks complètement',
ja: 'HP戻して',
cn: '奶满T奶',
ko: '탱/힐 체력 풀피로',
},
},
},
{
id: 'O9S Primordial Crust',
type: 'GainsEffect',
netRegex: NetRegexes.gainsEffect({ effectId: '645' }),
condition: (data, matches) => data.me === matches.target && data.phaseType !== 'orb',
infoText: (_data, _matches, output) => output.text!(),
run: (data) => data.primordialCrust = true,
outputStrings: {
text: {
en: 'Die on next mechanic',
de: 'An nächster Mechanik tödlichen Schaden nehmen',
fr: 'Mourrez sur la prochaine mécanique',
ja: '次のギミックで死んでね',
cn: '想办法找死',
ko: '다음 기믹에 맞기 (디버프)',
},
},
},
{
id: 'O9S Primordial Crust Cleanup',
type: 'GainsEffect',
netRegex: NetRegexes.gainsEffect({ effectId: '645' }),
condition: Conditions.targetIsYou(),
delaySeconds: 30,
run: (data) => delete data.primordialCrust,
},
{
id: 'O9S Earth Stack Marker',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '003E', capture: false }),
suppressSeconds: 10,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Stack with partner',
de: 'Stacks verteilen',
fr: 'Packez-vous en binôme',
ja: '相手と頭割り',
cn: '与伙伴重合',
ko: '파트너랑 모이기',
},
},
},
// Orb Phase
{
id: 'O9S Orb Phase Tracking',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '318A', source: 'Chaos', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '318A', source: 'Chaos', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '318A', source: 'Chaos', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '318A', source: 'カオス', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '318A', source: '卡奥斯', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '318A', source: '카오스', capture: false }),
preRun: (data) => data.phaseType = 'orb',
},
{
id: 'O9S Orb Entropy',
type: 'GainsEffect',
netRegex: NetRegexes.gainsEffect({ effectId: '640' }),
condition: (data, matches) => matches.target !== data.me && data.phaseType === 'orb',
delaySeconds: (_data, matches) => parseFloat(matches.duration) - 3,
suppressSeconds: 10,
alertText: (data, _matches, output) => {
if (data.head === 'wind')
return output.text!();
},
run: (data) => delete data.wind,
outputStrings: {
text: {
en: 'Back to DPS',
de: 'Rücken zum DPS',
fr: 'Dos au DPS',
ja: 'DPSの後ろへ',
cn: '背对DPS',
ko: '딜러한테서 뒤돌기',
},
},
},
{
id: 'O9S Orb Dynamic Fluid',
type: 'GainsEffect',
netRegex: NetRegexes.gainsEffect({ effectId: '641' }),
condition: (data, matches) => matches.target === data.me && data.phaseType === 'orb',
delaySeconds: (_data, matches) => parseFloat(matches.duration) - 5,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Hit DPS with Water',
de: 'töte deinen DPS',
fr: 'Tuez les DPS',
ja: '水当てて',
cn: '水环害死DPS',
ko: '딜러 물 맞기',
},
},
},
// Enrage Phase
{
id: 'O9S Enrage Phase Tracking',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3186', source: 'Chaos', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '3186', source: 'Chaos', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '3186', source: 'Chaos', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '3186', source: 'カオス', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '3186', source: '卡奥斯', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '3186', source: '카오스', capture: false }),
run: (data) => {
data.blazeCount = (data.blazeCount ?? 0) + 1;
if (data.blazeCount >= 3)
data.phaseType = 'enrage';
},
},
],
timelineReplace: [
{
'locale': 'de',
'replaceSync': {
'Chaos': 'Chaos',
},
'replaceText': {
'Big Bang': 'Quantengravitation',
'Blaze': 'Flamme',
'Bowels of Agony': 'Quälende Eingeweide',
'Chaotic Dispersion': 'Chaos-Dispersion',
'Cyclone': 'Tornado',
'Damning Edict': 'Verdammendes Edikt',
'Earthquake': 'Erdbeben',
'Fiendish Orbs': 'Höllenkugeln',
'Knock(?! )': 'Einschlag',
'Long/Lat Implosion': 'Horizontale/Vertikale Implosion',
'Soul of Chaos': 'Chaosseele',
'Stray Earth': 'Chaoserde',
'Stray Flames': 'Chaosflammen',
'Stray Gusts': 'Chaosböen',
'Stray Spray': 'Chaosspritzer',
'Tsunami': 'Tsunami',
'Umbra Smash': 'Schattenschlag',
'\\(ALL\\)': '(ALLE)',
},
},
{
'locale': 'fr',
'replaceSync': {
'Chaos': 'Chaos',
},
'replaceText': {
'Big Bang': 'Saillie',
'Blaze': 'Flammes',
'Bowels of Agony': 'Entrailles de l\'agonie',
'Chaotic Dispersion': 'Dispersion chaotique',
'Cyclone': 'Tornade',
'Damning Edict': 'Décret accablant',
'Earthquake': 'Grand séisme',
'Fiendish Orbs': 'Ordre de poursuite',
'Knock(?! )': 'Impact',
'Long/Lat Implosion': 'Implosion Hz/Vert',
'Soul of Chaos': 'Âme du chaos',
'Stray Earth': 'Terre du chaos',
'Stray Flames': 'Flammes du chaos',
'Stray Gusts': 'Vent du chaos',
'Stray Spray': 'Eaux du chaos',
'Tsunami': 'Raz-de-marée',
'Umbra Smash': 'Fracas ombral',
'\\(ALL\\)': '(Tous)',
},
},
{
'locale': 'ja',
'replaceSync': {
'Chaos': 'カオス',
},
'replaceText': {
'Big Bang': '突出',
'Blaze': 'ほのお',
'Bowels of Agony': 'バウル・オブ・アゴニー',
'Chaotic Dispersion': 'カオティックディスパーション',
'Cyclone': 'たつまき',
'Damning Edict': 'ダミングイーディクト',
'Earthquake': 'じしん',
'Fiendish Orbs': '追尾せよ',
'Knock(?! )': '着弾',
'Long/Lat Implosion': 'インプロージョン 横/縦',
'Soul of Chaos': 'ソウル・オブ・カオス',
'Stray Earth': '混沌の土',
'Stray Flames': '混沌の炎',
'Stray Gusts': '混沌の風',
'Stray Spray': '混沌の水',
'Tsunami': 'つなみ',
'Umbra Smash': 'アンブラスマッシュ',
'\\(ALL\\)': '(全て)',
},
},
{
'locale': 'cn',
'replaceSync': {
'Chaos': '卡奥斯',
},
'replaceText': {
'Big Bang': '돌출',
'Blaze': '烈焰',
'Bowels of Agony': '深层痛楚',
'Chaotic Dispersion': '散布混沌',
'Cyclone': '龙卷风',
'Damning Edict': '诅咒敕令',
'Earthquake': '地震',
'Fiendish Orbs': '追踪',
'Knock(?! )': '中弹',
'Long/Lat Implosion': '经/纬聚爆',
'Soul of Chaos': '混沌之魂',
'Stray Earth': '混沌之土',
'Stray Flames': '混沌之炎',
'Stray Gusts': '混沌之风',
'Stray Spray': '混沌之水',
'Tsunami': '海啸',
'Umbra Smash': '本影爆碎',
'\\(ALL\\)': '\\(全部\\)',
},
},
{
'locale': 'ko',
'replaceSync': {
'Chaos': '카오스',
},
'replaceText': {
'Big Bang': '돌출하라',
'Blaze': '화염',
'Bowels of Agony': '고통의 심핵',
'Chaotic Dispersion': '혼돈 유포',
'Cyclone': '회오리',
'Damning Edict': '파멸 포고',
'Earthquake': '지진',
'Fiendish Orbs': '추격하라',
'Knock(?! )': '착탄',
'Long/Lat Implosion': '가로/세로 내파',
'Soul of Chaos': '혼돈의 영혼',
'Stray Earth': '혼돈의 흙',
'Stray Flames': '혼돈의 불',
'Stray Gusts': '혼돈의 바람',
'Stray Spray': '혼돈의 물',
'Tsunami': '해일',
'Umbra Smash': '그림자 타격',
'\\(ALL\\)': '(모두)',
},
},
],
};
export default triggerSet; | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { Reports } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { ApiManagementClient } from "../apiManagementClient";
import {
ReportRecordContract,
ReportsListByApiNextOptionalParams,
ReportsListByApiOptionalParams,
ReportsListByUserNextOptionalParams,
ReportsListByUserOptionalParams,
ReportsListByOperationNextOptionalParams,
ReportsListByOperationOptionalParams,
ReportsListByProductNextOptionalParams,
ReportsListByProductOptionalParams,
ReportsListByGeoNextOptionalParams,
ReportsListByGeoOptionalParams,
ReportsListBySubscriptionNextOptionalParams,
ReportsListBySubscriptionOptionalParams,
ReportsListByTimeNextOptionalParams,
ReportsListByTimeOptionalParams,
RequestReportRecordContract,
ReportsListByRequestOptionalParams,
ReportsListByApiResponse,
ReportsListByUserResponse,
ReportsListByOperationResponse,
ReportsListByProductResponse,
ReportsListByGeoResponse,
ReportsListBySubscriptionResponse,
ReportsListByTimeResponse,
ReportsListByRequestResponse,
ReportsListByApiNextResponse,
ReportsListByUserNextResponse,
ReportsListByOperationNextResponse,
ReportsListByProductNextResponse,
ReportsListByGeoNextResponse,
ReportsListBySubscriptionNextResponse,
ReportsListByTimeNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing Reports operations. */
export class ReportsImpl implements Reports {
private readonly client: ApiManagementClient;
/**
* Initialize a new instance of the class Reports class.
* @param client Reference to the service client
*/
constructor(client: ApiManagementClient) {
this.client = client;
}
/**
* Lists report records by API.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param filter The filter to apply on the operation.
* @param options The options parameters.
*/
public listByApi(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListByApiOptionalParams
): PagedAsyncIterableIterator<ReportRecordContract> {
const iter = this.listByApiPagingAll(
resourceGroupName,
serviceName,
filter,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByApiPagingPage(
resourceGroupName,
serviceName,
filter,
options
);
}
};
}
private async *listByApiPagingPage(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListByApiOptionalParams
): AsyncIterableIterator<ReportRecordContract[]> {
let result = await this._listByApi(
resourceGroupName,
serviceName,
filter,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByApiNext(
resourceGroupName,
serviceName,
filter,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByApiPagingAll(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListByApiOptionalParams
): AsyncIterableIterator<ReportRecordContract> {
for await (const page of this.listByApiPagingPage(
resourceGroupName,
serviceName,
filter,
options
)) {
yield* page;
}
}
/**
* Lists report records by User.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param filter | Field | Usage | Supported operators | Supported functions
* |</br>|-------------|-------------|-------------|-------------|</br>| timestamp | filter | ge, le
* | | </br>| displayName | select, orderBy | | | </br>| userId | select, filter | eq |
* | </br>| apiRegion | filter | eq | | </br>| productId | filter | eq | | </br>|
* subscriptionId | filter | eq | | </br>| apiId | filter | eq | | </br>| operationId | filter
* | eq | | </br>| callCountSuccess | select, orderBy | | | </br>| callCountBlocked |
* select, orderBy | | | </br>| callCountFailed | select, orderBy | | | </br>|
* callCountOther | select, orderBy | | | </br>| callCountTotal | select, orderBy | | |
* </br>| bandwidth | select, orderBy | | | </br>| cacheHitsCount | select | | | </br>|
* cacheMissCount | select | | | </br>| apiTimeAvg | select, orderBy | | | </br>|
* apiTimeMin | select | | | </br>| apiTimeMax | select | | | </br>| serviceTimeAvg |
* select | | | </br>| serviceTimeMin | select | | | </br>| serviceTimeMax | select |
* | | </br>
* @param options The options parameters.
*/
public listByUser(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListByUserOptionalParams
): PagedAsyncIterableIterator<ReportRecordContract> {
const iter = this.listByUserPagingAll(
resourceGroupName,
serviceName,
filter,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByUserPagingPage(
resourceGroupName,
serviceName,
filter,
options
);
}
};
}
private async *listByUserPagingPage(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListByUserOptionalParams
): AsyncIterableIterator<ReportRecordContract[]> {
let result = await this._listByUser(
resourceGroupName,
serviceName,
filter,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByUserNext(
resourceGroupName,
serviceName,
filter,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByUserPagingAll(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListByUserOptionalParams
): AsyncIterableIterator<ReportRecordContract> {
for await (const page of this.listByUserPagingPage(
resourceGroupName,
serviceName,
filter,
options
)) {
yield* page;
}
}
/**
* Lists report records by API Operations.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param filter | Field | Usage | Supported operators | Supported functions
* |</br>|-------------|-------------|-------------|-------------|</br>| timestamp | filter | ge, le
* | | </br>| displayName | select, orderBy | | | </br>| apiRegion | filter | eq | |
* </br>| userId | filter | eq | | </br>| productId | filter | eq | | </br>| subscriptionId |
* filter | eq | | </br>| apiId | filter | eq | | </br>| operationId | select, filter | eq |
* | </br>| callCountSuccess | select, orderBy | | | </br>| callCountBlocked | select, orderBy
* | | | </br>| callCountFailed | select, orderBy | | | </br>| callCountOther | select,
* orderBy | | | </br>| callCountTotal | select, orderBy | | | </br>| bandwidth |
* select, orderBy | | | </br>| cacheHitsCount | select | | | </br>| cacheMissCount |
* select | | | </br>| apiTimeAvg | select, orderBy | | | </br>| apiTimeMin | select |
* | | </br>| apiTimeMax | select | | | </br>| serviceTimeAvg | select | | |
* </br>| serviceTimeMin | select | | | </br>| serviceTimeMax | select | | | </br>
* @param options The options parameters.
*/
public listByOperation(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListByOperationOptionalParams
): PagedAsyncIterableIterator<ReportRecordContract> {
const iter = this.listByOperationPagingAll(
resourceGroupName,
serviceName,
filter,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByOperationPagingPage(
resourceGroupName,
serviceName,
filter,
options
);
}
};
}
private async *listByOperationPagingPage(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListByOperationOptionalParams
): AsyncIterableIterator<ReportRecordContract[]> {
let result = await this._listByOperation(
resourceGroupName,
serviceName,
filter,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByOperationNext(
resourceGroupName,
serviceName,
filter,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByOperationPagingAll(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListByOperationOptionalParams
): AsyncIterableIterator<ReportRecordContract> {
for await (const page of this.listByOperationPagingPage(
resourceGroupName,
serviceName,
filter,
options
)) {
yield* page;
}
}
/**
* Lists report records by Product.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param filter | Field | Usage | Supported operators | Supported functions
* |</br>|-------------|-------------|-------------|-------------|</br>| timestamp | filter | ge, le
* | | </br>| displayName | select, orderBy | | | </br>| apiRegion | filter | eq | |
* </br>| userId | filter | eq | | </br>| productId | select, filter | eq | | </br>|
* subscriptionId | filter | eq | | </br>| callCountSuccess | select, orderBy | | | </br>|
* callCountBlocked | select, orderBy | | | </br>| callCountFailed | select, orderBy | |
* | </br>| callCountOther | select, orderBy | | | </br>| callCountTotal | select, orderBy |
* | | </br>| bandwidth | select, orderBy | | | </br>| cacheHitsCount | select | |
* | </br>| cacheMissCount | select | | | </br>| apiTimeAvg | select, orderBy | | |
* </br>| apiTimeMin | select | | | </br>| apiTimeMax | select | | | </br>|
* serviceTimeAvg | select | | | </br>| serviceTimeMin | select | | | </br>|
* serviceTimeMax | select | | | </br>
* @param options The options parameters.
*/
public listByProduct(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListByProductOptionalParams
): PagedAsyncIterableIterator<ReportRecordContract> {
const iter = this.listByProductPagingAll(
resourceGroupName,
serviceName,
filter,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByProductPagingPage(
resourceGroupName,
serviceName,
filter,
options
);
}
};
}
private async *listByProductPagingPage(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListByProductOptionalParams
): AsyncIterableIterator<ReportRecordContract[]> {
let result = await this._listByProduct(
resourceGroupName,
serviceName,
filter,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByProductNext(
resourceGroupName,
serviceName,
filter,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByProductPagingAll(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListByProductOptionalParams
): AsyncIterableIterator<ReportRecordContract> {
for await (const page of this.listByProductPagingPage(
resourceGroupName,
serviceName,
filter,
options
)) {
yield* page;
}
}
/**
* Lists report records by geography.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param filter | Field | Usage | Supported operators | Supported functions
* |</br>|-------------|-------------|-------------|-------------|</br>| timestamp | filter | ge, le
* | | </br>| country | select | | | </br>| region | select | | | </br>| zip |
* select | | | </br>| apiRegion | filter | eq | | </br>| userId | filter | eq | |
* </br>| productId | filter | eq | | </br>| subscriptionId | filter | eq | | </br>| apiId |
* filter | eq | | </br>| operationId | filter | eq | | </br>| callCountSuccess | select |
* | | </br>| callCountBlocked | select | | | </br>| callCountFailed | select | | |
* </br>| callCountOther | select | | | </br>| bandwidth | select, orderBy | | | </br>|
* cacheHitsCount | select | | | </br>| cacheMissCount | select | | | </br>| apiTimeAvg
* | select | | | </br>| apiTimeMin | select | | | </br>| apiTimeMax | select | |
* | </br>| serviceTimeAvg | select | | | </br>| serviceTimeMin | select | | | </br>|
* serviceTimeMax | select | | | </br>
* @param options The options parameters.
*/
public listByGeo(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListByGeoOptionalParams
): PagedAsyncIterableIterator<ReportRecordContract> {
const iter = this.listByGeoPagingAll(
resourceGroupName,
serviceName,
filter,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByGeoPagingPage(
resourceGroupName,
serviceName,
filter,
options
);
}
};
}
private async *listByGeoPagingPage(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListByGeoOptionalParams
): AsyncIterableIterator<ReportRecordContract[]> {
let result = await this._listByGeo(
resourceGroupName,
serviceName,
filter,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByGeoNext(
resourceGroupName,
serviceName,
filter,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByGeoPagingAll(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListByGeoOptionalParams
): AsyncIterableIterator<ReportRecordContract> {
for await (const page of this.listByGeoPagingPage(
resourceGroupName,
serviceName,
filter,
options
)) {
yield* page;
}
}
/**
* Lists report records by subscription.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param filter | Field | Usage | Supported operators | Supported functions
* |</br>|-------------|-------------|-------------|-------------|</br>| timestamp | filter | ge, le
* | | </br>| displayName | select, orderBy | | | </br>| apiRegion | filter | eq | |
* </br>| userId | select, filter | eq | | </br>| productId | select, filter | eq | | </br>|
* subscriptionId | select, filter | eq | | </br>| callCountSuccess | select, orderBy | | |
* </br>| callCountBlocked | select, orderBy | | | </br>| callCountFailed | select, orderBy |
* | | </br>| callCountOther | select, orderBy | | | </br>| callCountTotal | select,
* orderBy | | | </br>| bandwidth | select, orderBy | | | </br>| cacheHitsCount |
* select | | | </br>| cacheMissCount | select | | | </br>| apiTimeAvg | select,
* orderBy | | | </br>| apiTimeMin | select | | | </br>| apiTimeMax | select | |
* | </br>| serviceTimeAvg | select | | | </br>| serviceTimeMin | select | | | </br>|
* serviceTimeMax | select | | | </br>
* @param options The options parameters.
*/
public listBySubscription(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListBySubscriptionOptionalParams
): PagedAsyncIterableIterator<ReportRecordContract> {
const iter = this.listBySubscriptionPagingAll(
resourceGroupName,
serviceName,
filter,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listBySubscriptionPagingPage(
resourceGroupName,
serviceName,
filter,
options
);
}
};
}
private async *listBySubscriptionPagingPage(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListBySubscriptionOptionalParams
): AsyncIterableIterator<ReportRecordContract[]> {
let result = await this._listBySubscription(
resourceGroupName,
serviceName,
filter,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listBySubscriptionNext(
resourceGroupName,
serviceName,
filter,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listBySubscriptionPagingAll(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListBySubscriptionOptionalParams
): AsyncIterableIterator<ReportRecordContract> {
for await (const page of this.listBySubscriptionPagingPage(
resourceGroupName,
serviceName,
filter,
options
)) {
yield* page;
}
}
/**
* Lists report records by Time.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param filter | Field | Usage | Supported operators | Supported functions
* |</br>|-------------|-------------|-------------|-------------|</br>| timestamp | filter, select
* | ge, le | | </br>| interval | select | | | </br>| apiRegion | filter | eq | |
* </br>| userId | filter | eq | | </br>| productId | filter | eq | | </br>| subscriptionId |
* filter | eq | | </br>| apiId | filter | eq | | </br>| operationId | filter | eq | |
* </br>| callCountSuccess | select | | | </br>| callCountBlocked | select | | | </br>|
* callCountFailed | select | | | </br>| callCountOther | select | | | </br>| bandwidth
* | select, orderBy | | | </br>| cacheHitsCount | select | | | </br>| cacheMissCount |
* select | | | </br>| apiTimeAvg | select | | | </br>| apiTimeMin | select | |
* | </br>| apiTimeMax | select | | | </br>| serviceTimeAvg | select | | | </br>|
* serviceTimeMin | select | | | </br>| serviceTimeMax | select | | | </br>
* @param interval By time interval. Interval must be multiple of 15 minutes and may not be zero. The
* value should be in ISO 8601 format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can
* be used to convert TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours,
* minutes, seconds)).
* @param options The options parameters.
*/
public listByTime(
resourceGroupName: string,
serviceName: string,
filter: string,
interval: string,
options?: ReportsListByTimeOptionalParams
): PagedAsyncIterableIterator<ReportRecordContract> {
const iter = this.listByTimePagingAll(
resourceGroupName,
serviceName,
filter,
interval,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByTimePagingPage(
resourceGroupName,
serviceName,
filter,
interval,
options
);
}
};
}
private async *listByTimePagingPage(
resourceGroupName: string,
serviceName: string,
filter: string,
interval: string,
options?: ReportsListByTimeOptionalParams
): AsyncIterableIterator<ReportRecordContract[]> {
let result = await this._listByTime(
resourceGroupName,
serviceName,
filter,
interval,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByTimeNext(
resourceGroupName,
serviceName,
filter,
interval,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByTimePagingAll(
resourceGroupName: string,
serviceName: string,
filter: string,
interval: string,
options?: ReportsListByTimeOptionalParams
): AsyncIterableIterator<ReportRecordContract> {
for await (const page of this.listByTimePagingPage(
resourceGroupName,
serviceName,
filter,
interval,
options
)) {
yield* page;
}
}
/**
* Lists report records by Request.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param filter | Field | Usage | Supported operators | Supported functions
* |</br>|-------------|-------------|-------------|-------------|</br>| timestamp | filter | ge, le
* | | </br>| apiId | filter | eq | | </br>| operationId | filter | eq | | </br>| productId
* | filter | eq | | </br>| userId | filter | eq | | </br>| apiRegion | filter | eq | |
* </br>| subscriptionId | filter | eq | | </br>
* @param options The options parameters.
*/
public listByRequest(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListByRequestOptionalParams
): PagedAsyncIterableIterator<RequestReportRecordContract> {
const iter = this.listByRequestPagingAll(
resourceGroupName,
serviceName,
filter,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByRequestPagingPage(
resourceGroupName,
serviceName,
filter,
options
);
}
};
}
private async *listByRequestPagingPage(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListByRequestOptionalParams
): AsyncIterableIterator<RequestReportRecordContract[]> {
let result = await this._listByRequest(
resourceGroupName,
serviceName,
filter,
options
);
yield result.value || [];
}
private async *listByRequestPagingAll(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListByRequestOptionalParams
): AsyncIterableIterator<RequestReportRecordContract> {
for await (const page of this.listByRequestPagingPage(
resourceGroupName,
serviceName,
filter,
options
)) {
yield* page;
}
}
/**
* Lists report records by API.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param filter The filter to apply on the operation.
* @param options The options parameters.
*/
private _listByApi(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListByApiOptionalParams
): Promise<ReportsListByApiResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, filter, options },
listByApiOperationSpec
);
}
/**
* Lists report records by User.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param filter | Field | Usage | Supported operators | Supported functions
* |</br>|-------------|-------------|-------------|-------------|</br>| timestamp | filter | ge, le
* | | </br>| displayName | select, orderBy | | | </br>| userId | select, filter | eq |
* | </br>| apiRegion | filter | eq | | </br>| productId | filter | eq | | </br>|
* subscriptionId | filter | eq | | </br>| apiId | filter | eq | | </br>| operationId | filter
* | eq | | </br>| callCountSuccess | select, orderBy | | | </br>| callCountBlocked |
* select, orderBy | | | </br>| callCountFailed | select, orderBy | | | </br>|
* callCountOther | select, orderBy | | | </br>| callCountTotal | select, orderBy | | |
* </br>| bandwidth | select, orderBy | | | </br>| cacheHitsCount | select | | | </br>|
* cacheMissCount | select | | | </br>| apiTimeAvg | select, orderBy | | | </br>|
* apiTimeMin | select | | | </br>| apiTimeMax | select | | | </br>| serviceTimeAvg |
* select | | | </br>| serviceTimeMin | select | | | </br>| serviceTimeMax | select |
* | | </br>
* @param options The options parameters.
*/
private _listByUser(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListByUserOptionalParams
): Promise<ReportsListByUserResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, filter, options },
listByUserOperationSpec
);
}
/**
* Lists report records by API Operations.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param filter | Field | Usage | Supported operators | Supported functions
* |</br>|-------------|-------------|-------------|-------------|</br>| timestamp | filter | ge, le
* | | </br>| displayName | select, orderBy | | | </br>| apiRegion | filter | eq | |
* </br>| userId | filter | eq | | </br>| productId | filter | eq | | </br>| subscriptionId |
* filter | eq | | </br>| apiId | filter | eq | | </br>| operationId | select, filter | eq |
* | </br>| callCountSuccess | select, orderBy | | | </br>| callCountBlocked | select, orderBy
* | | | </br>| callCountFailed | select, orderBy | | | </br>| callCountOther | select,
* orderBy | | | </br>| callCountTotal | select, orderBy | | | </br>| bandwidth |
* select, orderBy | | | </br>| cacheHitsCount | select | | | </br>| cacheMissCount |
* select | | | </br>| apiTimeAvg | select, orderBy | | | </br>| apiTimeMin | select |
* | | </br>| apiTimeMax | select | | | </br>| serviceTimeAvg | select | | |
* </br>| serviceTimeMin | select | | | </br>| serviceTimeMax | select | | | </br>
* @param options The options parameters.
*/
private _listByOperation(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListByOperationOptionalParams
): Promise<ReportsListByOperationResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, filter, options },
listByOperationOperationSpec
);
}
/**
* Lists report records by Product.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param filter | Field | Usage | Supported operators | Supported functions
* |</br>|-------------|-------------|-------------|-------------|</br>| timestamp | filter | ge, le
* | | </br>| displayName | select, orderBy | | | </br>| apiRegion | filter | eq | |
* </br>| userId | filter | eq | | </br>| productId | select, filter | eq | | </br>|
* subscriptionId | filter | eq | | </br>| callCountSuccess | select, orderBy | | | </br>|
* callCountBlocked | select, orderBy | | | </br>| callCountFailed | select, orderBy | |
* | </br>| callCountOther | select, orderBy | | | </br>| callCountTotal | select, orderBy |
* | | </br>| bandwidth | select, orderBy | | | </br>| cacheHitsCount | select | |
* | </br>| cacheMissCount | select | | | </br>| apiTimeAvg | select, orderBy | | |
* </br>| apiTimeMin | select | | | </br>| apiTimeMax | select | | | </br>|
* serviceTimeAvg | select | | | </br>| serviceTimeMin | select | | | </br>|
* serviceTimeMax | select | | | </br>
* @param options The options parameters.
*/
private _listByProduct(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListByProductOptionalParams
): Promise<ReportsListByProductResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, filter, options },
listByProductOperationSpec
);
}
/**
* Lists report records by geography.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param filter | Field | Usage | Supported operators | Supported functions
* |</br>|-------------|-------------|-------------|-------------|</br>| timestamp | filter | ge, le
* | | </br>| country | select | | | </br>| region | select | | | </br>| zip |
* select | | | </br>| apiRegion | filter | eq | | </br>| userId | filter | eq | |
* </br>| productId | filter | eq | | </br>| subscriptionId | filter | eq | | </br>| apiId |
* filter | eq | | </br>| operationId | filter | eq | | </br>| callCountSuccess | select |
* | | </br>| callCountBlocked | select | | | </br>| callCountFailed | select | | |
* </br>| callCountOther | select | | | </br>| bandwidth | select, orderBy | | | </br>|
* cacheHitsCount | select | | | </br>| cacheMissCount | select | | | </br>| apiTimeAvg
* | select | | | </br>| apiTimeMin | select | | | </br>| apiTimeMax | select | |
* | </br>| serviceTimeAvg | select | | | </br>| serviceTimeMin | select | | | </br>|
* serviceTimeMax | select | | | </br>
* @param options The options parameters.
*/
private _listByGeo(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListByGeoOptionalParams
): Promise<ReportsListByGeoResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, filter, options },
listByGeoOperationSpec
);
}
/**
* Lists report records by subscription.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param filter | Field | Usage | Supported operators | Supported functions
* |</br>|-------------|-------------|-------------|-------------|</br>| timestamp | filter | ge, le
* | | </br>| displayName | select, orderBy | | | </br>| apiRegion | filter | eq | |
* </br>| userId | select, filter | eq | | </br>| productId | select, filter | eq | | </br>|
* subscriptionId | select, filter | eq | | </br>| callCountSuccess | select, orderBy | | |
* </br>| callCountBlocked | select, orderBy | | | </br>| callCountFailed | select, orderBy |
* | | </br>| callCountOther | select, orderBy | | | </br>| callCountTotal | select,
* orderBy | | | </br>| bandwidth | select, orderBy | | | </br>| cacheHitsCount |
* select | | | </br>| cacheMissCount | select | | | </br>| apiTimeAvg | select,
* orderBy | | | </br>| apiTimeMin | select | | | </br>| apiTimeMax | select | |
* | </br>| serviceTimeAvg | select | | | </br>| serviceTimeMin | select | | | </br>|
* serviceTimeMax | select | | | </br>
* @param options The options parameters.
*/
private _listBySubscription(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListBySubscriptionOptionalParams
): Promise<ReportsListBySubscriptionResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, filter, options },
listBySubscriptionOperationSpec
);
}
/**
* Lists report records by Time.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param filter | Field | Usage | Supported operators | Supported functions
* |</br>|-------------|-------------|-------------|-------------|</br>| timestamp | filter, select
* | ge, le | | </br>| interval | select | | | </br>| apiRegion | filter | eq | |
* </br>| userId | filter | eq | | </br>| productId | filter | eq | | </br>| subscriptionId |
* filter | eq | | </br>| apiId | filter | eq | | </br>| operationId | filter | eq | |
* </br>| callCountSuccess | select | | | </br>| callCountBlocked | select | | | </br>|
* callCountFailed | select | | | </br>| callCountOther | select | | | </br>| bandwidth
* | select, orderBy | | | </br>| cacheHitsCount | select | | | </br>| cacheMissCount |
* select | | | </br>| apiTimeAvg | select | | | </br>| apiTimeMin | select | |
* | </br>| apiTimeMax | select | | | </br>| serviceTimeAvg | select | | | </br>|
* serviceTimeMin | select | | | </br>| serviceTimeMax | select | | | </br>
* @param interval By time interval. Interval must be multiple of 15 minutes and may not be zero. The
* value should be in ISO 8601 format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can
* be used to convert TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours,
* minutes, seconds)).
* @param options The options parameters.
*/
private _listByTime(
resourceGroupName: string,
serviceName: string,
filter: string,
interval: string,
options?: ReportsListByTimeOptionalParams
): Promise<ReportsListByTimeResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, filter, interval, options },
listByTimeOperationSpec
);
}
/**
* Lists report records by Request.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param filter | Field | Usage | Supported operators | Supported functions
* |</br>|-------------|-------------|-------------|-------------|</br>| timestamp | filter | ge, le
* | | </br>| apiId | filter | eq | | </br>| operationId | filter | eq | | </br>| productId
* | filter | eq | | </br>| userId | filter | eq | | </br>| apiRegion | filter | eq | |
* </br>| subscriptionId | filter | eq | | </br>
* @param options The options parameters.
*/
private _listByRequest(
resourceGroupName: string,
serviceName: string,
filter: string,
options?: ReportsListByRequestOptionalParams
): Promise<ReportsListByRequestResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, filter, options },
listByRequestOperationSpec
);
}
/**
* ListByApiNext
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param filter The filter to apply on the operation.
* @param nextLink The nextLink from the previous successful call to the ListByApi method.
* @param options The options parameters.
*/
private _listByApiNext(
resourceGroupName: string,
serviceName: string,
filter: string,
nextLink: string,
options?: ReportsListByApiNextOptionalParams
): Promise<ReportsListByApiNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, filter, nextLink, options },
listByApiNextOperationSpec
);
}
/**
* ListByUserNext
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param filter | Field | Usage | Supported operators | Supported functions
* |</br>|-------------|-------------|-------------|-------------|</br>| timestamp | filter | ge, le
* | | </br>| displayName | select, orderBy | | | </br>| userId | select, filter | eq |
* | </br>| apiRegion | filter | eq | | </br>| productId | filter | eq | | </br>|
* subscriptionId | filter | eq | | </br>| apiId | filter | eq | | </br>| operationId | filter
* | eq | | </br>| callCountSuccess | select, orderBy | | | </br>| callCountBlocked |
* select, orderBy | | | </br>| callCountFailed | select, orderBy | | | </br>|
* callCountOther | select, orderBy | | | </br>| callCountTotal | select, orderBy | | |
* </br>| bandwidth | select, orderBy | | | </br>| cacheHitsCount | select | | | </br>|
* cacheMissCount | select | | | </br>| apiTimeAvg | select, orderBy | | | </br>|
* apiTimeMin | select | | | </br>| apiTimeMax | select | | | </br>| serviceTimeAvg |
* select | | | </br>| serviceTimeMin | select | | | </br>| serviceTimeMax | select |
* | | </br>
* @param nextLink The nextLink from the previous successful call to the ListByUser method.
* @param options The options parameters.
*/
private _listByUserNext(
resourceGroupName: string,
serviceName: string,
filter: string,
nextLink: string,
options?: ReportsListByUserNextOptionalParams
): Promise<ReportsListByUserNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, filter, nextLink, options },
listByUserNextOperationSpec
);
}
/**
* ListByOperationNext
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param filter | Field | Usage | Supported operators | Supported functions
* |</br>|-------------|-------------|-------------|-------------|</br>| timestamp | filter | ge, le
* | | </br>| displayName | select, orderBy | | | </br>| apiRegion | filter | eq | |
* </br>| userId | filter | eq | | </br>| productId | filter | eq | | </br>| subscriptionId |
* filter | eq | | </br>| apiId | filter | eq | | </br>| operationId | select, filter | eq |
* | </br>| callCountSuccess | select, orderBy | | | </br>| callCountBlocked | select, orderBy
* | | | </br>| callCountFailed | select, orderBy | | | </br>| callCountOther | select,
* orderBy | | | </br>| callCountTotal | select, orderBy | | | </br>| bandwidth |
* select, orderBy | | | </br>| cacheHitsCount | select | | | </br>| cacheMissCount |
* select | | | </br>| apiTimeAvg | select, orderBy | | | </br>| apiTimeMin | select |
* | | </br>| apiTimeMax | select | | | </br>| serviceTimeAvg | select | | |
* </br>| serviceTimeMin | select | | | </br>| serviceTimeMax | select | | | </br>
* @param nextLink The nextLink from the previous successful call to the ListByOperation method.
* @param options The options parameters.
*/
private _listByOperationNext(
resourceGroupName: string,
serviceName: string,
filter: string,
nextLink: string,
options?: ReportsListByOperationNextOptionalParams
): Promise<ReportsListByOperationNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, filter, nextLink, options },
listByOperationNextOperationSpec
);
}
/**
* ListByProductNext
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param filter | Field | Usage | Supported operators | Supported functions
* |</br>|-------------|-------------|-------------|-------------|</br>| timestamp | filter | ge, le
* | | </br>| displayName | select, orderBy | | | </br>| apiRegion | filter | eq | |
* </br>| userId | filter | eq | | </br>| productId | select, filter | eq | | </br>|
* subscriptionId | filter | eq | | </br>| callCountSuccess | select, orderBy | | | </br>|
* callCountBlocked | select, orderBy | | | </br>| callCountFailed | select, orderBy | |
* | </br>| callCountOther | select, orderBy | | | </br>| callCountTotal | select, orderBy |
* | | </br>| bandwidth | select, orderBy | | | </br>| cacheHitsCount | select | |
* | </br>| cacheMissCount | select | | | </br>| apiTimeAvg | select, orderBy | | |
* </br>| apiTimeMin | select | | | </br>| apiTimeMax | select | | | </br>|
* serviceTimeAvg | select | | | </br>| serviceTimeMin | select | | | </br>|
* serviceTimeMax | select | | | </br>
* @param nextLink The nextLink from the previous successful call to the ListByProduct method.
* @param options The options parameters.
*/
private _listByProductNext(
resourceGroupName: string,
serviceName: string,
filter: string,
nextLink: string,
options?: ReportsListByProductNextOptionalParams
): Promise<ReportsListByProductNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, filter, nextLink, options },
listByProductNextOperationSpec
);
}
/**
* ListByGeoNext
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param filter | Field | Usage | Supported operators | Supported functions
* |</br>|-------------|-------------|-------------|-------------|</br>| timestamp | filter | ge, le
* | | </br>| country | select | | | </br>| region | select | | | </br>| zip |
* select | | | </br>| apiRegion | filter | eq | | </br>| userId | filter | eq | |
* </br>| productId | filter | eq | | </br>| subscriptionId | filter | eq | | </br>| apiId |
* filter | eq | | </br>| operationId | filter | eq | | </br>| callCountSuccess | select |
* | | </br>| callCountBlocked | select | | | </br>| callCountFailed | select | | |
* </br>| callCountOther | select | | | </br>| bandwidth | select, orderBy | | | </br>|
* cacheHitsCount | select | | | </br>| cacheMissCount | select | | | </br>| apiTimeAvg
* | select | | | </br>| apiTimeMin | select | | | </br>| apiTimeMax | select | |
* | </br>| serviceTimeAvg | select | | | </br>| serviceTimeMin | select | | | </br>|
* serviceTimeMax | select | | | </br>
* @param nextLink The nextLink from the previous successful call to the ListByGeo method.
* @param options The options parameters.
*/
private _listByGeoNext(
resourceGroupName: string,
serviceName: string,
filter: string,
nextLink: string,
options?: ReportsListByGeoNextOptionalParams
): Promise<ReportsListByGeoNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, filter, nextLink, options },
listByGeoNextOperationSpec
);
}
/**
* ListBySubscriptionNext
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param filter | Field | Usage | Supported operators | Supported functions
* |</br>|-------------|-------------|-------------|-------------|</br>| timestamp | filter | ge, le
* | | </br>| displayName | select, orderBy | | | </br>| apiRegion | filter | eq | |
* </br>| userId | select, filter | eq | | </br>| productId | select, filter | eq | | </br>|
* subscriptionId | select, filter | eq | | </br>| callCountSuccess | select, orderBy | | |
* </br>| callCountBlocked | select, orderBy | | | </br>| callCountFailed | select, orderBy |
* | | </br>| callCountOther | select, orderBy | | | </br>| callCountTotal | select,
* orderBy | | | </br>| bandwidth | select, orderBy | | | </br>| cacheHitsCount |
* select | | | </br>| cacheMissCount | select | | | </br>| apiTimeAvg | select,
* orderBy | | | </br>| apiTimeMin | select | | | </br>| apiTimeMax | select | |
* | </br>| serviceTimeAvg | select | | | </br>| serviceTimeMin | select | | | </br>|
* serviceTimeMax | select | | | </br>
* @param nextLink The nextLink from the previous successful call to the ListBySubscription method.
* @param options The options parameters.
*/
private _listBySubscriptionNext(
resourceGroupName: string,
serviceName: string,
filter: string,
nextLink: string,
options?: ReportsListBySubscriptionNextOptionalParams
): Promise<ReportsListBySubscriptionNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, filter, nextLink, options },
listBySubscriptionNextOperationSpec
);
}
/**
* ListByTimeNext
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param filter | Field | Usage | Supported operators | Supported functions
* |</br>|-------------|-------------|-------------|-------------|</br>| timestamp | filter, select
* | ge, le | | </br>| interval | select | | | </br>| apiRegion | filter | eq | |
* </br>| userId | filter | eq | | </br>| productId | filter | eq | | </br>| subscriptionId |
* filter | eq | | </br>| apiId | filter | eq | | </br>| operationId | filter | eq | |
* </br>| callCountSuccess | select | | | </br>| callCountBlocked | select | | | </br>|
* callCountFailed | select | | | </br>| callCountOther | select | | | </br>| bandwidth
* | select, orderBy | | | </br>| cacheHitsCount | select | | | </br>| cacheMissCount |
* select | | | </br>| apiTimeAvg | select | | | </br>| apiTimeMin | select | |
* | </br>| apiTimeMax | select | | | </br>| serviceTimeAvg | select | | | </br>|
* serviceTimeMin | select | | | </br>| serviceTimeMax | select | | | </br>
* @param interval By time interval. Interval must be multiple of 15 minutes and may not be zero. The
* value should be in ISO 8601 format (http://en.wikipedia.org/wiki/ISO_8601#Durations).This code can
* be used to convert TimeSpan to a valid interval string: XmlConvert.ToString(new TimeSpan(hours,
* minutes, seconds)).
* @param nextLink The nextLink from the previous successful call to the ListByTime method.
* @param options The options parameters.
*/
private _listByTimeNext(
resourceGroupName: string,
serviceName: string,
filter: string,
interval: string,
nextLink: string,
options?: ReportsListByTimeNextOptionalParams
): Promise<ReportsListByTimeNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, filter, interval, nextLink, options },
listByTimeNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const listByApiOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/reports/byApi",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ReportCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.top,
Parameters.skip,
Parameters.apiVersion,
Parameters.filter1,
Parameters.orderby
],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
};
const listByUserOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/reports/byUser",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ReportCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.top,
Parameters.skip,
Parameters.apiVersion,
Parameters.filter1,
Parameters.orderby
],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
};
const listByOperationOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/reports/byOperation",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ReportCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.top,
Parameters.skip,
Parameters.apiVersion,
Parameters.filter1,
Parameters.orderby
],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
};
const listByProductOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/reports/byProduct",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ReportCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.top,
Parameters.skip,
Parameters.apiVersion,
Parameters.filter1,
Parameters.orderby
],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
};
const listByGeoOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/reports/byGeo",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ReportCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.top,
Parameters.skip,
Parameters.apiVersion,
Parameters.filter1
],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
};
const listBySubscriptionOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/reports/bySubscription",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ReportCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.top,
Parameters.skip,
Parameters.apiVersion,
Parameters.filter1,
Parameters.orderby
],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
};
const listByTimeOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/reports/byTime",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ReportCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.top,
Parameters.skip,
Parameters.apiVersion,
Parameters.filter1,
Parameters.orderby,
Parameters.interval
],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
};
const listByRequestOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/reports/byRequest",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.RequestReportCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.top,
Parameters.skip,
Parameters.apiVersion,
Parameters.filter1
],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
};
const listByApiNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ReportCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.top,
Parameters.skip,
Parameters.apiVersion,
Parameters.filter1,
Parameters.orderby
],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
};
const listByUserNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ReportCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.top,
Parameters.skip,
Parameters.apiVersion,
Parameters.filter1,
Parameters.orderby
],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
};
const listByOperationNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ReportCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.top,
Parameters.skip,
Parameters.apiVersion,
Parameters.filter1,
Parameters.orderby
],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
};
const listByProductNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ReportCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.top,
Parameters.skip,
Parameters.apiVersion,
Parameters.filter1,
Parameters.orderby
],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
};
const listByGeoNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ReportCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.top,
Parameters.skip,
Parameters.apiVersion,
Parameters.filter1
],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
};
const listBySubscriptionNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ReportCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.top,
Parameters.skip,
Parameters.apiVersion,
Parameters.filter1,
Parameters.orderby
],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
};
const listByTimeNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ReportCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [
Parameters.top,
Parameters.skip,
Parameters.apiVersion,
Parameters.filter1,
Parameters.orderby,
Parameters.interval
],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
declare var describe, it, require;
import { Grammars, Parser, IToken } from '../dist';
import { testParseToken, describeTree, printBNF, testParseTokenFailsafe } from './TestHelpers';
let inspect = require('util').inspect;
let expect = require('expect');
let grammar = `
{ws=explicit}
Document ::= Directives EOF? {ws=implicit}
Directives ::= Directive Directives? {pin=1,ws=implicit,recoverUntil=DIRECTIVE_RECOVERY,fragment=true}
Directive ::= FunctionDirective | ValDirective | VarDirective | StructDirective {fragment=true}
FunctionDirective ::= EXPORT_KEYWORD? FUN_KEYWORD NameIdentifier FunctionparamList OfType? WS* AssignExpression {pin=2}
ValDirective ::= EXPORT_KEYWORD? VAL_KEYWORD NameIdentifier OfType? WS* AssignExpression {pin=2}
VarDirective ::= EXPORT_KEYWORD? VAR_KEYWORD NameIdentifier OfType? WS* AssignExpression {pin=2}
StructDirective ::= EXPORT_KEYWORD? STRUCT_KEYWORD NameIdentifier {pin=2}
AssignExpression ::= '=' WS* Expression {pin=2,fragment=true}
OfType ::= COLON WS* Type WS* {pin=2,recoverUntil=NEXT_ARG_RECOVERY}
FunctionparamList ::= OPEN_PAREN WS* ParameterList? WS* CLOSE_PAREN {pin=1,recoverUntil=CLOSE_PAREN}
ParameterList ::= Parameter NthParameter* {fragment=true}
NthParameter ::= ',' WS* Parameter WS* {pin=1,recoverUntil=NEXT_ARG_RECOVERY}
Parameter ::= NameIdentifier WS* OfType {pin=1,recoverUntil=NEXT_ARG_RECOVERY}
Type ::= WS* NameIdentifier IsPointer* IsArray?
IsPointer ::= '*'
IsArray ::= '[]'
Expression ::= OrExpression WS* (MatchExpression | BinaryExpression)* {simplifyWhenOneChildren=true}
MatchExpression ::= MATCH_KEYWORD WS* MatchBody WS* {pin=1}
BinaryExpression ::= NameIdentifier WS* OrExpression WS* {pin=1}
OrExpression ::= AndExpression (WS+ 'or' WS+ AndExpression)? {simplifyWhenOneChildren=true}
AndExpression ::= EqExpression (WS+ 'and' WS+ EqExpression)? {simplifyWhenOneChildren=true}
EqExpression ::= RelExpression (WS* ('==' | '!=') WS* RelExpression)? {simplifyWhenOneChildren=true}
RelExpression ::= ShiftExpression (WS* ('>=' | '<=' | '>' | '<') WS* ShiftExpression)? {simplifyWhenOneChildren=true}
ShiftExpression ::= AddExpression (WS* ('>>' | '<<' | '>>>') WS* AddExpression)? {simplifyWhenOneChildren=true}
AddExpression ::= MulExpression (WS* ('+' | '-') WS* MulExpression)? {simplifyWhenOneChildren=true}
MulExpression ::= UnaryExpression (WS* ('*' | '/' | '%') WS* UnaryExpression)? {simplifyWhenOneChildren=true}
UnaryExpression ::= NegExpression | UnaryMinus | IfExpression | FunctionCallExpression {simplifyWhenOneChildren=true}
NegExpression ::= '!' OrExpression {pin=1}
UnaryMinus ::= !NumberLiteral '-' OrExpression {pin=2}
RefPointerOperator::= '*' | '&'
RefExpression ::= RefPointerOperator VariableReference
FunctionCallExpression
::= Value WS* (&'(' CallArguments)? {simplifyWhenOneChildren=true}
Value ::= Literal | RefExpression | VariableReference | ParenExpression {fragment=true}
ParenExpression ::= '(' WS* Expression WS* ')' {pin=3,recoverUntil=CLOSE_PAREN}
IfExpression ::= 'if'
/* Pattern matching */
MatchBody ::= '{' WS* MatchElements* '}' {pin=1,recoverUntil=MATCH_RECOVERY}
MatchElements ::= (CaseCondition | CaseLiteral | CaseElse) WS* {fragment=true}
CaseCondition ::= CASE_KEYWORD WS+ NameIdentifier WS+ IF_KEYWORD WS* Expression '->' WS* Expression {pin=5}
CaseLiteral ::= CASE_KEYWORD WS+ Literal WS* '->' WS* Expression {pin=3}
CaseElse ::= ELSE_KEYWORD WS* '->' WS* Expression {pin=3}
/* Function call */
CallArguments ::= OPEN_PAREN Arguments? CLOSE_PAREN {pin=1,recoverUntil=PAREN_RECOVERY}
Arguments ::= WS* Expression WS* NthArgument* {fragment=true}
NthArgument ::= ',' WS* Expression WS* {pin=1,fragment=true,recoverUntil=NEXT_ARG_RECOVERY}
VariableReference ::= NameIdentifier
BooleanLiteral ::= TRUE_KEYWORD | FALSE_KEYWORD
NullLiteral ::= NULL_KEYWORD
NumberLiteral ::= "-"? ("0" | [1-9] [0-9]*) ("." [0-9]+)? (("e" | "E") ( "-" | "+" )? ("0" | [1-9] [0-9]*))? {pin=2}
StringLiteral ::= '"' (!'"' [#x20-#xFFFF])* '"'
Literal ::= ( StringLiteral
| NumberLiteral
| BooleanLiteral
| NullLiteral
) {fragment=true}
NameIdentifier ::= !KEYWORD [A-Za-z_]([A-Za-z0-9_])*
/* Keywords */
KEYWORD ::= TRUE_KEYWORD | FALSE_KEYWORD | NULL_KEYWORD | IF_KEYWORD | ELSE_KEYWORD | CASE_KEYWORD | VAR_KEYWORD | VAL_KEYWORD | FUN_KEYWORD | STRUCT_KEYWORD | EXPORT_KEYWORD | MATCH_KEYWORD | RESERVED_WORDS
FUN_KEYWORD ::= 'fun' WS+
VAL_KEYWORD ::= 'val' WS+
VAR_KEYWORD ::= 'var' WS+
STRUCT_KEYWORD ::= 'struct' WS+
EXPORT_KEYWORD ::= 'export' WS+
RESERVED_WORDS ::= ( 'async' | 'await' | 'defer'
| 'package' | 'declare'
| 'using'
| 'delete'
| 'break' | 'continue'
| 'let' | 'const' | 'void'
| 'class' | 'private' | 'public' | 'protected' | 'extends'
| 'import' | 'from' | 'abstract'
| 'finally' | 'new' | 'native' | 'enum' | 'type'
| 'yield' | 'for' | 'do' | 'while' | 'try'
) WS+
TRUE_KEYWORD ::= 'true' ![A-Za-z0-9_]
FALSE_KEYWORD ::= 'false' ![A-Za-z0-9_]
NULL_KEYWORD ::= 'null' ![A-Za-z0-9_]
IF_KEYWORD ::= 'if' ![A-Za-z0-9_]
ELSE_KEYWORD ::= 'else' ![A-Za-z0-9_]
CASE_KEYWORD ::= 'case' ![A-Za-z0-9_]
MATCH_KEYWORD ::= 'match' ![A-Za-z0-9_]
/* Tokens */
DIRECTIVE_RECOVERY::= &(FUN_KEYWORD | VAL_KEYWORD | VAR_KEYWORD | STRUCT_KEYWORD | EXPORT_KEYWORD | RESERVED_WORDS)
NEXT_ARG_RECOVERY ::= &(',' | ')')
PAREN_RECOVERY ::= &(')')
MATCH_RECOVERY ::= &('}' | 'case' | 'else')
OPEN_PAREN ::= '('
CLOSE_PAREN ::= ')'
COLON ::= ':'
OPEN_DOC_COMMENT ::= '/*'
CLOSE_DOC_COMMENT ::= '*/'
DOC_COMMENT ::= !CLOSE_DOC_COMMENT [#x00-#xFFFF]
Comment ::= '//' (![#x0A#x0D] [#x00-#xFFFF])* EOL
MultiLineComment ::= OPEN_DOC_COMMENT DOC_COMMENT* CLOSE_DOC_COMMENT {pin=1}
WS ::= Comment | MultiLineComment | [#x20#x09#x0A#x0D]+ {fragment=true}
EOL ::= [#x0A#x0D]+|EOF
`;
describe('New lang', () => {
describe('Parse JSON', () => {
let parser: Parser;
it('create parser', () => {
parser = new Parser(Grammars.Custom.RULES, {});
testParseToken(parser, grammar);
});
});
describe('Grammars.Custom parses JSON grammar', function() {
let RULES = Grammars.Custom.getRules(grammar);
console.log('JSON:\n' + inspect(RULES, false, 20, true));
let parser = new Parser(RULES, {});
printBNF(parser);
function test(literals, ...placeholders) {
let result = '';
// interleave the literals with the placeholders
for (let i = 0; i < placeholders.length; i++) {
result += literals[i];
result += placeholders[i];
}
// add the last literal
result += literals[literals.length - 1];
testParseToken(parser, result);
}
test`fun test() = 1`;
test`fun test( a: MBER, b : NumBer) = 1`;
test`export fun test() = 2`;
test`var test: Double = 1`;
test`var test = 1`;
test`export var test = 1`;
test`val test: Number = 1`;
test`val test = 1`;
test`val test = 1 * 1 - 2 / 4 and 1 == 3 or 4 <= 4`;
test`val test = 1`;
test`val test = 1 mul 4`;
test`val floatingNumber: Number = 1.0`;
test`val floatingNumber: Number = 0.0`;
test`export val test = 1`;
test`val test = true`;
test`val test = false`;
test`val test = null`;
test`fun test(): Number = 1`;
test`fun test(): Number = /*asd*/ 1`;
test`fun test(): Number = /**/ 1`;
test`export fun test(a: Number) = 2`;
test`export fun test(a: Number, b: Type) = 2`;
test`val test = 1 + (4 + 1)`;
test`val test = (1 + 4) + 1`;
test`
export var test = 1
var test2 = 1
val test2 = 1
`;
test`
var test = 1
fun getTest() = test
`;
test`var test = 1 fun pointerOfTest() = &test `;
test`var test: Entity* = 1 fun valueOfTest() = *test`;
test`var test: Struct* = 1`;
test`var test: Struct**** = 1`;
test`var test: Struct[] = 1`;
test`var test: Struct*[] = 1`;
test`var test: Int64**[] = 1`;
// test`
// export struct Entity {
// a: Number,
// b: Entity*,
// c: Number*[]
// }
// export var entities: Entity* = 1
// export fun getTest() = test
// `;
test`val test = 1 match {}`;
test`val test = 1 match { else -> 1 }`;
test`
val test = 1 match {
case 2 -> true
else -> false
}
`;
test`val test = 1 match { case 2 -> true else -> false }`;
test`
val test = 1 match {
case 2->true
else->false
}
`;
test`
val test = 1 match {
case 2 -> true
else -> false
}
`;
test`
val test = 1 match {
case x if true -> true
case x if x < 1 and x < 10 -> true
case 2 -> true
else -> false
}
`;
test`val test = 1 match { case x if x < 1 and x < 10 -> true }`;
test`var a = x match { else -> 1 } map 1 * 2`;
test`var a = !x()`;
test`var a = x()`;
testParseTokenFailsafe(parser, `export fun test(a: ) = 2`, null, doc => {
expect(doc.errors[0].token.type).toEqual('SyntaxError');
expect(doc.errors[0].token.text).toEqual(') = 2');
});
testParseTokenFailsafe(parser, `export struct Entity asd val x = 1`, null, doc => {
expect(doc.errors[0].token.type).toEqual('SyntaxError');
expect(doc.errors[0].token.text).toEqual('asd ');
});
testParseTokenFailsafe(parser, `export struct Entity asd`, null, doc => {
expect(doc.errors[0].message).toEqual('Unexpected end of input: \nasd');
});
testParseTokenFailsafe(parser, `struct Entity asd val x = 1`, null, doc => {
expect(doc.errors[0].token.type).toEqual('SyntaxError');
expect(doc.errors[0].token.text).toEqual('asd ');
});
testParseTokenFailsafe(parser, `struct Entity asd`, null, doc => {
expect(doc.errors[0].message).toEqual('Unexpected end of input: \nasd');
});
testParseTokenFailsafe(parser, `export fun test(a: ,b: AType) = 2`, null, doc => {
expect(doc.errors[0].token.type).toEqual('SyntaxError');
expect(doc.errors[0].token.text).toEqual(',b: AType) = 2');
});
testParseTokenFailsafe(parser, `export fun test() = 2 /*`, null, doc => {
expect(doc.errors[0].token.type).toEqual('SyntaxError');
expect(doc.errors[0].token.text).toEqual('');
});
testParseTokenFailsafe(parser, `export fun test(a: 1) = 2`, null, doc => {
expect(doc.errors[0].token.type).toEqual('SyntaxError');
expect(doc.errors[0].message).toEqual('Unexpected input: "1" Expecting: OfType');
expect(doc.errors[0].token.text).toEqual('1');
});
testParseTokenFailsafe(parser, 'export fun () = 1', null, doc => {
expect(doc.errors[0].token.type).toEqual('SyntaxError');
expect(doc.errors[0].token.text).toEqual('() = 1');
});
testParseTokenFailsafe(parser, 'var a = .0', null, doc => {
expect(doc.errors[0].token.type).toEqual('SyntaxError');
expect(doc.errors[0].token.text).toEqual('.0');
});
testParseTokenFailsafe(parser, 'var a = x match { else } map 1', null, doc => {
expect(doc.errors[0].token.type).toEqual('SyntaxError');
expect(doc.errors[0].token.text).toEqual('else } map 1');
});
testParseTokenFailsafe(parser, 'var a = x match { else -> } map 1', null, doc => {
expect(doc.errors[0].token.type).toEqual('SyntaxError');
expect(doc.errors[0].token.text).toEqual('} map 1');
});
testParseTokenFailsafe(parser, 'var a = match', null, doc => {
expect(doc.errors[0].token.type).toEqual('SyntaxError');
expect(doc.errors[0].token.text).toEqual('match');
});
test`val test = 1 map 1 map 2 map 3`;
test`val test = x(1)`;
test`val test = x(1,2)`;
test`val test = (x)(1,2)`;
test`val test = (x())(1,2)`;
test`val test = x( 1 , 2 /* sdgf */)`;
});
}); | the_stack |
import { PkceCodes, AuthorityFactory, CommonAuthorizationCodeRequest, Constants, AuthorizationCodeClient, ProtocolMode, Logger, AuthenticationScheme, AuthorityOptions, ClientConfiguration } from "@azure/msal-common";
import sinon from "sinon";
import { SilentHandler } from "../../src/interaction_handler/SilentHandler";
import { Configuration, buildConfiguration } from "../../src/config/Configuration";
import { TEST_CONFIG, testNavUrl, TEST_URIS, RANDOM_TEST_GUID, TEST_POP_VALUES } from "../utils/StringConstants";
import { InteractionHandler } from "../../src/interaction_handler/InteractionHandler";
import { BrowserAuthError } from "../../src/error/BrowserAuthError";
import { CryptoOps } from "../../src/crypto/CryptoOps";
import { TestStorageManager } from "../cache/TestStorageManager";
import { BrowserCacheManager } from "../../src/cache/BrowserCacheManager";
const DEFAULT_IFRAME_TIMEOUT_MS = 6000;
const testPkceCodes = {
challenge: "TestChallenge",
verifier: "TestVerifier"
} as PkceCodes;
const testNetworkResult = {
testParam: "testValue"
};
const defaultTokenRequest: CommonAuthorizationCodeRequest = {
redirectUri: `${TEST_URIS.DEFAULT_INSTANCE}/`,
code: "thisIsATestCode",
scopes: TEST_CONFIG.DEFAULT_SCOPES,
codeVerifier: TEST_CONFIG.TEST_VERIFIER,
authority: `${Constants.DEFAULT_AUTHORITY}/`,
correlationId: RANDOM_TEST_GUID,
authenticationScheme: AuthenticationScheme.BEARER
};
const networkInterface = {
sendGetRequestAsync<T>(): T {
return {} as T;
},
sendPostRequestAsync<T>(): T {
return {} as T;
},
};
describe("SilentHandler.ts Unit Tests", () => {
let browserStorage: BrowserCacheManager;
let authCodeModule: AuthorizationCodeClient;
let browserRequestLogger: Logger;
beforeEach(() => {
const appConfig: Configuration = {
auth: {
clientId: TEST_CONFIG.MSAL_CLIENT_ID
}
};
const configObj = buildConfiguration(appConfig, true);
const authorityOptions: AuthorityOptions = {
protocolMode: ProtocolMode.AAD,
knownAuthorities: [],
cloudDiscoveryMetadata: "",
authorityMetadata: ""
}
const authorityInstance = AuthorityFactory.createInstance(configObj.auth.authority, networkInterface, browserStorage, authorityOptions);
const authConfig: ClientConfiguration = {
authOptions: {
...configObj.auth,
authority: authorityInstance,
},
systemOptions: {
tokenRenewalOffsetSeconds:
configObj.system.tokenRenewalOffsetSeconds
},
cryptoInterface: {
createNewGuid: (): string => {
return "newGuid";
},
base64Decode: (input: string): string => {
return "testDecodedString";
},
base64Encode: (input: string): string => {
return "testEncodedString";
},
generatePkceCodes: async (): Promise<PkceCodes> => {
return testPkceCodes;
},
getPublicKeyThumbprint: async (): Promise<string> => {
return TEST_POP_VALUES.ENCODED_REQ_CNF;
},
signJwt: async (): Promise<string> => {
return "signedJwt";
},
removeTokenBindingKey: async (): Promise<boolean> => {
return Promise.resolve(true);
},
clearKeystore: async (): Promise<boolean> => {
return Promise.resolve(true);
}
},
networkInterface: {
sendGetRequestAsync: async (): Promise<any> => {
return testNetworkResult;
},
sendPostRequestAsync: async (): Promise<any> => {
return testNetworkResult;
},
},
loggerOptions: {
loggerCallback: (): void => {},
piiLoggingEnabled: true,
},
};
authConfig.storageInterface = new TestStorageManager(TEST_CONFIG.MSAL_CLIENT_ID, authConfig.cryptoInterface!);
authCodeModule = new AuthorizationCodeClient(authConfig);
const browserCrypto = new CryptoOps();
const logger = new Logger(authConfig.loggerOptions!);
browserStorage = new BrowserCacheManager(TEST_CONFIG.MSAL_CLIENT_ID, configObj.cache, browserCrypto, logger);
browserRequestLogger = new Logger(authConfig.loggerOptions!);
});
afterEach(() => {
sinon.restore();
});
describe("Constructor", () => {
it("creates a subclass of InteractionHandler called SilentHandler", () => {
const silentHandler = new SilentHandler(authCodeModule, browserStorage, defaultTokenRequest, browserRequestLogger, DEFAULT_IFRAME_TIMEOUT_MS);
expect(silentHandler instanceof SilentHandler).toBe(true);
expect(silentHandler instanceof InteractionHandler).toBe(true);
});
});
describe("initiateAuthRequest()", () => {
it("throws error if requestUrl is empty", async () => {
const silentHandler = new SilentHandler(authCodeModule, browserStorage, defaultTokenRequest, browserRequestLogger, DEFAULT_IFRAME_TIMEOUT_MS);
await expect(silentHandler.initiateAuthRequest("")).rejects.toMatchObject(BrowserAuthError.createEmptyNavigationUriError());
//@ts-ignore
await expect(silentHandler.initiateAuthRequest(null)).rejects.toMatchObject(BrowserAuthError.createEmptyNavigationUriError());
});
it("Creates a frame asynchronously when created with default timeout", async () => {
const silentHandler = new SilentHandler(authCodeModule, browserStorage, defaultTokenRequest, browserRequestLogger, DEFAULT_IFRAME_TIMEOUT_MS);
const loadFrameSpy = sinon.spy(silentHandler, <any>"loadFrame");
const authFrame = await silentHandler.initiateAuthRequest(testNavUrl);
expect(loadFrameSpy.called).toBe(true);
expect(authFrame instanceof HTMLIFrameElement).toBe(true);
}, DEFAULT_IFRAME_TIMEOUT_MS + 1000);
it("Creates a frame synchronously when created with a timeout of 0", async () => {
const silentHandler = new SilentHandler(authCodeModule, browserStorage, defaultTokenRequest, browserRequestLogger, 0);
const loadFrameSyncSpy = sinon.spy(silentHandler, <any>"loadFrameSync");
const loadFrameSpy = sinon.spy(silentHandler, <any>"loadFrame");
const authFrame = await silentHandler.initiateAuthRequest(testNavUrl);
expect(loadFrameSyncSpy.calledOnce).toBe(true);
expect(loadFrameSpy.called).toBe(false);
expect(authFrame instanceof HTMLIFrameElement).toBe(true);
});
});
describe("monitorIframeForHash", () => {
it("times out", done => {
const iframe = {
contentWindow: {
// @ts-ignore
location: null // example of scenario that would never otherwise resolve
}
};
const silentHandler = new SilentHandler(authCodeModule, browserStorage, defaultTokenRequest, browserRequestLogger, DEFAULT_IFRAME_TIMEOUT_MS);
// @ts-ignore
silentHandler.monitorIframeForHash(iframe, 500)
.catch(() => {
done();
});
});
it("times out when event loop is suspended", done => {
jest.setTimeout(5000);
const iframe = {
contentWindow: {
location: {
href: "http://localhost",
hash: ""
}
}
};
const silentHandler = new SilentHandler(authCodeModule, browserStorage, defaultTokenRequest, browserRequestLogger, DEFAULT_IFRAME_TIMEOUT_MS);
// @ts-ignore
silentHandler.monitorIframeForHash(iframe, 2000)
.catch(() => {
done();
});
setTimeout(() => {
iframe.contentWindow.location = {
href: "http://localhost/#/code=hello",
hash: "#code=hello"
};
}, 1600);
/**
* This code mimics the JS event loop being synchonously paused (e.g. tab suspension) midway through polling the iframe.
* If the event loop is suspended for longer than the configured timeout,
* the polling operation should throw an error for a timeout.
*/
const startPauseDelay = 200;
const pauseDuration = 3000;
setTimeout(() => {
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, pauseDuration);
}, startPauseDelay);
});
it("returns hash", done => {
const iframe = {
contentWindow: {
location: {
href: "http://localhost",
hash: ""
}
}
};
const silentHandler = new SilentHandler(authCodeModule, browserStorage, defaultTokenRequest, browserRequestLogger, DEFAULT_IFRAME_TIMEOUT_MS);
// @ts-ignore
silentHandler.monitorIframeForHash(iframe, 1000)
.then((hash: string) => {
expect(hash).toEqual("#code=hello");
done();
});
setTimeout(() => {
iframe.contentWindow.location = {
href: "http://localhost/#code=hello",
hash: "#code=hello"
};
}, 500);
});
});
}); | the_stack |
import * as assert from 'assert';
import { SaplingParser } from '../../SaplingParser';
import { describe, suite , test, before} from 'mocha';
import { expect } from 'chai';
import * as path from 'path';
// You can import and use all API from the 'vscode' module
// as well as import your extension to test it
// import * as vscode from 'vscode';
// import * as myExtension from '../../extension';
suite('Parser Test Suite', () => {
let parser, tree, file;
// UNPARSED TREE TEST
describe('It initializes correctly', () => {
before( () => {
file = path.join(__dirname, '../../../src/test/test_apps/test_0/index.js');
parser = new SaplingParser(file);
});
test('A new instance of the parser class is an object', () => {
expect(parser).to.be.an('object');
});
test('It initializes with a proper entry file and an undefined tree', () => {
expect(parser.entryFile).to.equal(file);
expect(parser.tree).to.be.undefined;
});
});
// TEST 0: ONE CHILD
describe('It works for simple apps', () => {
before( () => {
file = path.join(__dirname, '../../../src/test/test_apps/test_0/index.js');
parser = new SaplingParser(file);
tree = parser.parse();
});
test('Parsing returns a object tree that is not undefined', () => {
expect(tree).to.be.an('object');
});
test('Parsed tree has a property called name with value index and one child with name App', () => {
expect(tree).to.have.own.property('name').that.is.equal('index');
expect(tree).to.have.own.property('children').that.is.an('array');
expect(tree.children[0]).to.have.own.property('name').that.is.equal('App');
});
});
// TEST 1: NESTED CHILDREN
describe('It works for 2 components', () => {
before(() => {
file = path.join(__dirname, '../../../src/test/test_apps/test_1/index.js');
parser = new SaplingParser(file);
tree = parser.parse();
});
test('Parsed tree has a property called name with value index and one child with name App, which has its own child Main', () => {
expect(tree).to.have.own.property('name').to.equal('index');
expect(tree.children[0].name).to.equal('App');
expect(tree.children[0]).to.have.own.property('children').that.is.an('array');
expect(tree.children[0].children[0]).to.have.own.property('name').to.equal('Main');
});
test('Parsed tree children should equal the child components', () => {
expect(tree.children).to.have.lengthOf(1);
expect(tree.children[0].children).to.have.lengthOf(1);
});
test('Parsed tree depth is accurate', () => {
expect(tree).to.have.own.property('depth').that.is.equal(0);
expect(tree.children[0]).to.have.own.property('depth').that.is.equal(1);
expect(tree.children[0].children[0]).to.have.own.property('depth').that.is.equal(2);
});
});
// TEST 2: THIRD PARTY, REACT ROUTER, DESTRUCTURED IMPORTS
describe('It works for third party / React Router components and destructured imports', () => {
before(() => {
file = path.join(__dirname, '../../../src/test/test_apps/test_2/index.js');
parser = new SaplingParser(file);
tree = parser.parse();
});
test('Should parse destructured and third party imports', () => {
expect(tree.children).to.have.lengthOf(3);
expect(tree.children[0]).to.have.own.property('name').that.is.oneOf(['Switch', 'Route']);
expect(tree.children[1]).to.have.own.property('name').that.is.oneOf(['Switch', 'Route']);
expect(tree.children[2]).to.have.own.property('name').that.is.equal('Tippy');
});
test('reactRouter should be designated as third party and reactRouter', () => {
expect(tree.children[0]).to.have.own.property('thirdParty').to.be.true;
expect(tree.children[1]).to.have.own.property('thirdParty').to.be.true;
expect(tree.children[0]).to.have.own.property('reactRouter').to.be.true;
expect(tree.children[1]).to.have.own.property('reactRouter').to.be.true;
});
test('Tippy should be designated as third party and not reactRouter', () => {
expect(tree.children[2]).to.have.own.property('thirdParty').to.be.true;
expect(tree.children[2]).to.have.own.property('reactRouter').to.be.false;
});
});
// TEST 3: IDENTIFIES REDUX STORE CONNECTION
describe('It identifies a Redux store connection and designates the component as such', () => {
before(() => {
file = path.join(__dirname, '../../../src/test/test_apps/test_3/index.js');
parser = new SaplingParser(file);
tree = parser.parse();
});
test('The reduxConnect properties of the connected component and the unconnected component should be true and false, respectively', () => {
expect(tree.children[1].children[0].name).to.equal('ConnectedContainer');
expect(tree.children[1].children[0]).to.have.own.property('reduxConnect').that.is.true;
expect(tree.children[1].children[1].name).to.equal('UnconnectedContainer');
expect(tree.children[1].children[1]).to.have.own.property('reduxConnect').that.is.false;
});
});
// TEST 4: ALIASED IMPORTS
describe('It works for aliases', () => {
before(() => {
file = path.join(__dirname, '../../../src/test/test_apps/test_4/index.js');
parser = new SaplingParser(file);
tree = parser.parse();
});
test('alias should still give us components', () => {
expect(tree.children).to.have.lengthOf(2);
expect(tree.children[0]).to.have.own.property('name').that.is.equal('Switch');
expect(tree.children[1]).to.have.own.property('name').that.is.equal('Route');
expect(tree.children[0]).to.have.own.property('name').that.is.not.equal('S');
expect(tree.children[1]).to.have.own.property('name').that.is.not.equal('R');
});
});
// TEST 5: MISSING EXTENSIONS AND UNUSED IMPORTS
describe('It works for extension-less imports', () => {
let names, paths, expectedNames, expectedPaths;
before(() => {
file = path.join(__dirname, '../../../src/test/test_apps/test_5/index.js');
parser = new SaplingParser(file);
tree = parser.parse();
names = tree.children.map(child => child.name);
paths = tree.children.map(child => child.filePath);
expectedNames = ['JS', 'JSX', 'TS', 'TSX'];
expectedPaths = [
'../../../src/test/test_apps/test_5/components/JS.js',
'../../../src/test/test_apps/test_5/components/JSX.jsx',
'../../../src/test/test_apps/test_5/components/TS.ts',
'../../../src/test/test_apps/test_5/components/TSX.tsx'
].map( el => path.resolve(__dirname, el));
});
test('Check children match expected children', () => {
expect(tree.children).to.have.lengthOf(4);
for (let i = 0; i < tree.children.length; i++) {
expect(tree.children[i].name).to.equal(expectedNames[i]);
expect(tree.children[i].filePath).to.equal(expectedPaths[i]);
expect(tree.children[i].error).to.equal('');
}
});
test('Imports that are not invoked should not be children', () => {
expect(names).to.not.contain('Switch');
expect(names).to.not.contain('Route');
});
});
// TEST 6: BAD IMPORT OF APP2 FROM APP1 COMPONENT
describe('It works for badly imported children nodes', () => {
before(() => {
file = path.join(__dirname, '../../../src/test/test_apps/test_6/index.js');
parser = new SaplingParser(file);
tree = parser.parse();
});
test('improperly imported child component should exist but show an error', () => {
expect(tree.children[0].children[0]).to.have.own.property('name').that.equals('App2');
expect(tree.children[0].children[0]).to.have.own.property('error').that.does.not.equal('');
});
});
// TEST 7: SYNTAX ERROR IN APP FILE CAUSES PARSER ERROR
describe('It should log an error when the parser encounters a javascript syntax error', () => {
before(() => {
file = path.join(__dirname, '../../../src/test/test_apps/test_7/index.js');
parser = new SaplingParser(file);
tree = parser.parse();
});
test('Should have a nonempty error message on the invalid child and not parse further', () => {
expect(tree.children[0]).to.have.own.property('name').that.equals('App');
expect(tree.children[0]).to.have.own.property('error').that.does.not.equal('');
expect(tree.children[0].children).to.have.lengthOf(0);
});
});
// TEST 8: MULTIPLE PROPS ON ONE COMPONENT
describe('It should properly count repeat components and consolidate and grab their props', () => {
before(() => {
file = path.join(__dirname, '../../../src/test/test_apps/test_8/index.js');
parser = new SaplingParser(file);
tree = parser.parse();
});
test('Grandchild should have a count of 1', () => {
expect(tree.children[0].children[0]).to.have.own.property('count').that.equals(1);
});
test('Grandchild should have the correct three props', () => {
expect(tree.children[0].children[0].props).has.own.property('prop1').that.is.true;
expect(tree.children[0].children[0].props).has.own.property('prop2').that.is.true;
expect(tree.children[0].children[0].props).has.own.property('prop3').that.is.true;
});
});
// TEST 9: FINDING DIFFERENT PROPS ACROSS TWO OR MORE IDENTICAL COMPONENTS
describe('It should properly count repeat components and consolidate and grab their props', () => {
before(() => {
file = path.join(__dirname, '../../../src/test/test_apps/test_9/index.js');
parser = new SaplingParser(file);
tree = parser.parse();
});
test('Grandchild should have a count of 2', () => {
expect(tree.children[0].children[0]).to.have.own.property('count').that.equals(2);
});
test('Grandchild should have the correct two props', () => {
expect(tree.children[0].children[0].props).has.own.property('prop1').that.is.true;
expect(tree.children[0].children[0].props).has.own.property('prop2').that.is.true;
});
});
// TEST 10: CHECK CHILDREN WORKS AND COMPONENTS WORK
describe('It should render children when children are rendered as values of prop called component', () => {
before(() => {
file = path.join(__dirname, '../../../src/test/test_apps/test_10/index.jsx');
parser = new SaplingParser(file);
tree = parser.parse();
});
test('Parent should have children that match the value stored in component prop', () => {
expect(tree.children[0]).to.have.own.property('name').that.is.equal('BrowserRouter');
expect(tree.children[1]).to.have.own.property('name').that.is.equal('App');
expect(tree.children[1].children[3]).to.have.own.property('name').that.is.equal('DrillCreator');
expect(tree.children[1].children[4]).to.have.own.property('name').that.is.equal('HistoryDisplay');
});
});
// TEST 11: PARSER DOESN'T BREAK UPON RECURSIVE COMPONENTS
describe('It should render the second call of mutually recursive components, but no further', () => {
before(() => {
file = path.join(__dirname, '../../../src/test/test_apps/test_11/index.js');
parser = new SaplingParser(file);
tree = parser.parse();
});
test('Tree should not be undefined', () => {
expect(tree).to.not.be.undefined;
});
test('Tree should have an index component while child App1, grandchild App2, great-grandchild App1', () => {
expect(tree).to.have.own.property('name').that.is.equal('index');
expect(tree.children).to.have.lengthOf(1);
expect(tree.children[0]).to.have.own.property('name').that.is.equal('App1');
expect(tree.children[0].children).to.have.lengthOf(1);
expect(tree.children[0].children[0]).to.have.own.property('name').that.is.equal('App2');
expect(tree.children[0].children[0].children).to.have.lengthOf(1);
expect(tree.children[0].children[0].children[0]).to.have.own.property('name').that.is.equal('App1');
expect(tree.children[0].children[0].children[0].children).to.have.lengthOf(0);
});
});
// TEST 12: NEXT.JS APPS
describe('It should parse Next.js applications', () => {
before(() => {
file = path.join(__dirname, '../../../src/test/test_apps/test_12/pages/index.js');
parser = new SaplingParser(file);
tree = parser.parse();
});
test('Root should be named index, children should be named Head, Navbar, and Image, children of Navbar should be named Link and Image', () => {
expect(tree).to.have.own.property('name').that.is.equal('index');
expect(tree.children).to.have.lengthOf(3);
expect(tree.children[0]).to.have.own.property('name').that.is.equal('Head');
expect(tree.children[1]).to.have.own.property('name').that.is.equal('Navbar');
expect(tree.children[2]).to.have.own.property('name').that.is.equal('Image');
expect(tree.children[1].children).to.have.lengthOf(2);
expect(tree.children[1].children[0]).to.have.own.property('name').that.is.equal('Link');
expect(tree.children[1].children[1]).to.have.own.property('name').that.is.equal('Image');
});
});
// TEST 13: Variable Declaration Imports and React.lazy Imports
describe('It should parse VariableDeclaration imports including React.lazy imports', () => {
before(() => {
file = path.join(__dirname, '../../../src/test/test_apps/test_13/index.js');
parser = new SaplingParser(file);
tree = parser.parse();
});
test('Root should be named index, it should have one child named App', () => {
expect(tree).to.have.own.property('name').that.is.equal('index');
expect(tree.children).to.have.lengthOf(1);
expect(tree.children[0]).to.have.own.property('name').that.is.equal('App');
});
test('App should have three children, Page1, Page2 and Page3, all found successfully', () => {
expect(tree.children[0].children[0]).to.have.own.property('name').that.is.equal('Page1');
expect(tree.children[0].children[0]).to.have.own.property('thirdParty').that.is.false;
expect(tree.children[0].children[1]).to.have.own.property('name').that.is.equal('Page2');
expect(tree.children[0].children[1]).to.have.own.property('thirdParty').that.is.false;
expect(tree.children[0].children[2]).to.have.own.property('name').that.is.equal('Page3');
expect(tree.children[0].children[2]).to.have.own.property('thirdParty').that.is.false;
});
});
}); | the_stack |
import { defaultTo, uniq } from "lodash";
import { DateTime } from "luxon";
import isNonNullArray from "coral-common/helpers/isNonNullArray";
import { Config } from "coral-server/config";
import { MongoContext } from "coral-server/data/context";
import {
CannotMergeAnArchivedStory,
CannotOpenAnArchivedStory,
StoryURLInvalidError,
UserNotFoundError,
} from "coral-server/errors";
import { StoryCreatedCoralEvent } from "coral-server/events";
import { CoralEventPublisherBroker } from "coral-server/events/publisher";
import logger from "coral-server/logger";
import {
mergeCommentActionCounts,
mergeManyStoryActions,
removeStoryActions,
removeStoryModerationActions,
} from "coral-server/models/action/comment";
import {
calculateTotalCommentCount,
mergeCommentModerationQueueCount,
mergeCommentStatusCount,
mergeManyCommentStories,
removeStoryComments,
} from "coral-server/models/comment";
import { LiveConfiguration } from "coral-server/models/settings";
import {
addStoryExpert,
closeStory,
createStory,
CreateStoryInput,
findOrCreateStory,
FindOrCreateStoryInput,
findStory,
FindStoryInput,
openStory,
removeStories,
removeStory,
removeStoryExpert,
resolveStoryMode,
retrieveManyStories,
retrieveStory,
retrieveStorySections,
setStoryMode,
Story,
updateStory,
updateStoryCounts,
UpdateStoryInput,
updateStorySettings,
UpdateStorySettingsInput,
} from "coral-server/models/story";
import {
ensureFeatureFlag,
hasFeatureFlag,
Tenant,
} from "coral-server/models/tenant";
import { retrieveUser } from "coral-server/models/user";
import { ScraperQueue } from "coral-server/queue/tasks/scraper";
import { findSiteByURL } from "coral-server/services/sites";
import { scrape } from "coral-server/services/stories/scraper";
import {
GQLFEATURE_FLAG,
GQLSTORY_MODE,
} from "coral-server/graph/schema/__generated__/types";
export type FindStory = FindStoryInput;
export async function find(
mongo: MongoContext,
tenant: Tenant,
input: FindStory
) {
return findStory(mongo, tenant.id, input);
}
export type FindOrCreateStory = FindOrCreateStoryInput;
export async function findOrCreate(
mongo: MongoContext,
tenant: Tenant,
broker: CoralEventPublisherBroker,
input: FindOrCreateStory,
scraper: ScraperQueue,
now = new Date()
) {
// Validate the mode if passed.
if (input.mode) {
validateStoryMode(tenant, input.mode);
}
let siteID = null;
if (input.url) {
const site = await findSiteByURL(mongo, tenant.id, input.url);
// If the URL is provided, and the url is not associated with a site, then refuse
// to create the Asset.
if (!site) {
throw new StoryURLInvalidError({
storyURL: input.url,
tenantDomain: tenant.domain,
});
}
siteID = site.id;
}
const { story, wasUpserted } = await findOrCreateStory(
mongo,
tenant.id,
input,
siteID,
now
);
if (!story) {
return null;
}
if (wasUpserted) {
StoryCreatedCoralEvent.publish(broker, {
storyID: story.id,
storyURL: story.url,
siteID: story.siteID,
}).catch((err) => {
logger.error({ err }, "could not publish story created event");
});
}
if (tenant.stories.scraping.enabled && !story.metadata && !story.scrapedAt) {
// If the scraper has not scraped this story, and we have no metadata, we
// need to scrape it now!
await scraper.add({
storyID: story.id,
storyURL: story.url,
tenantID: tenant.id,
});
}
return story;
}
export async function remove(
mongo: MongoContext,
tenant: Tenant,
storyID: string,
includeComments = false
) {
// Create a logger for this function.
const log = logger.child(
{
storyID,
includeComments,
},
true
);
log.debug("starting to remove story");
// Get the story so we can see if there are associated comments.
const story = await retrieveStory(mongo, tenant.id, storyID);
if (!story) {
// No story was found!
log.warn("attempted to remove story that wasn't found");
return null;
}
if (includeComments) {
// Remove the moderation actions associated with the comments we just removed.
const {
deletedCount: removedModerationActions,
} = await removeStoryModerationActions(mongo, tenant.id, story.id);
log.debug(
{ removedModerationActions },
"removed moderation actions while deleting story"
);
if (mongo.archive) {
const {
deletedCount: removedArchivedModerationActions,
} = await removeStoryModerationActions(mongo, tenant.id, story.id, true);
log.debug(
{ removedArchivedModerationActions },
"removed archived moderation actions while deleting story"
);
}
// Remove the actions associated with the comments we just removed.
const { deletedCount: removedActions } = await removeStoryActions(
mongo,
tenant.id,
story.id
);
log.debug({ removedActions }, "removed actions while deleting story");
if (mongo.archive) {
const { deletedCount: removedArchivedActions } = await removeStoryActions(
mongo,
tenant.id,
story.id,
true
);
log.debug(
{ removedArchivedActions },
"removed archived actions while deleting story"
);
}
// Remove the comments for the story.
const { deletedCount: removedComments } = await removeStoryComments(
mongo,
tenant.id,
story.id
);
log.debug({ removedComments }, "removed comments while deleting story");
if (mongo.archive) {
const {
deletedCount: removedArchivedComments,
} = await removeStoryComments(mongo, tenant.id, story.id, true);
log.debug(
{ removedArchivedComments },
"removed archived comments while deleting story"
);
}
} else if (calculateTotalCommentCount(story.commentCounts.status) > 0) {
log.warn(
"attempted to remove story that has linked comments without consent for deleting comments"
);
throw new Error(
"Failed to delete story. Attempted to remove a story that still has comments. It is preferable that you merge a story or update its Story URL instead of trying to delete it. If you are sure about what you're doing and want to delete this story with its comments. Use the option `includeComments = true`. For more details check the schema suggestions for this mutation input."
);
}
const removedStory = await removeStory(mongo, tenant.id, story.id);
if (!removedStory) {
// Story was already removed.
// TODO: evaluate use of transaction here.
return null;
}
log.debug("removed story");
return removedStory;
}
export type CreateStory = Omit<CreateStoryInput, "siteID">;
export async function create(
mongo: MongoContext,
tenant: Tenant,
broker: CoralEventPublisherBroker,
config: Config,
storyID: string,
storyURL: string,
{ mode, metadata, closedAt }: CreateStory,
now = new Date()
) {
// Validate the mode if passed.
if (mode) {
validateStoryMode(tenant, mode);
}
// Validate the id.
if (!storyID) {
throw new Error("story id is required");
}
if (!storyURL) {
throw new StoryURLInvalidError({ storyURL, tenantDomain: tenant.domain });
}
const site = await findSiteByURL(mongo, tenant.id, storyURL);
if (!site) {
throw new StoryURLInvalidError({ storyURL, tenantDomain: tenant.domain });
}
// Construct the input payload.
const input: CreateStoryInput = { metadata, mode, closedAt, siteID: site.id };
if (metadata) {
input.scrapedAt = now;
}
// Create the story in the database.
let story = await createStory(
mongo,
tenant.id,
storyID,
storyURL,
input,
now
);
if (!metadata && tenant.stories.scraping.enabled) {
// If the scraper has not scraped this story and story metadata was not
// provided, we need to scrape it now!
story = await scrape(mongo, config, tenant.id, story.id, storyURL);
}
StoryCreatedCoralEvent.publish(broker, {
storyID: story.id,
storyURL: story.url,
siteID: site.id,
}).catch((err) => {
logger.error({ err }, "could not publish story created event");
});
return story;
}
export type UpdateStory = UpdateStoryInput;
export async function update(
mongo: MongoContext,
tenant: Tenant,
storyID: string,
input: UpdateStory,
now = new Date()
) {
if (input.url) {
const site = await findSiteByURL(mongo, tenant.id, input.url);
if (!site) {
throw new StoryURLInvalidError({
storyURL: input.url,
tenantDomain: tenant.domain,
});
}
}
return updateStory(mongo, tenant.id, storyID, input, now);
}
function validateStoryMode(tenant: Tenant, mode: GQLSTORY_MODE) {
if (mode === GQLSTORY_MODE.QA) {
ensureFeatureFlag(tenant, GQLFEATURE_FLAG.ENABLE_QA);
} else if (mode === GQLSTORY_MODE.RATINGS_AND_REVIEWS) {
ensureFeatureFlag(tenant, GQLFEATURE_FLAG.ENABLE_RATINGS_AND_REVIEWS);
}
}
export type UpdateStorySettings = UpdateStorySettingsInput;
export async function updateSettings(
mongo: MongoContext,
tenant: Tenant,
storyID: string,
input: UpdateStorySettings,
now = new Date()
) {
// Validate the input mode.
if (input.mode) {
validateStoryMode(tenant, input.mode);
}
return updateStorySettings(mongo, tenant.id, storyID, input, now);
}
export async function open(
mongo: MongoContext,
tenant: Tenant,
storyID: string,
now = new Date()
) {
const story = await retrieveStory(mongo, tenant.id, storyID);
if (story?.isArchived || story?.isArchiving) {
throw new CannotOpenAnArchivedStory(tenant.id, storyID);
}
return openStory(mongo, tenant.id, storyID, now);
}
export async function close(
mongo: MongoContext,
tenant: Tenant,
storyID: string,
now = new Date()
) {
return closeStory(mongo, tenant.id, storyID, now);
}
export async function merge(
mongo: MongoContext,
tenant: Tenant,
destinationID: string,
sourceIDs: string[]
) {
// Create a logger for this operation.
const log = logger.child({ destinationID, sourceIDs }, true);
if (sourceIDs.length === 0) {
log.warn("cannot merge from 0 stories");
return null;
}
// Collect the story id's and check for duplicates.
const storyIDs = [destinationID, ...sourceIDs];
if (uniq(storyIDs).length !== storyIDs.length) {
throw new Error("cannot merge from/to the same story ID");
}
// Get the stories referenced.
const stories = await retrieveManyStories(mongo, tenant.id, storyIDs);
if (!isNonNullArray(stories)) {
throw new Error("cannot find all the stories");
}
// We can only merge stories if they are all on the same site.
if (uniq(stories.map(({ siteID }) => siteID)).length > 1) {
throw new Error("cannot merge stories on different sites");
}
// We can only merge stories with the comments mode so if any of them are not
// comments, then error.
if (
stories.some(
({ settings }) =>
resolveStoryMode(settings, tenant) !== GQLSTORY_MODE.COMMENTS
)
) {
throw new Error("cannot merge stories not in comments mode");
}
// We cannot merge stories that are archived or archiving
const story = stories.find((s) => s.isArchived || s.isArchiving);
if (story) {
throw new CannotMergeAnArchivedStory(tenant.id, story.id);
}
// Move all the comment's from the source stories over to the destination
// story.
const { modifiedCount: updatedComments } = await mergeManyCommentStories(
mongo,
tenant.id,
destinationID,
sourceIDs
);
log.debug({ updatedComments }, "updated comments while merging stories");
// Update all the action's that referenced the old story to reference the new
// story.
const { modifiedCount: updatedActions } = await mergeManyStoryActions(
mongo,
tenant.id,
destinationID,
sourceIDs
);
log.debug({ updatedActions }, "updated actions while merging stories");
// Merge the comment and action counts for all the source stories.
const [, ...sourceStories] = stories;
// Compute the new comment counts from the old stories.
const commentCounts = {
status: mergeCommentStatusCount(
...sourceStories.map((s) => s.commentCounts.status)
),
moderationQueue: mergeCommentModerationQueueCount(
...sourceStories.map((s) => s.commentCounts.moderationQueue)
),
action: mergeCommentActionCounts(
...sourceStories.map((s) => s.commentCounts.action)
),
};
// Update the story that was the destination of the merge.
const destinationStory = await updateStoryCounts(
mongo,
tenant.id,
destinationID,
commentCounts
);
if (!destinationStory) {
log.warn("destination story cannot be updated with new comment counts");
return null;
}
log.debug(
{ commentCounts: destinationStory.commentCounts },
"updated destination story with new comment counts"
);
// Remove the stories from MongoDB.
const { deletedCount } = await removeStories(mongo, tenant.id, sourceIDs);
log.debug({ deletedStories: deletedCount }, "deleted source stories");
// Return the story that had the other stories merged into.
return destinationStory;
}
export async function addExpert(
mongo: MongoContext,
tenant: Tenant,
storyID: string,
userID: string
) {
const user = await retrieveUser(mongo, tenant.id, userID);
if (!user) {
throw new UserNotFoundError(userID);
}
return addStoryExpert(mongo, tenant.id, storyID, userID);
}
export async function removeExpert(
mongo: MongoContext,
tenant: Tenant,
storyID: string,
userID: string
) {
const user = await retrieveUser(mongo, tenant.id, userID);
if (!user) {
throw new UserNotFoundError(userID);
}
return removeStoryExpert(mongo, tenant.id, storyID, userID);
}
export async function updateStoryMode(
mongo: MongoContext,
tenant: Tenant,
storyID: string,
mode: GQLSTORY_MODE
) {
// Validate the mode.
validateStoryMode(tenant, mode);
return setStoryMode(mongo, tenant.id, storyID, mode);
}
export async function retrieveSections(mongo: MongoContext, tenant: Tenant) {
if (!hasFeatureFlag(tenant, GQLFEATURE_FLAG.SECTIONS)) {
return null;
}
return retrieveStorySections(mongo, tenant.id);
}
type LiveEnabledSource = Story | LiveConfiguration;
function sourceIsStory(source: LiveEnabledSource): source is Story {
// All stories have an ID and a Tenant ID, if it has this it's a Story!
if ((source as Story).id && (source as Story).tenantID) {
return true;
}
return false;
}
export async function isLiveEnabled(
config: Config,
tenant: Tenant,
source: LiveEnabledSource,
now: Date
) {
if (config.get("disable_live_updates")) {
return false;
}
if (tenant.featureFlags?.includes(GQLFEATURE_FLAG.DISABLE_LIVE_UPDATES)) {
return false;
}
let settings: Partial<LiveConfiguration>;
if (sourceIsStory(source)) {
const timeout = config.get("disable_live_updates_timeout");
if (timeout > 0) {
// If one of these is available, use it to determine the time since the
// last comment.
const lastCommentedAt = source.lastCommentedAt || source.createdAt;
// If this date is before the timeout...
if (
DateTime.fromJSDate(lastCommentedAt)
.plus({
milliseconds: timeout,
})
.toJSDate() <= now
) {
// Then we know that the last comment (or lack there of) was left more
// than the timeout specified in configuration.
return false;
}
}
// If the live settings aren't set on the Story, then default to the
// organization setting.
if (!source.settings.live) {
return tenant.live.enabled;
}
// Live settings are available, set them on the settings object.
settings = source.settings.live;
} else {
// The source wasn't a story, but settings!
settings = source;
}
// If the settings don't have the setting property enabled, then use the
// tenant settings.
return defaultTo(settings.enabled, tenant.live.enabled);
} | the_stack |
interface JQuery {
form: SemanticUI.Form;
}
declare namespace SemanticUI {
interface Form {
settings: FormSettings;
/**
* Submits selected form
*/
(behavior: 'submit'): JQuery;
/**
* Returns true/false whether a form passes its validation rules
*/
(behavior: 'is valid'): boolean;
/**
* Returns true/false whether a field passes its validation rules
*/
(behavior: 'is valid', field: string): boolean;
/**
* Adds rule to existing rules for field
* @since 2.2.11
*/
(behavior: 'add rule', field: string, rules: string | string[] | Form.Rules): JQuery;
/**
* Adds rule to existing rules for field
* @since 2.2.11
*/
(behavior: 'add field', field: string, rules: string | string[] | Form.Rules): JQuery;
/**
* Adds fields object to existing fields
* @since 2.2.11
*/
(behavior: 'add fields', fields: Form.Fields): JQuery;
/**
* Removes specific rule from field leaving other rules
* @since 2.2.11
*/
(behavior: 'remove rule', field: string, rule: Form.Rule): JQuery;
/**
* Remove all validation for a field
* @since 2.2.11
*/
(behavior: 'remove field', field: string): JQuery;
/**
* @since 2.2.11
*/
(behavior: 'remove rules', fields: string | string[], rules: Form.Rule[]): JQuery;
/**
* @since 2.2.11
*/
(behavior: 'remove fields', fields: string[]): JQuery;
/**
* Adds error prompt to the field with the given identifier
*/
(behavior: 'add prompt', identifier: string, errors: string | string[]): JQuery;
/**
* Validates form and calls onSuccess or onFailure
*/
(behavior: 'validate form'): JQuery;
/**
* gets browser property change event
*/
(behavior: 'get change event'): string;
/**
* Returns element with matching name, id, or data-validate metadata to ID
*/
(behavior: 'get field', id: string): JQuery;
/**
* Returns value of element with id
*/
(behavior: 'get value', id: string): any;
/**
* Returns object of element values that match array of ids. If no IDS are passed will return all fields
*/
(behavior: 'get values', ids?: string[]): any;
/**
* Sets value of element with id
*/
(behavior: 'set value', id: string): JQuery;
/**
* Sets key/value pairs from passed values object to matching ids
*/
(behavior: 'set values', values: any): JQuery;
/**
* Returns validation rules for a given jQuery-referenced input field
*/
(behavior: 'get validation', element: JQuery): any;
/**
* Returns whether a field exists
*/
(behavior: 'has field', identifier: string): boolean;
/**
* Adds errors to form, given an array errors
*/
(behavior: 'add errors', errors: string[]): JQuery;
(behavior: 'destroy'): JQuery;
<K extends keyof FormSettings>(behavior: 'setting', name: K, value?: undefined): FormSettings._Impl[K];
<K extends keyof FormSettings>(behavior: 'setting', name: K, value: FormSettings._Impl[K]): JQuery;
(behavior: 'setting', value: FormSettings): JQuery;
(settings?: FormSettings | Form.Fields): JQuery;
}
/**
* @see {@link http://semantic-ui.com/behaviors/form.html#/settings}
*/
type FormSettings = FormSettings.Param;
namespace FormSettings {
type Param = (Pick<_Impl, 'keyboardShortcuts'> |
Pick<_Impl, 'on'> |
Pick<_Impl, 'revalidate'> |
Pick<_Impl, 'delay'> |
Pick<_Impl, 'inline'> |
Pick<_Impl, 'transition'> |
Pick<_Impl, 'duration'> |
Pick<_Impl, 'fields'> |
Pick<_Impl, 'text'> |
Pick<_Impl, 'prompt'> |
Pick<_Impl, 'onValid'> |
Pick<_Impl, 'onInvalid'> |
Pick<_Impl, 'onSuccess'> |
Pick<_Impl, 'onFailure'> |
Pick<_Impl, 'templates'> |
Pick<_Impl, 'rules'> |
Pick<_Impl, 'selector'> |
Pick<_Impl, 'metadata'> |
Pick<_Impl, 'className'> |
Pick<_Impl, 'error'> |
Pick<_Impl, 'namespace'> |
Pick<_Impl, 'name'> |
Pick<_Impl, 'silent'> |
Pick<_Impl, 'debug'> |
Pick<_Impl, 'performance'> |
Pick<_Impl, 'verbose'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
defaults: {
[name: string]: Form.Field;
};
// region Form Settings
/**
* Adds keyboard shortcuts for enter and escape keys to submit form and blur fields respectively
*
* @default true
*/
keyboardShortcuts: boolean;
/**
* Event used to trigger validation. Can be either submit, blur or change.
*
* @default 'submit'
*/
on: 'submit' | 'blur' | 'change';
/**
* If set to true will revalidate fields with errors on input change
*
* @default true
*/
revalidate: boolean;
/**
* Delay from last typed letter to validate a field when using on: change or when revalidating a field.
*
* @default true
*/
delay: boolean;
/**
* Adds inline error on field validation error
*
* @default false
*/
inline: boolean;
/**
* Named transition to use when animating validation errors. Fade and slide down are available without including ui transitions
*
* @default 'scale'
* @see {@link http://semantic-ui.com/modules/transition.html}
*/
transition: string;
/**
* Animation speed for inline prompt
*
* @default 150
*/
duration: number;
fields: {
[name: string]: string | string[] | Form.Field;
};
// endregion
// region Form Prompts
text: Form.TextSettings;
prompt: Form.PromptSettings;
// endregion
// region Callbacks
/**
* Callback on each valid field
*/
onValid(this: JQuery): void;
/**
* Callback on each invalid field
*/
onInvalid(this: JQuery): void;
/**
* Callback if a form is all valid
*/
onSuccess(this: JQuery, event: JQuery.TriggeredEvent<HTMLElement>, fields: any): void;
/**
* Callback if any form field is invalid
*/
onFailure(this: JQuery, formErrors: string[], fields: any): void;
// endregion
// region Templates
templates: Form.TemplatesSettings;
// endregion
// region Rules
rules: {
[name: string]: (this: HTMLElement, ...args: any[]) => boolean;
};
// endregion
// region DOM Settings
/**
* Selectors used to match functionality to DOM
*/
selector: Form.SelectorSettings;
/**
* HTML5 metadata attributes
*/
metadata: Form.MetadataSettings;
/**
* Class names used to attach style to state
*/
className: Form.ClassNameSettings;
// endregion
// region Debug Settings
error: Form.ErrorSettings;
// endregion
// region Component Settings
// region DOM Settings
/**
* Event namespace. Makes sure module teardown does not effect other events attached to an element.
*/
namespace: string;
// endregion
// region Debug Settings
/**
* Name used in log statements
*/
name: string;
/**
* Silences all console output including error messages, regardless of other debug settings.
*/
silent: boolean;
/**
* Debug output to console
*/
debug: boolean;
/**
* Show console.table output with performance metrics
*/
performance: boolean;
/**
* Debug output includes all internal behaviors
*/
verbose: boolean;
// endregion
// endregion
}
}
namespace Form {
interface Field {
identifier: string;
optional?: boolean;
rules: Rule[];
}
interface Rule {
type: string;
prompt: string;
}
interface Fields {
[name: string]: string | string[];
}
interface Rules {
rules: Rule[];
}
type TextSettings = TextSettings.Param;
namespace TextSettings {
type Param = (Pick<_Impl, 'unspecifiedRule'> |
Pick<_Impl, 'unspecifiedField'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default 'Please enter a valid value'
*/
unspecifiedRule: string;
/**
* @default 'This field'
*/
unspecifiedField: string;
}
}
type PromptSettings = PromptSettings.Param;
namespace PromptSettings {
type Param = (Pick<_Impl, 'empty'> |
Pick<_Impl, 'checked'> |
Pick<_Impl, 'email'> |
Pick<_Impl, 'url'> |
Pick<_Impl, 'regExp'> |
Pick<_Impl, 'integer'> |
Pick<_Impl, 'decimal'> |
Pick<_Impl, 'number'> |
Pick<_Impl, 'is'> |
Pick<_Impl, 'isExactly'> |
Pick<_Impl, 'not'> |
Pick<_Impl, 'notExactly'> |
Pick<_Impl, 'contain'> |
Pick<_Impl, 'containExactly'> |
Pick<_Impl, 'doesntContain'> |
Pick<_Impl, 'doesntContainExactly'> |
Pick<_Impl, 'minLength'> |
Pick<_Impl, 'length'> |
Pick<_Impl, 'exactLength'> |
Pick<_Impl, 'maxLength'> |
Pick<_Impl, 'match'> |
Pick<_Impl, 'different'> |
Pick<_Impl, 'creditCard'> |
Pick<_Impl, 'minCount'> |
Pick<_Impl, 'exactCount'> |
Pick<_Impl, 'maxCount'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default '{name} must have a value'
*/
empty: string;
/**
* @default '{name} must be checked'
*/
checked: string;
/**
* @default '{name} must be a valid e-mail'
*/
email: string;
/**
* @default '{name} must be a valid url'
*/
url: string;
/**
* @default '{name} is not formatted correctly'
*/
regExp: string;
/**
* @default '{name} must be an integer'
*/
integer: string;
/**
* @default '{name} must be a decimal number'
*/
decimal: string;
/**
* @default '{name} must be set to a number'
*/
number: string;
/**
* @default '{name} must be \'{ruleValue}\''
*/
is: string;
/**
* @default '{name} must be exactly \'{ruleValue}\''
*/
isExactly: string;
/**
* @default '{name} cannot be set to \'{ruleValue}\''
*/
not: string;
/**
* @default '{name} cannot be set to exactly \'{ruleValue}\''
*/
notExactly: string;
/**
* @default '{name} cannot contain \'{ruleValue}\''
*/
contain: string;
/**
* @default '{name} cannot contain exactly \'{ruleValue}\''
*/
containExactly: string;
/**
* @default '{name} must contain \'{ruleValue}\''
*/
doesntContain: string;
/**
* @default '{name} must contain exactly \'{ruleValue}\''
*/
doesntContainExactly: string;
/**
* @default '{name} must be at least {ruleValue} characters'
*/
minLength: string;
/**
* @default '{name} must be at least {ruleValue} characters'
*/
length: string;
/**
* @default '{name} must be exactly {ruleValue} characters'
*/
exactLength: string;
/**
* @default '{name} cannot be longer than {ruleValue} characters'
*/
maxLength: string;
/**
* @default '{name} must match {ruleValue} field'
*/
match: string;
/**
* @default '{name} must have a different value than {ruleValue} field'
*/
different: string;
/**
* @default '{name} must be a valid credit card number'
*/
creditCard: string;
/**
* @default '{name} must have at least {ruleValue} choices'
*/
minCount: string;
/**
* @default '{name} must have exactly {ruleValue} choices'
*/
exactCount: string;
/**
* @default '{name} must have {ruleValue} or less choices'
*/
maxCount: string;
}
}
type TemplatesSettings = TemplatesSettings.Param;
namespace TemplatesSettings {
type Param = (Pick<_Impl, 'error'> |
Pick<_Impl, 'prompt'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
error(errors: string[]): JQuery;
prompt(errors: string[]): JQuery;
}
}
type SelectorSettings = SelectorSettings.Param;
namespace SelectorSettings {
type Param = (Pick<_Impl, 'message'> |
Pick<_Impl, 'field'> |
Pick<_Impl, 'group'> |
Pick<_Impl, 'input'> |
Pick<_Impl, 'prompt'> |
Pick<_Impl, 'submit'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default '.error.message'
*/
message: string;
/**
* @default 'input, textarea, select'
*/
field: string;
/**
* @default '.field'
*/
group: string;
/**
* @default 'input'
*/
input: string;
/**
* @default '.prompt'
*/
prompt: string;
/**
* @default '.submit'
*/
submit: string;
}
}
type MetadataSettings = MetadataSettings.Param;
namespace MetadataSettings {
type Param = (Pick<_Impl, 'validate'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default 'validate'
*/
validate: string;
}
}
type ClassNameSettings = ClassNameSettings.Param;
namespace ClassNameSettings {
type Param = (Pick<_Impl, 'active'> |
Pick<_Impl, 'placeholder'> |
Pick<_Impl, 'disabled'> |
Pick<_Impl, 'visible'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default 'active'
*/
active: string;
/**
* @default 'default'
*/
placeholder: string;
/**
* @default 'disabled'
*/
disabled: string;
/**
* @default 'visible'
*/
visible: string;
}
}
type ErrorSettings = ErrorSettings.Param;
namespace ErrorSettings {
type Param = (Pick<_Impl, 'method'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default 'The method you called is not defined.'
*/
method: string;
}
}
}
} | the_stack |
import { createElement, isNullOrUndefined, classList } from '@syncfusion/ej2-base';
import { TextBox, NumericTextBox } from '@syncfusion/ej2-inputs';
import { Button } from '@syncfusion/ej2-buttons';
import { Popup } from '@syncfusion/ej2-popups';
import { FieldElementBox, TextFormField, FormField, DropDownFormField, CheckBoxFormField } from '../viewer/page';
import { Point } from '../editor/editor-helper';
import { DateTimePicker, ChangedEventArgs } from '@syncfusion/ej2-calendars';
import { DocumentEditor } from '../../document-editor';
import { DropDownList } from '@syncfusion/ej2-dropdowns';
import { TextFormFieldType } from '../../base/types';
import { afterFormFieldFillEvent, FormFieldFillEventArgs } from '../../base/index';
/**
* @private
*/
export class FormFieldPopUp {
private target: HTMLElement;
private textBoxContainer: HTMLElement;
private textBoxInput: HTMLInputElement;
private numberInput: HTMLInputElement;
private dateInput: HTMLInputElement;
private dropDownInput: HTMLInputElement;
private numbericInput: HTMLElement;
private popupObject: Popup;
private owner: DocumentEditor;
private formField: FieldElementBox;
private textBoxInstance: TextBox;
private numericTextBoxInstance: NumericTextBox;
private datePickerInstance: DateTimePicker;
private ddlInstance: DropDownList;
private dataPickerOkButton: Button;
/**
* @param {DocumentEditor} owner - Specifies the document editor.
* @private
*/
public constructor(owner: DocumentEditor) {
this.owner = owner;
}
private initPopup(): void {
const popupElement: HTMLElement = createElement('div', { className: 'e-de-form-popup' });
this.textBoxContainer = this.initTextBoxInput();
popupElement.appendChild(this.textBoxContainer);
popupElement.appendChild(this.initNumericTextBox());
popupElement.appendChild(this.initDatePicker());
popupElement.appendChild(this.initDropDownList());
this.target = popupElement;
this.owner.documentHelper.viewerContainer.appendChild(popupElement);
}
private initTextBoxInput(): HTMLElement {
const textBoxDiv: HTMLElement = createElement('div', { className: 'e-de-txt-field' });
const textBoxInput: HTMLInputElement = createElement('input', { className: 'e-de-txt-form' }) as HTMLInputElement;
const textBox: TextBox = new TextBox();
this.textBoxInput = textBoxInput;
const textBoxButtonDiv: HTMLElement = createElement('div', { className: 'e-de-cmt-action-button' });
const textBoxOkButton: HTMLButtonElement = createElement('button') as HTMLButtonElement;
const textBoxCancelButton: HTMLButtonElement = createElement('button') as HTMLButtonElement;
textBoxOkButton.addEventListener('click', this.applyTextFormFieldValue);
textBoxCancelButton.addEventListener('click', this.closeButton);
textBoxDiv.appendChild(textBoxInput);
textBoxButtonDiv.appendChild(textBoxOkButton);
textBoxButtonDiv.appendChild(textBoxCancelButton);
textBoxDiv.appendChild(textBoxButtonDiv);
textBox.appendTo(textBoxInput);
new Button({ cssClass: 'e-de-save e-primary', iconCss: 'e-de-save-icon' }, textBoxOkButton);
new Button({ cssClass: 'e-de-cancel', iconCss: 'e-de-cancel-icon' }, textBoxCancelButton);
this.textBoxInstance = textBox;
return textBoxDiv;
}
private initNumericTextBox(): HTMLElement {
const numericDiv: HTMLElement = createElement('div', { className: 'e-de-num-field' });
const numberInput: HTMLInputElement = createElement('input', { className: 'e-de-txt-form' }) as HTMLInputElement;
const numericTextBox: NumericTextBox = new NumericTextBox();
this.numberInput = numberInput;
const textBoxButtonDiv: HTMLElement = createElement('div', { className: 'e-de-cmt-action-button' });
const textBoxOkButton: HTMLButtonElement = createElement('button') as HTMLButtonElement;
const textBoxCancelButton: HTMLButtonElement = createElement('button') as HTMLButtonElement;
textBoxOkButton.addEventListener('click', this.applyNumberFormFieldValue);
textBoxCancelButton.addEventListener('click', this.closeButton);
numericDiv.appendChild(numberInput);
textBoxButtonDiv.appendChild(textBoxOkButton);
textBoxButtonDiv.appendChild(textBoxCancelButton);
numericDiv.appendChild(textBoxButtonDiv);
numericTextBox.appendTo(numberInput);
new Button({ cssClass: 'e-de-save e-primary', iconCss: 'e-de-save-icon' }, textBoxOkButton);
new Button({ cssClass: 'e-de-cancel', iconCss: 'e-de-cancel-icon' }, textBoxCancelButton);
this.numericTextBoxInstance = numericTextBox;
return numericDiv;
}
private initDatePicker(): HTMLElement {
const dateDiv: HTMLElement = createElement('div', { className: 'e-de-date-field' });
const dateInput: HTMLInputElement = createElement('input', { className: 'e-de-txt-form' }) as HTMLInputElement;
/* eslint-disable-next-line max-len */
const datePicker: DateTimePicker = new DateTimePicker({ allowEdit: false, strictMode: true, change: this.enableDisableDatePickerOkButton });
this.dateInput = dateInput;
const textBoxButtonDiv: HTMLElement = createElement('div', { className: 'e-de-cmt-action-button' });
const textBoxOkButton: HTMLButtonElement = createElement('button') as HTMLButtonElement;
const textBoxCancelButton: HTMLButtonElement = createElement('button') as HTMLButtonElement;
textBoxOkButton.addEventListener('click', this.applyDateFormFieldValue);
textBoxCancelButton.addEventListener('click', this.closeButton);
dateDiv.appendChild(dateInput);
textBoxButtonDiv.appendChild(textBoxOkButton);
textBoxButtonDiv.appendChild(textBoxCancelButton);
dateDiv.appendChild(textBoxButtonDiv);
datePicker.appendTo(dateInput);
this.dataPickerOkButton = new Button({ cssClass: 'e-de-save e-primary', iconCss: 'e-de-save-icon' }, textBoxOkButton);
new Button({ cssClass: 'e-de-cancel', iconCss: 'e-de-cancel-icon' }, textBoxCancelButton);
this.datePickerInstance = datePicker;
return dateDiv;
}
private initDropDownList(): HTMLElement {
const dropDownDiv: HTMLElement = createElement('div', { className: 'e-de-ddl-field' });
const dropDownInput: HTMLInputElement = createElement('input', { className: 'e-de-txt-form' }) as HTMLInputElement;
const ddl: DropDownList = new DropDownList();
this.dropDownInput = dropDownInput;
const textBoxButtonDiv: HTMLElement = createElement('div', { className: 'e-de-cmt-action-button' });
const textBoxOkButton: HTMLButtonElement = createElement('button') as HTMLButtonElement;
const textBoxCancelButton: HTMLButtonElement = createElement('button') as HTMLButtonElement;
textBoxOkButton.addEventListener('click', this.applyDropDownFormFieldValue);
textBoxCancelButton.addEventListener('click', this.closeButton);
dropDownDiv.appendChild(dropDownInput);
textBoxButtonDiv.appendChild(textBoxOkButton);
textBoxButtonDiv.appendChild(textBoxCancelButton);
dropDownDiv.appendChild(textBoxButtonDiv);
ddl.appendTo(dropDownInput);
new Button({ cssClass: 'e-de-save e-primary', iconCss: 'e-de-save-icon' }, textBoxOkButton);
new Button({ cssClass: 'e-de-cancel', iconCss: 'e-de-cancel-icon' }, textBoxCancelButton);
this.ddlInstance = ddl;
return dropDownDiv;
}
/**
* @returns {void}
*/
private applyTextFormFieldValue = (): void => {
this.owner.editor.updateFormField(this.formField, this.textBoxInstance.value);
this.owner.trigger(afterFormFieldFillEvent, { 'fieldName': this.formField.formFieldData.name, value: this.formField.resultText, isCanceled: false });
this.hidePopup();
};
/**
* @returns {void}
*/
private applyNumberFormFieldValue = (): void => {
this.owner.editor.updateFormField(this.formField, this.numberInput.value.toString());
this.owner.trigger(afterFormFieldFillEvent, { 'fieldName': this.formField.formFieldData.name, value: this.formField.resultText, isCanceled: false });
this.hidePopup();
};
/**
* @returns {void}
*/
private applyDateFormFieldValue = (): void => {
if (!isNullOrUndefined(this.datePickerInstance.value)) {
this.owner.editor.updateFormField(this.formField, this.dateInput.value);
this.owner.trigger(afterFormFieldFillEvent, { 'fieldName': this.formField.formFieldData.name, value: this.formField.resultText, isCanceled: false });
this.hidePopup();
}
};
/**
* @returns {void}
*/
private applyDropDownFormFieldValue = (): void => {
this.owner.editor.updateFormField(this.formField, this.ddlInstance.index);
this.owner.trigger(afterFormFieldFillEvent, { 'fieldName': this.formField.formFieldData.name, value: (this.formField.formFieldData as DropDownFormField).selectedIndex, isCanceled: false });
this.hidePopup();
};
/**
* @param {ChangedEventArgs} args - Specifies the event args.
* @returns {void}
*/
private enableDisableDatePickerOkButton = (args: ChangedEventArgs): void => {
if (args.isInteracted) {
this.dataPickerOkButton.disabled = false;
}
};
/**
* @private
* @param {FieldElementBox} formField - Specifies the field element.
* @returns {void}
*/
public showPopUp(formField: FieldElementBox): void {
if (formField) {
this.formField = formField;
this.owner.selection.selectField();
if (isNullOrUndefined(this.target)) {
this.initPopup();
}
classList(this.target, [], ['e-de-txt-form', 'e-de-num-form', 'e-de-date-form', 'e-de-ddl-form']);
const formFieldData: FormField = formField.formFieldData;
if (formFieldData) {
if (formFieldData instanceof TextFormField) {
let resultText: string = formField.resultText;
const rex: RegExp = new RegExp(this.owner.documentHelper.textHelper.getEnSpaceCharacter(), 'gi');
if (resultText.replace(rex, '') === '') {
resultText = '';
}
const maxLength: number = formFieldData.maxLength;
const formFieldType: TextFormFieldType = formFieldData.type;
let inputElement: HTMLInputElement;
resultText = resultText ? resultText : '';
if (formFieldType === 'Text') {
classList(this.target, ['e-de-txt-form'], []);
inputElement = this.textBoxInput;
this.textBoxInstance.value = resultText;
} else if (formFieldData.type === 'Number') {
classList(this.target, ['e-de-num-form'], []);
inputElement = this.numberInput;
this.numericTextBoxInstance.format = formFieldData.format;
this.numericTextBoxInstance.value = parseFloat(resultText.replace(/,/gi, ''));
} else if (formFieldType === 'Date') {
classList(this.target, ['e-de-date-form'], []);
inputElement = this.dateInput;
let format: string = formFieldData.format;
if (format.indexOf('am/pm') !== -1) {
format = format.replace(/am\/pm/gi, 'a');
}
this.datePickerInstance.format = format;
this.datePickerInstance.value = new Date(resultText);
this.dataPickerOkButton.disabled = true;
}
if (inputElement) {
if (maxLength > 0) {
inputElement.maxLength = maxLength;
} else {
inputElement.removeAttribute('maxlength');
}
setTimeout(() => {
inputElement.focus();
});
}
} else if (formFieldData instanceof DropDownFormField) {
classList(this.target, ['e-de-ddl-form'], []);
this.ddlInstance.dataSource = formFieldData.dropdownItems;
this.ddlInstance.index = formFieldData.selectedIndex;
setTimeout(() => {
this.ddlInstance.showPopup();
});
}
const left: number = this.owner.selection.getLeftInternal(formField.line, formField, 0);
const lineHeight: number = formField.line.height * this.owner.documentHelper.zoomFactor;
const position: Point = this.owner.selection.getTooltipPosition(formField.line, left, this.target, true);
if (!this.popupObject) {
this.popupObject = new Popup(this.target, {
height: 'auto',
width: 'auto',
relateTo: this.owner.documentHelper.viewerContainer.parentElement,
position: { X: position.x, Y: position.y + lineHeight }
});
}
this.target.style.display = 'block';
this.popupObject.show();
}
this.owner.documentHelper.isFormFilling = true;
}
}
/**
* @private
* @returns {void}
*/
private closeButton = (): void => {
const field: FieldElementBox = this.formField;
this.hidePopup();
const eventArgs: FormFieldFillEventArgs = { 'fieldName': field.formFieldData.name };
if (field.formFieldData instanceof TextFormField) {
eventArgs.value = field.resultText;
} else if (field.formFieldData instanceof CheckBoxFormField) {
eventArgs.value = field.formFieldData.checked;
} else {
eventArgs.value = (field.formFieldData as DropDownFormField).selectedIndex;
}
eventArgs.isCanceled = true;
this.owner.trigger(afterFormFieldFillEvent, eventArgs);
};
/**
* @private
* @returns {void}
*/
public hidePopup = (): void => {
this.owner.documentHelper.isFormFilling = false;
this.formField = undefined;
if (this.target) {
this.target.style.display = 'none';
}
if (this.popupObject) {
this.popupObject.hide();
this.popupObject.destroy();
this.popupObject = undefined;
}
};
} | the_stack |
module RtmpJs.MP4 {
function hex(s: string): Uint8Array {
var len = s.length >> 1;
var arr = new Uint8Array(len);
for (var i = 0; i < len; i++) {
arr[i] = parseInt(s.substr(i * 2, 2), 16);
}
return arr;
}
var SOUNDRATES = [5500, 11025, 22050, 44100];
var SOUNDFORMATS = ['PCM', 'ADPCM', 'MP3', 'PCM le', 'Nellymouser16', 'Nellymouser8', 'Nellymouser', 'G.711 A-law', 'G.711 mu-law', null, 'AAC', 'Speex', 'MP3 8khz'];
var MP3_SOUND_CODEC_ID = 2;
var AAC_SOUND_CODEC_ID = 10;
enum AudioPacketType {
HEADER = 0,
RAW = 1,
}
interface AudioPacket {
codecDescription: string;
codecId: number;
data: Uint8Array;
rate: number;
size: number;
channels: number;
samples: number;
packetType: AudioPacketType;
}
function parseAudiodata(data: Uint8Array): AudioPacket {
var i = 0;
var packetType = AudioPacketType.RAW;
var flags = data[i];
var codecId = flags >> 4;
var soundRateId = (flags >> 2) & 3;
var sampleSize = flags & 2 ? 16 : 8;
var channels = flags & 1 ? 2 : 1;
var samples: number;
i++;
switch (codecId) {
case AAC_SOUND_CODEC_ID:
var type = data[i++];
packetType = <AudioPacketType>type;
samples = 1024; // AAC implementations typically represent 1024 PCM audio samples
break;
case MP3_SOUND_CODEC_ID:
var version = (data[i + 1] >> 3) & 3; // 3 - MPEG 1
var layer = (data[i + 1] >> 1) & 3; // 3 - Layer I, 2 - II, 1 - III
samples = layer === 1 ? (version === 3 ? 1152 : 576) :
(layer === 3 ? 384 : 1152);
break;
}
return {
codecDescription: SOUNDFORMATS[codecId],
codecId: codecId,
data: data.subarray(i),
rate: SOUNDRATES[soundRateId],
size: sampleSize,
channels: channels,
samples: samples,
packetType: packetType
};
}
var VIDEOCODECS = [null, 'JPEG', 'Sorenson', 'Screen', 'VP6', 'VP6 alpha', 'Screen2', 'AVC'];
var VP6_VIDEO_CODEC_ID = 4;
var AVC_VIDEO_CODEC_ID = 7;
enum VideoFrameType {
KEY = 1,
INNER = 2,
DISPOSABLE = 3,
GENERATED = 4,
INFO = 5,
}
enum VideoPacketType {
HEADER = 0,
NALU = 1,
END = 2,
}
interface VideoPacket {
frameType: VideoFrameType;
codecId: number;
codecDescription: string;
data: Uint8Array;
packetType: VideoPacketType;
compositionTime: number;
horizontalOffset?: number;
verticalOffset?: number;
}
function parseVideodata(data: Uint8Array): VideoPacket {
var i = 0;
var frameType = data[i] >> 4;
var codecId = data[i] & 15;
i++;
var result: any = {
frameType: <VideoFrameType>frameType,
codecId: codecId,
codecDescription: VIDEOCODECS[codecId]
};
switch (codecId) {
case AVC_VIDEO_CODEC_ID:
var type = data[i++];
result.packetType = <VideoPacketType>type;
result.compositionTime = ((data[i] << 24) | (data[i + 1] << 16) | (data[i + 2] << 8)) >> 8;
i += 3;
break;
case VP6_VIDEO_CODEC_ID:
result.packetType = VideoPacketType.NALU;
result.horizontalOffset = (data[i] >> 4) & 15;
result.verticalOffset = data[i] & 15;
result.compositionTime = 0;
i++;
break;
}
result.data = data.subarray(i);
return result;
}
var AUDIO_PACKET = 8;
var VIDEO_PACKET = 9;
var MAX_PACKETS_IN_CHUNK = 50;
var SPLIT_AT_KEYFRAMES = true;
interface CachedPacket {
packet: any;
timestamp: number;
trackId: number;
}
export interface MP4Track {
codecDescription?: string;
codecId: number;
language: string;
timescale: number;
samplerate?: number;
channels?: number;
samplesize?: number;
framerate?: number;
width?: number;
height?: number;
}
export interface MP4Metadata {
tracks: MP4Track[];
duration: number;
audioTrackId: number;
videoTrackId: number;
}
enum MP4MuxState {
CAN_GENERATE_HEADER = 0,
NEED_HEADER_DATA = 1,
MAIN_PACKETS = 2
}
interface MP4TrackState {
trackId: number;
trackInfo: MP4Track;
cachedDuration: number;
samplesProcessed: number;
initializationData: Uint8Array[];
mimeTypeCodec?: string;
}
export class MP4Mux {
private metadata: MP4Metadata;
private filePos: number;
private cachedPackets: CachedPacket[];
private trackStates: MP4TrackState[];
private audioTrackState: MP4TrackState;
private videoTrackState: MP4TrackState;
private state: MP4MuxState;
private chunkIndex: number;
oncodecinfo: (codecs: string[]) => void = function (codecs: string[]) {
//
};
ondata: (data) => void = function (data) {
throw new Error('MP4Mux.ondata is not set');
};
public constructor(metadata: MP4Metadata) {
this.metadata = metadata;
this.trackStates = this.metadata.tracks.map((t, index) => {
var state = {
trackId: index + 1,
trackInfo: t,
cachedDuration: 0,
samplesProcessed: 0,
initializationData: []
};
if (this.metadata.audioTrackId === index) {
this.audioTrackState = state;
}
if (this.metadata.videoTrackId === index) {
this.videoTrackState = state;
}
return state;
}, this);
this._checkIfNeedHeaderData();
this.filePos = 0;
this.cachedPackets = [];
this.chunkIndex = 0;
}
public pushPacket(type: number, data: Uint8Array, timestamp: number) {
if (this.state === MP4MuxState.CAN_GENERATE_HEADER) {
this._tryGenerateHeader();
}
switch (type) {
case AUDIO_PACKET: // audio
var audioTrack = this.audioTrackState;
var audioPacket = parseAudiodata(data);
if (!audioTrack || audioTrack.trackInfo.codecId !== audioPacket.codecId) {
throw new Error('Unexpected audio packet codec: ' + audioPacket.codecDescription);
}
switch (audioPacket.codecId) {
default:
throw new Error('Unsupported audio codec: ' + audioPacket.codecDescription);
case MP3_SOUND_CODEC_ID:
break; // supported codec
case AAC_SOUND_CODEC_ID:
if (audioPacket.packetType === AudioPacketType.HEADER) {
audioTrack.initializationData.push(audioPacket.data);
return;
}
break;
}
this.cachedPackets.push({packet: audioPacket, timestamp: timestamp, trackId: audioTrack.trackId});
break;
case VIDEO_PACKET:
var videoTrack = this.videoTrackState;
var videoPacket = parseVideodata(data);
if (!videoTrack || videoTrack.trackInfo.codecId !== videoPacket.codecId) {
throw new Error('Unexpected video packet codec: ' + videoPacket.codecDescription);
}
switch (videoPacket.codecId) {
default:
throw new Error('unsupported video codec: ' + videoPacket.codecDescription);
case VP6_VIDEO_CODEC_ID:
break; // supported
case AVC_VIDEO_CODEC_ID:
if (videoPacket.packetType === VideoPacketType.HEADER) {
videoTrack.initializationData.push(videoPacket.data);
return;
}
break;
}
this.cachedPackets.push({packet: videoPacket, timestamp: timestamp, trackId: videoTrack.trackId});
break;
default:
throw new Error('unknown packet type: ' + type);
}
if (this.state === MP4MuxState.NEED_HEADER_DATA) {
this._tryGenerateHeader();
}
if (this.cachedPackets.length >= MAX_PACKETS_IN_CHUNK &&
this.state === MP4MuxState.MAIN_PACKETS) {
this._chunk();
}
}
public flush() {
if (this.cachedPackets.length > 0) {
this._chunk();
}
}
private _checkIfNeedHeaderData() {
if (this.trackStates.some((ts) =>
ts.trackInfo.codecId === AAC_SOUND_CODEC_ID || ts.trackInfo.codecId === AVC_VIDEO_CODEC_ID)) {
this.state = MP4MuxState.NEED_HEADER_DATA;
} else {
this.state = MP4MuxState.CAN_GENERATE_HEADER;
}
}
private _tryGenerateHeader() {
var allInitializationDataExists = this.trackStates.every((ts) => {
switch (ts.trackInfo.codecId) {
case AAC_SOUND_CODEC_ID:
case AVC_VIDEO_CODEC_ID:
return ts.initializationData.length > 0;
default:
return true;
}
});
if (!allInitializationDataExists) {
return; // not enough data, waiting more
}
var brands: string[] = ['isom'];
var audioDataReferenceIndex = 1, videoDataReferenceIndex = 1;
var traks: Iso.TrackBox[] = [];
for (var i = 0; i < this.trackStates.length; i++) {
var trackState = this.trackStates[i];
var trackInfo = trackState.trackInfo;
var sampleEntry: Iso.SampleEntry;
switch (trackInfo.codecId) {
case AAC_SOUND_CODEC_ID:
var audioSpecificConfig = trackState.initializationData[0];
sampleEntry = new Iso.AudioSampleEntry('mp4a', audioDataReferenceIndex, trackInfo.channels, trackInfo.samplesize, trackInfo.samplerate);
var esdsData = new Uint8Array(41 + audioSpecificConfig.length);
esdsData.set(hex('0000000003808080'), 0);
esdsData[8] = 32 + audioSpecificConfig.length;
esdsData.set(hex('00020004808080'), 9);
esdsData[16] = 18 + audioSpecificConfig.length;
esdsData.set(hex('40150000000000FA000000000005808080'), 17);
esdsData[34] = audioSpecificConfig.length;
esdsData.set(audioSpecificConfig, 35);
esdsData.set(hex('068080800102'), 35 + audioSpecificConfig.length);
(<Iso.AudioSampleEntry>sampleEntry).otherBoxes = [
new Iso.RawTag('esds', esdsData)
];
var objectType = (audioSpecificConfig[0] >> 3); // TODO 31
// mp4a.40.objectType
trackState.mimeTypeCodec = 'mp4a.40.' + objectType;
break;
case MP3_SOUND_CODEC_ID:
sampleEntry = new Iso.AudioSampleEntry('.mp3', audioDataReferenceIndex, trackInfo.channels, trackInfo.samplesize, trackInfo.samplerate);
trackState.mimeTypeCodec = 'mp3';
break;
case AVC_VIDEO_CODEC_ID:
var avcC = trackState.initializationData[0];
sampleEntry = new Iso.VideoSampleEntry('avc1', videoDataReferenceIndex, trackInfo.width, trackInfo.height);
(<Iso.VideoSampleEntry>sampleEntry).otherBoxes = [
new Iso.RawTag('avcC', avcC)
];
var codecProfile = (avcC[1] << 16) | (avcC[2] << 8) | avcC[3];
// avc1.XXYYZZ -- XX - profile + YY - constraints + ZZ - level
trackState.mimeTypeCodec = 'avc1.' + (0x1000000 | codecProfile).toString(16).substr(1);
brands.push('iso2', 'avc1', 'mp41');
break;
case VP6_VIDEO_CODEC_ID:
sampleEntry = new Iso.VideoSampleEntry('VP6F', videoDataReferenceIndex, trackInfo.width, trackInfo.height);
(<Iso.VideoSampleEntry>sampleEntry).otherBoxes = [
new Iso.RawTag('glbl', hex('00'))
];
// TODO to lie about codec to get it playing in MSE?
trackState.mimeTypeCodec = 'avc1.42001E';
break;
default:
throw new Error('not supported track type');
}
var trak;
var trakFlags = Iso.TrackHeaderFlags.TRACK_ENABLED | Iso.TrackHeaderFlags.TRACK_IN_MOVIE;
if (trackState === this.audioTrackState) {
trak = new Iso.TrackBox(
new Iso.TrackHeaderBox(trakFlags, trackState.trackId, -1, 0 /*width*/, 0 /*height*/, 1.0, i),
new Iso.MediaBox(
new Iso.MediaHeaderBox(trackInfo.timescale, -1, trackInfo.language),
new Iso.HandlerBox('soun', 'SoundHandler'),
new Iso.MediaInformationBox(
new Iso.SoundMediaHeaderBox(),
new Iso.DataInformationBox(
new Iso.DataReferenceBox([new Iso.DataEntryUrlBox(Iso.SELF_CONTAINED_DATA_REFERENCE_FLAG)])),
new Iso.SampleTableBox(
new Iso.SampleDescriptionBox([sampleEntry]),
new Iso.RawTag('stts', hex('0000000000000000')),
new Iso.RawTag('stsc', hex('0000000000000000')),
new Iso.RawTag('stsz', hex('000000000000000000000000')),
new Iso.RawTag('stco', hex('0000000000000000'))
)
)
)
);
} else if (trackState === this.videoTrackState) {
trak = new Iso.TrackBox(
new Iso.TrackHeaderBox(trakFlags, trackState.trackId, -1, trackInfo.width, trackInfo.height, 0 /* volume */, i),
new Iso.MediaBox(
new Iso.MediaHeaderBox(trackInfo.timescale, -1, trackInfo.language),
new Iso.HandlerBox('vide', 'VideoHandler'),
new Iso.MediaInformationBox(
new Iso.VideoMediaHeaderBox(),
new Iso.DataInformationBox(
new Iso.DataReferenceBox([new Iso.DataEntryUrlBox(Iso.SELF_CONTAINED_DATA_REFERENCE_FLAG)])),
new Iso.SampleTableBox(
new Iso.SampleDescriptionBox([sampleEntry]),
new Iso.RawTag('stts', hex('0000000000000000')),
new Iso.RawTag('stsc', hex('0000000000000000')),
new Iso.RawTag('stsz', hex('000000000000000000000000')),
new Iso.RawTag('stco', hex('0000000000000000'))
)
)
)
);
}
traks.push(trak);
}
var mvex = new Iso.MovieExtendsBox(null, [
new Iso.TrackExtendsBox(1, 1, 0, 0, 0),
new Iso.TrackExtendsBox(2, 1, 0, 0, 0)
], null);
var udat = new Iso.BoxContainerBox('udat', [
new Iso.MetaBox(
new Iso.RawTag('hdlr', hex('00000000000000006D6469726170706C000000000000000000')), // notice weird stuff in reserved field
[new Iso.RawTag('ilst', hex('00000025A9746F6F0000001D6461746100000001000000004C61766635342E36332E313034'))]
)
]);
var mvhd = new Iso.MovieHeaderBox(1000, 0 /* unknown duration */, this.trackStates.length + 1);
var moov = new Iso.MovieBox(mvhd, traks, mvex, udat);
var ftype = new Iso.FileTypeBox('isom', 0x00000200, brands);
var ftypeSize = ftype.layout(0);
var moovSize = moov.layout(ftypeSize);
var header = new Uint8Array(ftypeSize + moovSize);
ftype.write(header);
moov.write(header);
this.oncodecinfo(this.trackStates.map((ts) => ts.mimeTypeCodec));
this.ondata(header);
this.filePos += header.length;
this.state = MP4MuxState.MAIN_PACKETS;
}
_chunk() {
var cachedPackets = this.cachedPackets;
if (SPLIT_AT_KEYFRAMES && this.videoTrackState) {
var j = cachedPackets.length - 1;
var videoTrackId = this.videoTrackState.trackId;
// Finding last video keyframe.
while (j > 0 &&
(cachedPackets[j].trackId !== videoTrackId || cachedPackets[j].packet.frameType !== VideoFrameType.KEY)) {
j--;
}
if (j > 0) {
// We have keyframes and not only the first frame is a keyframe...
cachedPackets = cachedPackets.slice(0, j);
}
}
if (cachedPackets.length === 0) {
return; // No data to produce.
}
var tdatParts: Uint8Array[] = [];
var tdatPosition: number = 0;
var trafs: Iso.TrackFragmentBox[] = [];
var trafDataStarts: number[] = [];
for (var i = 0; i < this.trackStates.length; i++) {
var trackState = this.trackStates[i];
var trackInfo = trackState.trackInfo;
var trackId = trackState.trackId;
// Finding all packets for this track.
var trackPackets = cachedPackets.filter((cp) => cp.trackId === trackId);
if (trackPackets.length === 0) {
continue;
}
//var currentTimestamp = (trackPackets[0].timestamp * trackInfo.timescale / 1000) | 0;
var tfdt = new Iso.TrackFragmentBaseMediaDecodeTimeBox(trackState.cachedDuration);
var tfhd: Iso.TrackFragmentHeaderBox;
var trun: Iso.TrackRunBox;
var trunSamples: Iso.TrackRunSample[];
trafDataStarts.push(tdatPosition);
switch (trackInfo.codecId) {
case AAC_SOUND_CODEC_ID:
case MP3_SOUND_CODEC_ID:
trunSamples = [];
for (var j = 0; j < trackPackets.length; j++) {
var audioPacket: AudioPacket = trackPackets[j].packet;
var audioFrameDuration = Math.round(audioPacket.samples * trackInfo.timescale / trackInfo.samplerate);
tdatParts.push(audioPacket.data);
tdatPosition += audioPacket.data.length;
trunSamples.push({duration: audioFrameDuration, size: audioPacket.data.length});
trackState.samplesProcessed += audioPacket.samples;
}
var tfhdFlags = Iso.TrackFragmentFlags.DEFAULT_SAMPLE_FLAGS_PRESENT;
tfhd = new Iso.TrackFragmentHeaderBox(tfhdFlags, trackId, 0 /* offset */, 0 /* index */, 0 /* duration */, 0 /* size */, Iso.SampleFlags.SAMPLE_DEPENDS_ON_NO_OTHERS);
var trunFlags = Iso.TrackRunFlags.DATA_OFFSET_PRESENT |
Iso.TrackRunFlags.SAMPLE_DURATION_PRESENT | Iso.TrackRunFlags.SAMPLE_SIZE_PRESENT;
trun = new Iso.TrackRunBox(trunFlags, trunSamples, 0 /* data offset */, 0 /* first flags */);
trackState.cachedDuration = Math.round(trackState.samplesProcessed * trackInfo.timescale / trackInfo.samplerate);
break;
case AVC_VIDEO_CODEC_ID:
case VP6_VIDEO_CODEC_ID:
trunSamples = [];
var samplesProcessed = trackState.samplesProcessed;
var decodeTime = samplesProcessed * trackInfo.timescale / trackInfo.framerate;
var lastTime = Math.round(decodeTime);
for (var j = 0; j < trackPackets.length; j++) {
var videoPacket: VideoPacket = trackPackets[j].packet;
samplesProcessed++;
var nextTime = Math.round(samplesProcessed * trackInfo.timescale / trackInfo.framerate);
var videoFrameDuration = nextTime - lastTime;
lastTime = nextTime;
var compositionTime = Math.round(samplesProcessed * trackInfo.timescale / trackInfo.framerate +
videoPacket.compositionTime * trackInfo.timescale / 1000);
tdatParts.push(videoPacket.data);
tdatPosition += videoPacket.data.length;
var frameFlags = videoPacket.frameType === VideoFrameType.KEY ?
Iso.SampleFlags.SAMPLE_DEPENDS_ON_NO_OTHERS :
(Iso.SampleFlags.SAMPLE_DEPENDS_ON_OTHER | Iso.SampleFlags.SAMPLE_IS_NOT_SYNC);
trunSamples.push({duration: videoFrameDuration, size: videoPacket.data.length,
flags: frameFlags, compositionTimeOffset: (compositionTime - nextTime)});
}
var tfhdFlags = Iso.TrackFragmentFlags.DEFAULT_SAMPLE_FLAGS_PRESENT;
tfhd = new Iso.TrackFragmentHeaderBox(tfhdFlags, trackId, 0 /* offset */, 0 /* index */, 0 /* duration */, 0 /* size */, Iso.SampleFlags.SAMPLE_DEPENDS_ON_NO_OTHERS);
var trunFlags = Iso.TrackRunFlags.DATA_OFFSET_PRESENT |
Iso.TrackRunFlags.SAMPLE_DURATION_PRESENT | Iso.TrackRunFlags.SAMPLE_SIZE_PRESENT |
Iso.TrackRunFlags.SAMPLE_FLAGS_PRESENT | Iso.TrackRunFlags.SAMPLE_COMPOSITION_TIME_OFFSET;
trun = new Iso.TrackRunBox(trunFlags, trunSamples, 0 /* data offset */, 0 /* first flag */ );
trackState.cachedDuration = lastTime;
trackState.samplesProcessed = samplesProcessed;
break;
default:
throw new Error('Un codec');
}
var traf = new Iso.TrackFragmentBox(tfhd, tfdt, trun);
trafs.push(traf);
}
this.cachedPackets.splice(0, cachedPackets.length);
var moofHeader = new Iso.MovieFragmentHeaderBox(++this.chunkIndex);
var moof = new Iso.MovieFragmentBox(moofHeader, trafs);
var moofSize = moof.layout(0);
var mdat = new Iso.MediaDataBox(tdatParts);
var mdatSize = mdat.layout(moofSize);
var tdatOffset = moofSize + 8 /* 'mdat' header size */;
for (var i = 0; i < trafs.length; i++) {
trafs[i].run.dataOffset = tdatOffset + trafDataStarts[i];
}
var chunk = new Uint8Array(moofSize + mdatSize);
moof.write(chunk);
mdat.write(chunk);
this.ondata(chunk);
this.filePos += chunk.length;
}
}
export function parseFLVMetadata(metadata: any): MP4Metadata {
var tracks: MP4Track[] = [];
var audioTrackId = -1;
var videoTrackId = -1;
var duration = +metadata.asGetPublicProperty('duration');
var audioCodec, audioCodecId;
var audioCodecCode = metadata.asGetPublicProperty('audiocodecid');
switch (audioCodecCode) {
case MP3_SOUND_CODEC_ID:
case 'mp3':
audioCodec = 'mp3';
audioCodecId = MP3_SOUND_CODEC_ID;
break;
case AAC_SOUND_CODEC_ID:
case 'mp4a':
audioCodec = 'mp4a';
audioCodecId = AAC_SOUND_CODEC_ID;
break;
default:
if (!isNaN(audioCodecCode)) {
throw new Error('Unsupported audio codec: ' + audioCodecCode);
}
audioCodec = null;
audioCodecId = -1;
break;
}
var videoCodec, videoCodecId;
var videoCodecCode = metadata.asGetPublicProperty('videocodecid');
switch (videoCodecCode) {
case VP6_VIDEO_CODEC_ID:
case 'vp6f':
videoCodec = 'vp6f';
videoCodecId = VP6_VIDEO_CODEC_ID;
break;
case AVC_VIDEO_CODEC_ID:
case 'avc1':
videoCodec = 'avc1';
videoCodecId = AVC_VIDEO_CODEC_ID;
break;
default:
if (!isNaN(videoCodecCode)) {
throw new Error('Unsupported video codec: ' + videoCodecCode);
}
videoCodec = null;
videoCodecId = -1;
break;
}
var audioTrack: MP4Track = (audioCodec === null) ? null : {
codecDescription: audioCodec,
codecId: audioCodecId,
language: 'und',
timescale: +metadata.asGetPublicProperty('audiosamplerate') || 44100,
samplerate: +metadata.asGetPublicProperty('audiosamplerate') || 44100,
channels: +metadata.asGetPublicProperty('audiochannels') || 2,
samplesize: 16
};
var videoTrack: MP4Track = (videoCodec === null) ? null : {
codecDescription: videoCodec,
codecId: videoCodecId,
language: 'und',
timescale: 60000,
framerate: +metadata.asGetPublicProperty('videoframerate') ||
+metadata.asGetPublicProperty('framerate'),
width: +metadata.asGetPublicProperty('width'),
height: +metadata.asGetPublicProperty('height')
};
var trackInfos = metadata.asGetPublicProperty('trackinfo');
if (trackInfos) {
// Not in the Adobe's references, red5 specific?
for (var i = 0; i < trackInfos.length; i++) {
var info = trackInfos[i];
var sampleDescription = info.asGetPublicProperty('sampledescription')[0];
if (sampleDescription.asGetPublicProperty('sampletype') === audioCodecCode) {
audioTrack.language = info.asGetPublicProperty('language');
audioTrack.timescale = +info.asGetPublicProperty('timescale');
} else if (sampleDescription.asGetPublicProperty('sampletype') === videoCodecCode) {
videoTrack.language = info.asGetPublicProperty('language');
videoTrack.timescale = +info.asGetPublicProperty('timescale');
}
}
}
if (videoTrack) {
videoTrackId = tracks.length;
tracks.push(videoTrack);
}
if (audioTrack) {
audioTrackId = tracks.length;
tracks.push(audioTrack);
}
return {
tracks: tracks,
duration: duration,
audioTrackId: audioTrackId,
videoTrackId: videoTrackId
};
}
export function splitMetadata(metadata: MP4Metadata): MP4Metadata[] {
var tracks: MP4Metadata[] = [];
if (metadata.audioTrackId >= 0) {
tracks.push({
tracks: [metadata.tracks[metadata.audioTrackId]],
duration: metadata.duration,
audioTrackId: 0,
videoTrackId: -1
});
}
if (metadata.videoTrackId >= 0) {
tracks.push({
tracks: [metadata.tracks[metadata.videoTrackId]],
duration: metadata.duration,
audioTrackId: -1,
videoTrackId: 0
});
}
return tracks;
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.