text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { getOwner, setOwner } from '@ember/application';
import { associateDestroyableChild, destroy } from '@ember/destroyable';
import { Assertion, Listener, Log, Orbit, TaskQueue } from '@orbit/core';
import {
buildQuery,
buildTransform,
DefaultRequestOptions,
FullRequestOptions,
FullResponse,
RequestOptions,
TransformBuilderFunc
} from '@orbit/data';
import MemorySource, { MemorySourceMergeOptions } from '@orbit/memory';
import { RecordCacheQueryOptions } from '@orbit/record-cache';
import {
InitializedRecord,
RecordKeyMap,
RecordOperation,
RecordQueryResult,
RecordSchema,
RecordSourceQueryOptions,
RecordTransform,
RecordTransformResult,
StandardRecordValidator,
UninitializedRecord
} from '@orbit/records';
import { StandardValidator, ValidatorForFn } from '@orbit/validators';
import Cache, { CacheSettings } from './cache';
import LiveQuery from './live-query';
import Model from './model';
import {
ModelAwareQueryBuilder,
ModelAwareQueryOrExpressions,
ModelAwareTransformBuilder,
ModelAwareTransformOrOperations,
RecordIdentityOrModel
} from './utils/model-aware-types';
import { ModelFields } from './utils/model-fields';
const { assert, deprecate } = Orbit;
export interface StoreSettings {
source: MemorySource<
RecordSourceQueryOptions,
RequestOptions,
ModelAwareQueryBuilder,
ModelAwareTransformBuilder
>;
base?: Store;
}
/**
* @class Store
*/
export default class Store {
#source: MemorySource<
RecordSourceQueryOptions,
RequestOptions,
ModelAwareQueryBuilder,
ModelAwareTransformBuilder
>;
#cache: Cache;
#base?: Store;
static create(injections: StoreSettings): Store {
const owner = getOwner(injections);
const store = new this(injections);
setOwner(store, owner);
return store;
}
constructor(settings: StoreSettings) {
this.#source = settings.source;
this.#base = settings.base;
const owner = getOwner(settings);
const cacheSettings: CacheSettings = {
sourceCache: this.source.cache
};
setOwner(cacheSettings, owner);
this.#cache = new Cache(cacheSettings);
if (this.#base) {
associateDestroyableChild(this.#base, this);
}
associateDestroyableChild(this, this.#cache);
}
destroy() {
destroy(this);
}
get source(): MemorySource<
RecordSourceQueryOptions,
RequestOptions,
ModelAwareQueryBuilder,
ModelAwareTransformBuilder
> {
return this.#source;
}
get cache(): Cache {
return this.#cache;
}
get keyMap(): RecordKeyMap | undefined {
return this.source.keyMap;
}
get schema(): RecordSchema {
return this.source.schema;
}
get queryBuilder(): ModelAwareQueryBuilder {
return this.source.queryBuilder;
}
get transformBuilder(): ModelAwareTransformBuilder {
return this.source.transformBuilder;
}
get validatorFor():
| ValidatorForFn<StandardValidator | StandardRecordValidator>
| undefined {
return this.#source.validatorFor;
}
get defaultQueryOptions():
| DefaultRequestOptions<RecordSourceQueryOptions>
| undefined {
return this.source.defaultQueryOptions;
}
set defaultQueryOptions(
options: DefaultRequestOptions<RecordSourceQueryOptions> | undefined
) {
this.source.defaultQueryOptions = options;
}
get defaultTransformOptions():
| DefaultRequestOptions<RequestOptions>
| undefined {
return this.source.defaultTransformOptions;
}
set defaultTransformOptions(
options: DefaultRequestOptions<RequestOptions> | undefined
) {
this.source.defaultTransformOptions = options;
}
get transformLog(): Log {
return this.source.transformLog;
}
get requestQueue(): TaskQueue {
return this.source.requestQueue;
}
get syncQueue(): TaskQueue {
return this.source.syncQueue;
}
get forked(): boolean {
return !!this.source.base;
}
get base(): Store | undefined {
return this.#base;
}
fork(): Store {
const forkedSource = this.source.fork({
schema: this.schema,
cacheSettings: { debounceLiveQueries: false }
});
const injections = getOwner(this).ownerInjection();
return Store.create({
...injections,
source: forkedSource,
base: this
});
}
merge<
RequestData extends RecordTransformResult<Model> = RecordTransformResult<Model>
>(
forkedStore: Store,
options?: DefaultRequestOptions<RequestOptions> & MemorySourceMergeOptions
): Promise<RequestData>;
merge<
RequestData extends RecordTransformResult<Model> = RecordTransformResult<Model>
>(
forkedStore: Store,
options: FullRequestOptions<RequestOptions> & MemorySourceMergeOptions
): Promise<FullResponse<RequestData, unknown, RecordOperation>>;
async merge<
RequestData extends RecordTransformResult<Model> = RecordTransformResult<Model>
>(
forkedStore: Store,
options?: RequestOptions & MemorySourceMergeOptions
): Promise<
RequestData | FullResponse<RequestData, unknown, RecordOperation>
> {
if (options?.fullResponse) {
let response = (await this.source.merge(
forkedStore.source,
options as FullRequestOptions<RequestOptions> & MemorySourceMergeOptions
)) as FullResponse<
RecordTransformResult<InitializedRecord>,
unknown,
RecordOperation
>;
if (response.data !== undefined) {
const data = this.cache._lookupTransformResult(
response.data,
true // merge results should ALWAYS be an array
);
response = {
...response,
data
};
}
return response as FullResponse<RequestData, unknown, RecordOperation>;
} else {
let response = (await this.source.merge(
forkedStore.source,
options as DefaultRequestOptions<RequestOptions> &
MemorySourceMergeOptions
)) as RecordTransformResult<InitializedRecord>;
if (response !== undefined) {
response = this.cache._lookupTransformResult(
response,
true // merge results should ALWAYS be an array
);
}
return response as RequestData;
}
}
rollback(transformId: string, relativePosition?: number): Promise<void> {
return this.source.rollback(transformId, relativePosition);
}
rebase(): void {
this.source.rebase();
}
reset(): Promise<void> {
return this.source.reset();
}
/**
* @deprecated
*/
async liveQuery(
queryOrExpressions: ModelAwareQueryOrExpressions,
options?: DefaultRequestOptions<RecordCacheQueryOptions>,
id?: string
): Promise<LiveQuery> {
deprecate(
'Store#liveQuery is deprecated. Call `let lq = store.cache.liveQuery(query)` instead. If you want to await the same query on the store, call `await store.query(lq.query);'
);
const query = buildQuery(
queryOrExpressions,
options,
id,
this.source.queryBuilder
);
await this.source.query(query);
return this.cache.liveQuery(query);
}
async query<
RequestData extends RecordQueryResult<Model> = RecordQueryResult<Model>
>(
queryOrExpressions: ModelAwareQueryOrExpressions,
options?: DefaultRequestOptions<RecordCacheQueryOptions>,
id?: string
): Promise<RequestData>;
async query<
RequestData extends RecordQueryResult<Model> = RecordQueryResult<Model>
>(
queryOrExpressions: ModelAwareQueryOrExpressions,
options: FullRequestOptions<RecordCacheQueryOptions>,
id?: string
): Promise<FullResponse<RequestData, undefined, RecordOperation>>;
async query<
RequestData extends RecordQueryResult<Model> = RecordQueryResult<Model>
>(
queryOrExpressions: ModelAwareQueryOrExpressions,
options?: RecordCacheQueryOptions,
id?: string
): Promise<
RequestData | FullResponse<RequestData, undefined, RecordOperation>
> {
const query = buildQuery(
queryOrExpressions,
options,
id,
this.source.queryBuilder
);
if (options?.fullResponse) {
const response = await this.source.query(query, { fullResponse: true });
return {
...response,
data: this.cache._lookupQueryResult(
response.data,
Array.isArray(query.expressions)
)
} as FullResponse<RequestData, undefined, RecordOperation>;
} else {
const response = await this.source.query(query);
const data = this.cache._lookupQueryResult(
response,
Array.isArray(query.expressions)
);
return data as RequestData;
}
}
/**
* Adds a record
*/
async addRecord<RequestData extends RecordTransformResult<Model> = Model>(
properties: UninitializedRecord | ModelFields,
options?: DefaultRequestOptions<RecordCacheQueryOptions>
): Promise<RequestData> {
assert(
'Store#addRecord does not support the `fullResponse` option. Call `store.update(..., { fullResponse: true })` instead.',
options?.fullResponse === undefined
);
return await this.update((t) => t.addRecord(properties), options);
}
/**
* Updates a record
*/
async updateRecord<RequestData extends RecordTransformResult<Model> = Model>(
properties: InitializedRecord | ModelFields,
options?: DefaultRequestOptions<RecordCacheQueryOptions>
): Promise<RequestData> {
assert(
'Store#updateRecord does not support the `fullResponse` option. Call `store.update(..., { fullResponse: true })` instead.',
options?.fullResponse === undefined
);
return await this.update((t) => t.updateRecord(properties), options);
}
/**
* Removes a record
*/
async removeRecord(
identity: RecordIdentityOrModel,
options?: DefaultRequestOptions<RecordCacheQueryOptions>
): Promise<void> {
assert(
'Store#removeRecord does not support the `fullResponse` option. Call `store.update(..., { fullResponse: true })` instead.',
options?.fullResponse === undefined
);
await this.update((t) => t.removeRecord(identity), options);
}
/**
* @deprecated
*/
find(
type: string,
id?: string | undefined,
options?: DefaultRequestOptions<RecordCacheQueryOptions>
): Promise<Model | Model[] | undefined> {
deprecate(
'Store#find is deprecated. Call `store.findRecords(type)`, `store.findRecord(type, id)`, or `store.query(...)` instead.'
);
if (id === undefined) {
return this.findRecords(type, options);
} else {
return this.findRecord(type, id, options);
}
}
findRecord<RequestData extends RecordQueryResult<Model> = Model | undefined>(
type: string,
id: string,
options?: DefaultRequestOptions<RecordCacheQueryOptions>
): Promise<Model | undefined>;
findRecord<RequestData extends RecordQueryResult<Model> = Model | undefined>(
identity: RecordIdentityOrModel,
options?: DefaultRequestOptions<RecordCacheQueryOptions>
): Promise<Model | undefined>;
async findRecord<
RequestData extends RecordQueryResult<Model> = Model | undefined
>(
typeOrIdentity: string | RecordIdentityOrModel,
idOrOptions?: string | DefaultRequestOptions<RecordCacheQueryOptions>,
options?: DefaultRequestOptions<RecordCacheQueryOptions>
): Promise<RequestData> {
if (options?.fullResponse) {
delete options.fullResponse;
}
let identity: RecordIdentityOrModel;
let queryOptions: DefaultRequestOptions<RequestOptions> | undefined;
if (typeof typeOrIdentity === 'string') {
if (typeof idOrOptions === 'string') {
identity = { type: typeOrIdentity, id: idOrOptions };
queryOptions = options;
} else {
throw new Assertion(
'Store#findRecord may be called with either `type` and `id` strings OR a single `identity` object.'
);
}
} else {
identity = typeOrIdentity;
queryOptions = idOrOptions as DefaultRequestOptions<RequestOptions>;
}
return await this.query((q) => q.findRecord(identity), queryOptions);
}
async findRecords<RequestData extends RecordQueryResult<Model> = Model[]>(
typeOrIdentities: string | RecordIdentityOrModel[],
options?: DefaultRequestOptions<RecordCacheQueryOptions>
): Promise<RequestData> {
if (options?.fullResponse) {
delete options.fullResponse;
}
return await this.query<RequestData>(
(q) => q.findRecords(typeOrIdentities),
options
);
}
/**
* @deprecated
*/
async findRecordByKey(
type: string,
key: string,
value: string,
options?: DefaultRequestOptions<RecordCacheQueryOptions>
): Promise<Model | undefined> {
deprecate(
'Store#findRecordByKey is deprecated. Instead of `store.findRecordByKey(type, key, value)`, call `store.findRecord({ type, key, value })` or `store.query(...)`.'
);
return this.findRecord({ type, key, value }, options);
}
/**
* @deprecated
*/
peekRecord(type: string, id: string): Model | undefined {
deprecate(
'Store#peekRecord is deprecated. Instead of `store.peekRecord(type, id)`, call `store.cache.findRecord(type, id)` or `store.cache.query(...)`.'
);
return this.cache.findRecord(type, id);
}
/**
* @deprecated
*/
peekRecords(type: string): Model[] {
deprecate(
'Store#peekRecords is deprecated. Instead of `store.peekRecords(type)`, call `store.cache.findRecords(type)` or `store.cache.query(...)`.'
);
return this.cache.findRecords(type);
}
/**
* @deprecated
*/
peekRecordByKey(type: string, key: string, value: string): Model | undefined {
deprecate(
'Store#peekRecordByKey is deprecated. Instead of `store.peekRecordByKey(type, key, value)`, call `store.cache.findRecord({ type, key, value })` or `store.cache.query(...)`.'
);
return this.cache.findRecord({ type, key, value });
}
on(event: string, listener: Listener): void {
this.source.on(event, listener);
}
off(event: string, listener: Listener): void {
this.source.off(event, listener);
}
one(event: string, listener: Listener): void {
this.source.one(event, listener);
}
async sync(
transformOrTransforms:
| RecordTransform
| RecordTransform[]
| TransformBuilderFunc<RecordOperation, ModelAwareTransformBuilder>
): Promise<void> {
await this.source.sync(transformOrTransforms);
}
update<
RequestData extends RecordTransformResult<Model> = RecordTransformResult<Model>
>(
transformOrOperations: ModelAwareTransformOrOperations,
options?: DefaultRequestOptions<RequestOptions>,
id?: string
): Promise<RequestData>;
update<
RequestData extends RecordTransformResult<Model> = RecordTransformResult<Model>
>(
transformOrOperations: ModelAwareTransformOrOperations,
options: FullRequestOptions<RequestOptions>,
id?: string
): Promise<FullResponse<RequestData, unknown, RecordOperation>>;
async update<
RequestData extends RecordTransformResult<Model> = RecordTransformResult<Model>
>(
transformOrOperations: ModelAwareTransformOrOperations,
options?: RequestOptions,
id?: string
): Promise<
RequestData | FullResponse<RequestData, unknown, RecordOperation>
> {
const transform = buildTransform(
transformOrOperations,
options,
id,
this.source.transformBuilder
);
if (options?.fullResponse) {
let response = await this.source.update(transform, {
fullResponse: true
});
if (response.data !== undefined) {
const data = this.cache._lookupTransformResult(
response.data,
Array.isArray(transform.operations)
);
response = {
...response,
data
};
}
return response as FullResponse<RequestData, unknown, RecordOperation>;
} else {
let response = await this.source.update(transform);
if (response !== undefined) {
response = this.cache._lookupTransformResult(
response,
Array.isArray(transform.operations)
);
}
return response as RequestData;
}
}
transformsSince(transformId: string): RecordTransform[] {
deprecate(
'`Store#transformsSince` is deprecated. Call `getTransformsSince` instead.'
);
return this.getTransformsSince(transformId);
}
getTransformsSince(transformId: string): RecordTransform[] {
return this.source.getTransformsSince(transformId);
}
allTransforms(): RecordTransform[] {
deprecate(
'`Store#allTransforms` is deprecated. Call `getAllTransforms` instead.'
);
return this.getAllTransforms();
}
getAllTransforms(): RecordTransform[] {
return this.source.getAllTransforms();
}
getTransform(transformId: string): RecordTransform {
return this.source.getTransform(transformId);
}
getInverseOperations(transformId: string): RecordOperation[] {
return this.source.getInverseOperations(transformId);
}
} | the_stack |
import Series from "./series";
import Utils from "../shared/utils"
import DataFrame from "./frame";
import { NDframeInterface } from "../shared/types";
const utils = new Utils();
/**
* Internal function to slice a Series/DataFrame by index based labels
* @param Object
*/
export function _iloc({ ndFrame, rows, columns }: {
ndFrame: NDframeInterface
rows?: Array<string | number | boolean> | Series
columns?: Array<string | number>
}): Series | DataFrame {
let _rowIndexes: Array<number>
let _columnIndexes: Array<number>
const _data = ndFrame.values;
const _index = ndFrame.index;
if (rows instanceof Series) {
rows = rows.values as Array<string | number>
}
if (rows !== undefined && !Array.isArray(rows)) {
throw new Error(`rows parameter must be an Array. For example: rows: [1,2] or rows: ["0:10"]`)
}
if (columns !== undefined && !Array.isArray(columns)) {
throw new Error(`columns parameter must be an Array. For example: columns: [1,2] or columns: ["0:10"]`)
}
if (!rows) {
_rowIndexes = utils.range(0, ndFrame.shape[0] - 1)
} else if (rows.length == 1 && typeof rows[0] == "string") {
const rowSplit = rows[0].split(":")
if (rowSplit.length != 2) {
throw new Error(`Invalid row split parameter: If using row split string, it must be of the form; rows: ["start:end"]`);
}
if (isNaN(parseInt(rowSplit[0])) && rowSplit[0] != "") {
throw new Error(`Invalid row split parameter. Split parameter must be a number`);
}
if (isNaN(parseInt(rowSplit[1])) && rowSplit[1] != "") {
throw new Error(`Invalid row split parameter. Split parameter must be a number`);
}
const start = rowSplit[0] == "" ? 0 : parseInt(rowSplit[0])
const end = rowSplit[1] == "" ? ndFrame.shape[0] : parseInt(rowSplit[1])
if (start < 0) {
throw new Error(`row slice [start] index cannot be less than 0`);
}
if (end > ndFrame.shape[0]) {
throw new Error(`row slice [end] index cannot be bigger than ${ndFrame.shape[0]}`);
}
_rowIndexes = utils.range(start, end - 1)
} else {
const _formatedRows = []
for (let i = 0; i < rows.length; i++) {
let _indexToUse = rows[i];
if (_indexToUse > ndFrame.shape[0]) {
throw new Error(`Invalid row parameter: Specified index ${_indexToUse} cannot be bigger than index length ${ndFrame.shape[0]}`);
}
if (typeof _indexToUse !== "number" && typeof _indexToUse !== "boolean") {
throw new Error(`Invalid row parameter: row index ${_indexToUse} must be a number or boolean`);
}
if (typeof _indexToUse === "boolean" && _indexToUse === true) {
_formatedRows.push(_index[i])
}
if (typeof _indexToUse === "number") {
_formatedRows.push(_indexToUse)
}
}
_rowIndexes = _formatedRows as number[]
}
if (!columns) {
_columnIndexes = utils.range(0, ndFrame.shape[1] - 1)
} else if (columns.length == 1 && typeof columns[0] == "string") {
const columnSplit = columns[0].split(":")
if (columnSplit.length != 2) {
throw new Error(`Invalid column split parameter: If using column split string, it must be of the form; columns: ["start:end"]`);
}
if (isNaN(parseInt(columnSplit[0])) && columnSplit[0] != "") {
throw new Error(`Invalid column split parameter. Split parameter must be a number`);
}
if (isNaN(parseInt(columnSplit[1])) && columnSplit[1] != "") {
throw new Error(`Invalid column split parameter. Split parameter must be a number`);
}
const start = columnSplit[0] == "" ? 0 : parseInt(columnSplit[0])
const end = columnSplit[1] == "" ? ndFrame.shape[1] : parseInt(columnSplit[1])
if (start < 0) {
throw new Error(`column slice [start] index cannot be less than 0`);
}
if (end > ndFrame.shape[1]) {
throw new Error(`column slice [end] index cannot be bigger than ${ndFrame.shape[1]}`);
}
_columnIndexes = utils.range(start, end - 1)
} else {
for (let i = 0; i < columns.length; i++) {
const _indexToUse = columns[i];
if (_indexToUse > ndFrame.shape[1]) {
throw new Error(`Invalid column parameter: Specified index ${_indexToUse} cannot be bigger than index length ${ndFrame.shape[1]}`);
}
if (typeof _indexToUse != "number") {
throw new Error(`Invalid column parameter: column index ${_indexToUse} must be a number`);
}
}
_columnIndexes = columns as number[]
}
if (ndFrame instanceof Series) {
const newData = []
const newIndex = []
for (let i = 0; i < _rowIndexes.length; i++) {
const rowIndx = _rowIndexes[i]
newData.push(_data[rowIndx])
newIndex.push(_index[rowIndx])
}
const sf = new Series(
newData,
{
index: newIndex,
columns: ndFrame.columns,
dtypes: ndFrame.dtypes,
config: ndFrame.config
})
return sf
} else {
const newData = []
const newIndex = []
const newColumnNames: string[] = []
const newDtypes = []
for (let i = 0; i < _rowIndexes.length; i++) {
const rowIndx = _rowIndexes[i]
const rowData: any = _data[rowIndx]
const newRowDataWithRequiredCols = []
for (let j = 0; j < _columnIndexes.length; j++) {
const colIndx = _columnIndexes[j]
newRowDataWithRequiredCols.push(rowData[colIndx])
}
newData.push(newRowDataWithRequiredCols)
newIndex.push(_index[rowIndx])
}
for (let i = 0; i < _columnIndexes.length; i++) {
const colIndx = _columnIndexes[i]
newColumnNames.push(ndFrame.columns[colIndx])
newDtypes.push(ndFrame.dtypes[colIndx])
}
const df = new DataFrame(
newData,
{
index: newIndex,
columns: newColumnNames,
dtypes: newDtypes,
config: ndFrame.config
})
return df
}
}
/**
* Internal function to slice a Series/DataFrame by specified string location based labels
* @param Object
*/
export function _loc({ ndFrame, rows, columns }: {
ndFrame: NDframeInterface
rows?: Array<string | number | boolean> | Series
columns?: Array<string>
}): Series | DataFrame {
let _rowIndexes: Array<number>
let _columnIndexes: Array<number>
const _data = ndFrame.values;
const _index = ndFrame.index;
if (rows instanceof Series) {
rows = rows.values as Array<string>
}
if (rows !== undefined && !Array.isArray(rows)) {
throw new Error(`rows parameter must be an Array. For example: rows: [1,2] or rows: ["0:10"]`)
}
if (columns !== undefined && !Array.isArray(columns)) {
throw new Error(`columns parameter must be an Array. For example: columns: ["a","b"] or columns: ["a:c"]`)
}
if (!rows) {
_rowIndexes = _index.map(indexValue => _index.indexOf(indexValue)) // Return all row index
} else if (rows.length == 1 && typeof rows[0] == "string") {
if (rows[0].indexOf(":") === -1) { // Input type ==> ["1"] or [`"1"`]
let temp;
if (rows[0].startsWith(`"`) || rows[0].startsWith(`'`) || rows[0].startsWith("`")) {
temp = _index.indexOf(rows[0].replace(/['"`]/g, ''))
} else {
temp = _index.indexOf(Number(rows[0]))
}
if (temp === -1) {
throw new Error(`IndexError: Specified index (${rows[0]}) not found`);
}
_rowIndexes = [temp]
} else {
// Input type ==> ["1:2"] or [`"1":"4"`]
const rowSplit = rows[0].split(":")
if (rowSplit.length != 2) {
throw new Error(`Invalid row split parameter: If using row split string, it must be of the form; rows: ["start:end"]`);
}
let start: number
let end: number
if (rowSplit[0] === "") {
start = _index.indexOf(_index[0])
} else {
if (rowSplit[0].startsWith(`"`) || rowSplit[0].startsWith(`'`) || rowSplit[0].startsWith("`")) {
start = _index.indexOf(rowSplit[0].replace(/['"`]/g, ''))
} else {
start = _index.indexOf(Number(rowSplit[0]))
}
}
if (rowSplit[1] === "") {
end = _index.indexOf(_index[_index.length - 1]) + 1
} else {
if (rowSplit[0].startsWith(`"`) || rowSplit[0].startsWith(`'`) || rowSplit[0].startsWith("`")) {
end = _index.indexOf(rowSplit[1].replace(/['"`]/g, ''))
} else {
end = _index.indexOf(Number(rowSplit[1]))
}
}
if (start === -1) {
throw new Error(`IndexError: Specified start index not found`);
}
if (end === -1) {
throw new Error(`IndexError: Specified end index not found`);
}
_rowIndexes = _index.slice(start, end).map(indexValue => _index.indexOf(indexValue))
}
} else {
// Input type ==> ["1", "2"] or [1, 5] or [true, false]
const rowsIndexToUse = []
for (let i = 0; i < rows.length; i++) {
const isBoolean = typeof rows[i] === "boolean"
if (isBoolean && rows[i]) {
rowsIndexToUse.push(_index.indexOf(_index[i]))
}
if (!isBoolean) {
const rowIndex = _index.indexOf(rows[i] as number | string)
if (rowIndex === -1) {
throw new Error(`IndexError: Specified index (${rows[i]}) not found`);
}
rowsIndexToUse.push(rowIndex)
}
}
_rowIndexes = rowsIndexToUse
}
const _columnNames = ndFrame.columns
if (!columns) {
_columnIndexes = _columnNames.map(columnName => _columnNames.indexOf(columnName))// Return all column index
} else if (columns.length == 1) {
if (typeof columns[0] !== "string") {
throw new Error(`ColumnIndexError: columns parameter must be an array of a string name. For example: columns: ["b"]`)
}
if (columns[0].indexOf(":") == -1) { // Input type ==> ["A"]
_columnIndexes = [_columnNames.indexOf(columns[0])]
} else { // Input type ==> ["a:b"] or [`"col1":"col5"`]
const columnSplit = columns[0].split(":")
if (columnSplit.length != 2) {
throw new Error(`ColumnIndexError: Invalid row split parameter. If using row split string, it must be of the form; rows: ["start:end"]`);
}
const start = columnSplit[0] == "" ? _columnNames.indexOf(_columnNames[0]) : _columnNames.indexOf(columnSplit[0])
const end = columnSplit[1] == "" ? _columnNames.indexOf(_columnNames[_columnNames.length - 1]) : _columnNames.indexOf(columnSplit[1])
if (start === -1) {
throw new Error(`ColumnIndexError: Specified start index not found`);
}
if (end === -1) {
throw new Error(`ColumnIndexError: Specified end index not found`);
}
_columnIndexes = _columnNames.slice(start, end + 1).map(columnName => _columnNames.indexOf(columnName))
_columnIndexes.pop() //Remove the last element
}
} else {// Input type ==> ["A", "B"] or ["col1", "col2"]
for (let i = 0; i < columns.length; i++) {
if (_columnNames.indexOf(columns[i]) === -1) {
throw new Error(`ColumnIndexError: Specified column (${columns[i]}) not found`);
}
}
_columnIndexes = columns.map(columnName => _columnNames.indexOf(columnName))
}
if (ndFrame instanceof Series) {
const newData = []
const newIndex = []
for (let i = 0; i < _rowIndexes.length; i++) {
const rowIndx = _rowIndexes[i]
newData.push(_data[rowIndx])
newIndex.push(_index[rowIndx])
}
const sf = new Series(
newData,
{
index: newIndex,
columns: ndFrame.columns,
dtypes: ndFrame.dtypes,
config: ndFrame.config
})
return sf
} else {
const newData = []
const newIndex = []
const newColumnNames: string[] = []
const newDtypes = []
for (let i = 0; i < _rowIndexes.length; i++) {
const rowIndx: number = _rowIndexes[i]
const rowData: any = _data[rowIndx]
const newRowDataWithRequiredCols = []
for (let j = 0; j < _columnIndexes.length; j++) {
const colIndx = _columnIndexes[j]
newRowDataWithRequiredCols.push(rowData[colIndx])
}
newData.push(newRowDataWithRequiredCols)
newIndex.push(_index[rowIndx])
}
for (let i = 0; i < _columnIndexes.length; i++) {
const colIndx = _columnIndexes[i]
newColumnNames.push(ndFrame.columns[colIndx])
newDtypes.push(ndFrame.dtypes[colIndx])
}
const df = new DataFrame(
newData,
{
index: newIndex,
columns: newColumnNames,
dtypes: newDtypes,
config: ndFrame.config
})
return df
}
} | the_stack |
import BigNumber from 'bignumber.js';
import _ from 'lodash';
import { expectThrow, expect, expectBN, expectAssertFailure } from './helpers/Expect';
import initializePerpetual from './helpers/initializePerpetual';
import { ITestContext, perpetualDescribe } from './helpers/perpetualDescribe';
import { ADDRESSES, INTEGERS } from '../src/lib/Constants';
import {
address,
SoloBridgeTransfer,
TxResult,
SigningMethod,
SignedSoloBridgeTransfer,
SoloBridgeTransferMode,
} from '../src/lib/types';
import {
expectTokenBalances,
expectMarginBalances,
mintAndDeposit,
} from './helpers/balances';
const SOLO_USDC_MARKET = 2;
// Test parameters.
const futureTimestamp = Math.floor(Date.now() / 1000) + 15 * 60;
const pastTimestamp = Math.floor(Date.now() / 1000) - 15 * 60;
const amount = new BigNumber(1e18);
const soloAccountNumber = 5;
const defaultTransferToPerpetual: SoloBridgeTransfer = {
soloAccountNumber,
amount,
soloMarketId: SOLO_USDC_MARKET,
account: ADDRESSES.ZERO, // Set later
perpetual: ADDRESSES.ZERO, // Set later
transferMode: SoloBridgeTransferMode.SOME_TO_PERPETUAL,
salt: INTEGERS.ONES_255,
expiration: futureTimestamp,
};
let defaultTransferToSolo: SoloBridgeTransfer; // Set later
let defaultTransferToPerpetualSigned: SignedSoloBridgeTransfer;
let defaultTransferToSoloSigned: SignedSoloBridgeTransfer;
// Accounts and addresses.
let admin: address;
let account: address;
let otherAddress: address;
let perpetualAddress: address;
let soloAddress: address;
let proxyAddress: address;
async function init(ctx: ITestContext): Promise<void> {
await initializePerpetual(ctx);
// Accounts and addresses.
admin = ctx.accounts[0];
account = ctx.accounts[2];
otherAddress = ctx.accounts[3];
perpetualAddress = ctx.perpetual.contracts.perpetualProxy.options.address;
soloAddress = ctx.perpetual.testing.solo.address;
proxyAddress = ctx.perpetual.soloBridgeProxy.address;
// Initialize test parameters.
defaultTransferToPerpetual.account = account;
defaultTransferToPerpetual.perpetual = perpetualAddress;
defaultTransferToSolo = {
...defaultTransferToPerpetual,
transferMode: SoloBridgeTransferMode.SOME_TO_SOLO,
};
defaultTransferToPerpetualSigned = await ctx.perpetual.soloBridgeProxy.getSignedTransfer(
defaultTransferToPerpetual,
SigningMethod.Hash,
);
defaultTransferToSoloSigned = await ctx.perpetual.soloBridgeProxy.getSignedTransfer(
defaultTransferToSolo,
SigningMethod.Hash,
);
// Set test data on mock Solo contract.
await ctx.perpetual.testing.solo.setTokenAddress(
SOLO_USDC_MARKET,
ctx.perpetual.contracts.testToken.options.address,
);
// Set allowance on Solo and Perpetual for the proxy.
await Promise.all([
ctx.perpetual.soloBridgeProxy.approveMaximumOnSolo(SOLO_USDC_MARKET),
ctx.perpetual.soloBridgeProxy.approveMaximumOnPerpetual(),
]);
// Check initial balances.
await expectTokenBalances(
ctx,
[account, perpetualAddress, soloAddress, proxyAddress],
[0, 0, 0, 0],
);
}
perpetualDescribe('P1SoloBridgeProxy', init, (ctx: ITestContext) => {
describe('off-chain helpers', () => {
it('Signs correctly for hash', async () => {
const signedTransfer = await ctx.perpetual.soloBridgeProxy.getSignedTransfer(
defaultTransferToPerpetual,
SigningMethod.Hash,
);
const isValid = ctx.perpetual.soloBridgeProxy.transferHasValidSignature(signedTransfer);
expect(isValid).to.be.true;
});
it('Signs correctly for typed data', async () => {
const signedTransfer = await ctx.perpetual.soloBridgeProxy.getSignedTransfer(
defaultTransferToPerpetual,
SigningMethod.TypedData,
);
const isValid = ctx.perpetual.soloBridgeProxy.transferHasValidSignature(signedTransfer);
expect(isValid).to.be.true;
});
it('Recognizes invalid signatures', () => {
const badSignatures = [
`0x${'00'.repeat(63)}00`,
`0x${'ab'.repeat(63)}01`,
`0x${'01'.repeat(70)}01`,
];
badSignatures.map((typedSignature) => {
const isValid = ctx.perpetual.soloBridgeProxy.transferHasValidSignature({
...defaultTransferToPerpetual,
typedSignature,
});
expect(isValid).to.be.false;
});
});
});
describe('bridgeTransfer()', () => {
describe('transfer (Solo -> Perpetual)', async () => {
beforeEach(async () => {
// Give the test Solo contract tokens for withdrawal.
await ctx.perpetual.testing.token.mint(
ctx.perpetual.contracts.testToken.options.address,
soloAddress,
amount,
);
});
describe('with signature', async () => {
it('succeeds', async () => {
// Call the function.
const txResult = await ctx.perpetual.soloBridgeProxy.bridgeTransfer(
defaultTransferToPerpetualSigned,
);
// Check logs.
checkLogs(txResult, defaultTransferToPerpetual);
// Check balances.
await expectTokenBalances(
ctx,
[account, perpetualAddress, soloAddress, proxyAddress],
[0, amount, 0, 0],
);
await expectMarginBalances(ctx, txResult, [account], [amount]);
});
it('succeeds in transfer-all mode', async () => {
// Give some extra tokens to the proxy contract. These should be ignored by the transfer.
await ctx.perpetual.testing.token.mint(
ctx.perpetual.contracts.testToken.options.address,
proxyAddress,
12345,
);
// Create a transfer using transfer-all mode.
const transfer = await getModifiedTransferToPerpetual({
transferMode: SoloBridgeTransferMode.ALL_TO_PERPETUAL,
amount: 999, // Amount is ignored in transfer-all mode.
});
// Call the function.
const txResult = await ctx.perpetual.soloBridgeProxy.bridgeTransfer(transfer);
// Check logs.
// Compare against the original transfer object with the amount specified.
checkLogs(txResult, defaultTransferToPerpetual);
// Check balances.
await expectTokenBalances(
ctx,
[account, perpetualAddress, soloAddress, proxyAddress],
[0, amount, 0, 12345],
);
await expectMarginBalances(ctx, txResult, [account], [amount]);
});
it('succeeds with default salt and expiration', async () => {
// Defaults to expiration of zero, indicating no expiration.
const transfer = await getModifiedTransferToPerpetual({
expiration: undefined,
salt: undefined,
});
// Call the function.
const txResult = await ctx.perpetual.soloBridgeProxy.bridgeTransfer(transfer);
// Check logs.
checkLogs(txResult, defaultTransferToPerpetual);
// Check balances.
await expectTokenBalances(
ctx,
[account, perpetualAddress, soloAddress, proxyAddress],
[0, amount, 0, 0],
);
await expectMarginBalances(ctx, txResult, [account], [amount]);
});
it('fails if the transfer amount is greater than the available balance', async () => {
// Set up mock data.
const transfer = await getModifiedTransferToPerpetual({ amount: amount.plus(1) });
// Call the function.
await expectThrow(
ctx.perpetual.soloBridgeProxy.bridgeTransfer(transfer),
'ERC20: transfer amount exceeds balance',
);
});
it('fails if the Solo and Perpetual tokens do not match', async () => {
// Set up mock data.
const transfer = await getModifiedTransferToPerpetual(
{ soloMarketId: SOLO_USDC_MARKET + 1 },
);
// Call the function.
await expectThrow(
ctx.perpetual.soloBridgeProxy.bridgeTransfer(transfer),
'Solo and Perpetual assets are not the same',
);
});
it('fails if the transfer has expired', async () => {
const transfer = await getModifiedTransferToPerpetual({ expiration: pastTimestamp });
await expectThrow(
ctx.perpetual.soloBridgeProxy.bridgeTransfer(transfer),
'Signature has expired',
);
});
it('fails if the signature was already used', async () => {
const transfer = await getModifiedTransferToPerpetual({ amount: amount.div(2) });
await ctx.perpetual.soloBridgeProxy.bridgeTransfer(transfer);
await expectThrow(
ctx.perpetual.soloBridgeProxy.bridgeTransfer(transfer),
'Signature was already used or invalidated',
);
});
it('fails if the signature was invalidated', async () => {
await ctx.perpetual.soloBridgeProxy.invalidateSignature(
defaultTransferToPerpetual,
{ from: account },
);
await expectThrow(
ctx.perpetual.soloBridgeProxy.bridgeTransfer(defaultTransferToPerpetualSigned),
'Signature was already used or invalidated',
);
});
});
describe('without signature', async () => {
it('succeeds regardless of expiration, invalidation, or previous execution', async () => {
const transfer = await getModifiedTransferToPerpetual({
amount: amount.div(2),
expiration: pastTimestamp,
});
await ctx.perpetual.soloBridgeProxy.invalidateSignature(transfer, { from: account });
await ctx.perpetual.soloBridgeProxy.bridgeTransfer(transfer, { from: account });
const txResult = await ctx.perpetual.soloBridgeProxy.bridgeTransfer(
transfer,
{ from: account },
);
// Check balances.
await expectTokenBalances(
ctx,
[account, perpetualAddress, soloAddress, proxyAddress],
[0, amount, 0, 0],
);
await expectMarginBalances(ctx, txResult, [account], [amount]);
});
it('succeeds for account owner', async () => {
// Call the function.
const txResult = await ctx.perpetual.soloBridgeProxy.bridgeTransfer(
defaultTransferToPerpetual,
{ from: account },
);
// Check logs.
checkLogs(txResult, defaultTransferToPerpetual);
// Check balances.
await expectTokenBalances(
ctx,
[account, perpetualAddress, soloAddress, proxyAddress],
[0, amount, 0, 0],
);
await expectMarginBalances(ctx, txResult, [account], [amount]);
});
it('succeeds for Solo local operator', async () => {
// Set up.
await ctx.perpetual.testing.solo.setIsLocalOperator(account, otherAddress, true);
// Call the function.
const txResult = await ctx.perpetual.soloBridgeProxy.bridgeTransfer(
defaultTransferToPerpetual,
{ from: otherAddress },
);
// Check logs.
checkLogs(txResult, defaultTransferToPerpetual);
// Check balances.
await expectTokenBalances(
ctx,
[account, perpetualAddress, soloAddress, proxyAddress],
[0, amount, 0, 0],
);
await expectMarginBalances(ctx, txResult, [account], [amount]);
});
it('succeeds for Solo global operator', async () => {
// Set up.
await ctx.perpetual.testing.solo.setIsGlobalOperator(otherAddress, true);
// Call the function.
const txResult = await ctx.perpetual.soloBridgeProxy.bridgeTransfer(
defaultTransferToPerpetual,
{ from: otherAddress },
);
// Check logs.
checkLogs(txResult, defaultTransferToPerpetual);
// Check balances.
await expectTokenBalances(
ctx,
[account, perpetualAddress, soloAddress, proxyAddress],
[0, amount, 0, 0],
);
await expectMarginBalances(ctx, txResult, [account], [amount]);
});
it('fails for non-owner non-operator account', async () => {
await expectThrow(
ctx.perpetual.soloBridgeProxy.bridgeTransfer(
defaultTransferToPerpetual,
{ from: otherAddress },
),
'Sender does not have account permissions and signature is invalid',
);
});
it('fails for Perpetual local operator', async () => {
// Set up.
await ctx.perpetual.operator.setLocalOperator(otherAddress, true, { from: account });
// Call the function.
await expectThrow(
ctx.perpetual.soloBridgeProxy.bridgeTransfer(
defaultTransferToPerpetual,
{ from: otherAddress },
),
'Sender does not have account permissions and signature is invalid',
);
});
it('fails for Perpetual global operator', async () => {
// Set up.
await ctx.perpetual.admin.setGlobalOperator(otherAddress, true, { from: admin });
// Call the function.
await expectThrow(
ctx.perpetual.soloBridgeProxy.bridgeTransfer(
defaultTransferToPerpetual,
{ from: otherAddress },
),
'Sender does not have account permissions and signature is invalid',
);
});
});
});
describe('transfer (Perpetual -> Solo)', async () => {
beforeEach(async () => {
// Give the account tokens in the Perpetual contract.
await mintAndDeposit(ctx, account, amount);
});
describe('with signature', async () => {
it('succeeds', async () => {
const txResult = await ctx.perpetual.soloBridgeProxy.bridgeTransfer(
defaultTransferToSoloSigned,
);
// Check logs.
checkLogs(txResult, defaultTransferToSolo);
// Check balances.
await expectTokenBalances(
ctx,
[account, perpetualAddress, soloAddress, proxyAddress],
[0, 0, amount, 0],
);
await expectMarginBalances(ctx, txResult, [account], [0]);
});
it('succeeds with default salt and expiration', async () => {
// Defaults to expiration of zero, indicating no expiration.
const transfer = await getModifiedTransferToSolo({
expiration: undefined,
salt: undefined,
});
// Call the function.
const txResult = await ctx.perpetual.soloBridgeProxy.bridgeTransfer(transfer);
// Check logs.
checkLogs(txResult, defaultTransferToSolo);
// Check balances.
await expectTokenBalances(
ctx,
[account, perpetualAddress, soloAddress, proxyAddress],
[0, 0, amount, 0],
);
await expectMarginBalances(ctx, txResult, [account], [0]);
});
it('fails if the transfer amount is greater than the available balance', async () => {
// Set up mock data.
const transfer = await getModifiedTransferToSolo({ amount: amount.plus(1) });
// Call the function.
await expectThrow(
ctx.perpetual.soloBridgeProxy.bridgeTransfer(transfer),
'SafeERC20: low-level call failed',
);
});
it('fails if the Solo and Perpetual tokens do not match', async () => {
// Set up mock data.
const transfer = await getModifiedTransferToSolo(
{ soloMarketId: SOLO_USDC_MARKET + 1 },
);
// Call the function.
await expectThrow(
ctx.perpetual.soloBridgeProxy.bridgeTransfer(transfer),
'Solo and Perpetual assets are not the same',
);
});
it('fails if the transfer has expired', async () => {
const transfer = await getModifiedTransferToSolo({ expiration: pastTimestamp });
await expectThrow(
ctx.perpetual.soloBridgeProxy.bridgeTransfer(transfer),
'Signature has expired',
);
});
it('fails if the signature was already used', async () => {
const transfer = await getModifiedTransferToSolo({ amount: amount.div(2) });
await ctx.perpetual.soloBridgeProxy.bridgeTransfer(transfer);
await expectThrow(
ctx.perpetual.soloBridgeProxy.bridgeTransfer(transfer),
'Signature was already used or invalidated',
);
});
it('fails if the signature was invalidated', async () => {
await ctx.perpetual.soloBridgeProxy.invalidateSignature(
defaultTransferToSolo,
{ from: account },
);
await expectThrow(
ctx.perpetual.soloBridgeProxy.bridgeTransfer(defaultTransferToSoloSigned),
'Signature was already used or invalidated',
);
});
});
describe('without signature', async () => {
it('succeeds regardless of expiration, invalidation, or previous execution', async () => {
const transfer = await getModifiedTransferToSolo({
amount: amount.div(2),
expiration: pastTimestamp,
});
await ctx.perpetual.soloBridgeProxy.invalidateSignature(transfer, { from: account });
await ctx.perpetual.soloBridgeProxy.bridgeTransfer(transfer, { from: account });
const txResult = await ctx.perpetual.soloBridgeProxy.bridgeTransfer(
transfer,
{ from: account },
);
// Check balances.
await expectTokenBalances(
ctx,
[account, perpetualAddress, soloAddress, proxyAddress],
[0, 0, amount, 0],
);
await expectMarginBalances(ctx, txResult, [account], [0]);
});
it('succeeds for account owner', async () => {
// Call the function.
const txResult = await ctx.perpetual.soloBridgeProxy.bridgeTransfer(
defaultTransferToSolo,
{ from: account },
);
// Check logs.
checkLogs(txResult, defaultTransferToSolo);
// Check balances.
await expectTokenBalances(
ctx,
[account, perpetualAddress, soloAddress, proxyAddress],
[0, 0, amount, 0],
);
await expectMarginBalances(ctx, txResult, [account], [0]);
});
it('succeeds for Perpetual and Solo local operator', async () => {
// Set up.
await ctx.perpetual.operator.setLocalOperator(otherAddress, true, { from: account });
await ctx.perpetual.testing.solo.setIsLocalOperator(account, otherAddress, true);
// Call the function.
const txResult = await ctx.perpetual.soloBridgeProxy.bridgeTransfer(
defaultTransferToSolo,
{ from: otherAddress },
);
// Check logs.
checkLogs(txResult, defaultTransferToSolo);
// Check balances.
await expectTokenBalances(
ctx,
[account, perpetualAddress, soloAddress, proxyAddress],
[0, 0, amount, 0],
);
await expectMarginBalances(ctx, txResult, [account], [0]);
});
it('succeeds for Perpetual and Solo global operator', async () => {
// Set up.
await ctx.perpetual.admin.setGlobalOperator(otherAddress, true, { from: admin });
await ctx.perpetual.testing.solo.setIsGlobalOperator(otherAddress, true);
// Call the function.
const txResult = await ctx.perpetual.soloBridgeProxy.bridgeTransfer(
defaultTransferToSolo,
{ from: otherAddress },
);
// Check logs.
checkLogs(txResult, defaultTransferToSolo);
// Check balances.
await expectTokenBalances(
ctx,
[account, perpetualAddress, soloAddress, proxyAddress],
[0, 0, amount, 0],
);
await expectMarginBalances(ctx, txResult, [account], [0]);
});
it('fails for non-owner non-operator account', async () => {
await expectThrow(
ctx.perpetual.soloBridgeProxy.bridgeTransfer(
defaultTransferToSolo,
{ from: otherAddress },
),
'Sender does not have account permissions and signature is invalid',
);
});
it('fails for Perpetual local operator', async () => {
// Set up.
await ctx.perpetual.operator.setLocalOperator(otherAddress, true, { from: account });
// Call the function.
await expectThrow(
ctx.perpetual.soloBridgeProxy.bridgeTransfer(
defaultTransferToSolo,
{ from: otherAddress },
),
'Sender does not have account permissions and signature is invalid',
);
});
it('fails for Perpetual global operator', async () => {
// Set up.
await ctx.perpetual.admin.setGlobalOperator(otherAddress, true, { from: admin });
// Call the function.
await expectThrow(
ctx.perpetual.soloBridgeProxy.bridgeTransfer(
defaultTransferToSolo,
{ from: otherAddress },
),
'Sender does not have account permissions and signature is invalid',
);
});
it('fails for Solo local operator', async () => {
// Set up.
await ctx.perpetual.testing.solo.setIsLocalOperator(account, otherAddress, true);
// Call the function.
await expectThrow(
ctx.perpetual.soloBridgeProxy.bridgeTransfer(
defaultTransferToSolo,
{ from: otherAddress },
),
'Sender does not have account permissions and signature is invalid',
);
});
it('fails for Solo global operator', async () => {
// Set up.
await ctx.perpetual.testing.solo.setIsGlobalOperator(otherAddress, true);
// Call the function.
await expectThrow(
ctx.perpetual.soloBridgeProxy.bridgeTransfer(
defaultTransferToSolo,
{ from: otherAddress },
),
'Sender does not have account permissions and signature is invalid',
);
});
});
});
});
describe('invalidateSignature()', () => {
describe('invalidating a signature (Solo -> Perpetual)', async () => {
it('succeeds for account owner', async () => {
// Call the function.
const txResult = await ctx.perpetual.soloBridgeProxy.invalidateSignature(
defaultTransferToPerpetual,
{ from: account },
);
// Check logs.
const logs = await ctx.perpetual.logs.parseLogs(txResult);
expect(logs.length).to.equal(1);
const log = logs[0];
expect(log.name).to.equal('LogSignatureInvalidated');
expect(log.args.account).to.equal(defaultTransferToPerpetual.account);
expect(log.args.transferHash).to.equal(
ctx.perpetual.soloBridgeProxy.getTransferHash(defaultTransferToPerpetual),
);
});
it('succeeds for account owner (transfer-all mode)', async () => {
const transfer = await getModifiedTransferToPerpetual({
transferMode: SoloBridgeTransferMode.ALL_TO_PERPETUAL,
amount: 123, // Amount is ignored in transfer-all mode.
});
// Call the function.
const txResult = await ctx.perpetual.soloBridgeProxy.invalidateSignature(
transfer,
{ from: account },
);
// Check logs.
const logs = await ctx.perpetual.logs.parseLogs(txResult);
expect(logs.length).to.equal(1);
const log = logs[0];
expect(log.name).to.equal('LogSignatureInvalidated');
expect(log.args.account).to.equal(transfer.account);
expect(log.args.transferHash).to.equal(
ctx.perpetual.soloBridgeProxy.getTransferHash(transfer),
);
});
it('succeeds for Solo local operator', async () => {
// Set up.
await ctx.perpetual.testing.solo.setIsLocalOperator(account, otherAddress, true);
// Call the function.
const txResult = await ctx.perpetual.soloBridgeProxy.invalidateSignature(
defaultTransferToPerpetual,
{ from: otherAddress },
);
// Check logs.
const logs = await ctx.perpetual.logs.parseLogs(txResult);
expect(logs.length).to.equal(1);
const log = logs[0];
expect(log.name).to.equal('LogSignatureInvalidated');
expect(log.args.account).to.equal(defaultTransferToPerpetual.account);
expect(log.args.transferHash).to.equal(
ctx.perpetual.soloBridgeProxy.getTransferHash(defaultTransferToPerpetual),
);
});
it('succeeds for Solo global operator', async () => {
// Set up.
await ctx.perpetual.testing.solo.setIsGlobalOperator(otherAddress, true);
// Call the function.
const txResult = await ctx.perpetual.soloBridgeProxy.invalidateSignature(
defaultTransferToPerpetual,
{ from: otherAddress },
);
// Check logs.
const logs = await ctx.perpetual.logs.parseLogs(txResult);
expect(logs.length).to.equal(1);
const log = logs[0];
expect(log.name).to.equal('LogSignatureInvalidated');
expect(log.args.account).to.equal(defaultTransferToPerpetual.account);
expect(log.args.transferHash).to.equal(
ctx.perpetual.soloBridgeProxy.getTransferHash(defaultTransferToPerpetual),
);
});
it('fails for non-owner non-operator account', async () => {
await expectThrow(
ctx.perpetual.soloBridgeProxy.invalidateSignature(
defaultTransferToPerpetual,
{ from: otherAddress },
),
'Sender does not have permission to invalidate',
);
});
it('fails for Perpetual local operator', async () => {
// Set up.
await ctx.perpetual.operator.setLocalOperator(otherAddress, true, { from: account });
// Call the function.
await expectThrow(
ctx.perpetual.soloBridgeProxy.invalidateSignature(
defaultTransferToPerpetual,
{ from: otherAddress },
),
'Sender does not have permission to invalidate',
);
});
it('fails for Perpetual global operator', async () => {
// Set up.
await ctx.perpetual.admin.setGlobalOperator(otherAddress, true, { from: admin });
// Call the function.
await expectThrow(
ctx.perpetual.soloBridgeProxy.invalidateSignature(
defaultTransferToPerpetual,
{ from: otherAddress },
),
'Sender does not have permission to invalidate',
);
});
});
describe('invalidating a signature (Perpetual -> Solo)', async () => {
it('succeeds for account owner', async () => {
// Call the function.
const txResult = await ctx.perpetual.soloBridgeProxy.invalidateSignature(
defaultTransferToSolo,
{ from: account },
);
// Check logs.
const logs = await ctx.perpetual.logs.parseLogs(txResult);
expect(logs.length).to.equal(1);
const log = logs[0];
expect(log.name).to.equal('LogSignatureInvalidated');
expect(log.args.account).to.equal(defaultTransferToSolo.account);
expect(log.args.transferHash).to.equal(
ctx.perpetual.soloBridgeProxy.getTransferHash(defaultTransferToSolo),
);
});
it('succeeds for Perpetual and Solo local operator', async () => {
// Set up.
await ctx.perpetual.operator.setLocalOperator(otherAddress, true, { from: account });
await ctx.perpetual.testing.solo.setIsLocalOperator(account, otherAddress, true);
// Call the function.
const txResult = await ctx.perpetual.soloBridgeProxy.invalidateSignature(
defaultTransferToSolo,
{ from: otherAddress },
);
// Check logs.
const logs = await ctx.perpetual.logs.parseLogs(txResult);
expect(logs.length).to.equal(1);
const log = logs[0];
expect(log.name).to.equal('LogSignatureInvalidated');
expect(log.args.account).to.equal(defaultTransferToSolo.account);
expect(log.args.transferHash).to.equal(
ctx.perpetual.soloBridgeProxy.getTransferHash(defaultTransferToSolo),
);
});
it('succeeds for Perpetual and Solo global operator', async () => {
// Set up.
await ctx.perpetual.admin.setGlobalOperator(otherAddress, true, { from: admin });
await ctx.perpetual.testing.solo.setIsGlobalOperator(otherAddress, true);
// Call the function.
const txResult = await ctx.perpetual.soloBridgeProxy.invalidateSignature(
defaultTransferToSolo,
{ from: otherAddress },
);
// Check logs.
const logs = await ctx.perpetual.logs.parseLogs(txResult);
expect(logs.length).to.equal(1);
const log = logs[0];
expect(log.name).to.equal('LogSignatureInvalidated');
expect(log.args.account).to.equal(defaultTransferToSolo.account);
expect(log.args.transferHash).to.equal(
ctx.perpetual.soloBridgeProxy.getTransferHash(defaultTransferToSolo),
);
});
it('fails for non-owner non-operator account', async () => {
await expectThrow(
ctx.perpetual.soloBridgeProxy.invalidateSignature(
defaultTransferToSolo,
{ from: otherAddress },
),
'Sender does not have permission to invalidate',
);
});
it('fails for Perpetual local operator', async () => {
// Set up.
await ctx.perpetual.operator.setLocalOperator(otherAddress, true, { from: account });
// Call the function.
await expectThrow(
ctx.perpetual.soloBridgeProxy.invalidateSignature(
defaultTransferToSolo,
{ from: otherAddress },
),
'Sender does not have permission to invalidate',
);
});
it('fails for Perpetual global operator', async () => {
// Set up.
await ctx.perpetual.admin.setGlobalOperator(otherAddress, true, { from: admin });
// Call the function.
await expectThrow(
ctx.perpetual.soloBridgeProxy.invalidateSignature(
defaultTransferToSolo,
{ from: otherAddress },
),
'Sender does not have permission to invalidate',
);
});
it('fails for Solo local operator', async () => {
// Set up.
await ctx.perpetual.testing.solo.setIsLocalOperator(account, otherAddress, true);
// Call the function.
await expectThrow(
ctx.perpetual.soloBridgeProxy.invalidateSignature(
defaultTransferToSolo,
{ from: otherAddress },
),
'Sender does not have permission to invalidate',
);
});
it('fails for Solo global operator', async () => {
// Set up.
await ctx.perpetual.testing.solo.setIsGlobalOperator(otherAddress, true);
// Call the function.
await expectThrow(
ctx.perpetual.soloBridgeProxy.invalidateSignature(
defaultTransferToSolo,
{ from: otherAddress },
),
'Sender does not have permission to invalidate',
);
});
});
it('fails if the transfer mode is invalid', async () => {
const transfer = await getModifiedTransferToPerpetual({ transferMode: 3 });
await expectAssertFailure(
ctx.perpetual.soloBridgeProxy.bridgeTransfer(transfer),
);
});
});
// ============ Helper Functions ============
function getModifiedTransferToPerpetual(
args: Partial<SignedSoloBridgeTransfer>,
): Promise<SignedSoloBridgeTransfer> {
const newTransfer: SoloBridgeTransfer = {
...defaultTransferToPerpetual,
...args,
};
return ctx.perpetual.soloBridgeProxy.getSignedTransfer(newTransfer, SigningMethod.Hash);
}
function getModifiedTransferToSolo(
args: Partial<SignedSoloBridgeTransfer>,
): Promise<SignedSoloBridgeTransfer> {
const newTransfer: SoloBridgeTransfer = {
...defaultTransferToSolo,
...args,
};
return ctx.perpetual.soloBridgeProxy.getSignedTransfer(newTransfer, SigningMethod.Hash);
}
function checkLogs(
txResult: TxResult,
transfer: SoloBridgeTransfer,
): void {
const logs = ctx.perpetual.logs.parseLogs(txResult);
const toPerpetual = transfer.transferMode !== SoloBridgeTransferMode.SOME_TO_SOLO;
const transferLogs = _.filter(logs, { name: 'LogTransferred' });
expect(transferLogs.length, 'log transfer count').to.equal(1);
const transferLog = transferLogs[0];
expect(transferLog.args.account, 'log account').to.equal(transfer.account);
expect(transferLog.args.perpetual, 'log perpetual').to.equal(transfer.perpetual);
expectBN(transferLog.args.soloAccountNumber, 'log soloAccountNumber').to.equal(
transfer.soloAccountNumber,
);
expectBN(transferLog.args.soloMarketId, 'log soloMarketId').to.equal(transfer.soloMarketId);
expect(transferLog.args.toPerpetual, 'log toPerpetual').to.equal(toPerpetual);
expectBN(transferLog.args.amount, 'log amount').to.equal(transfer.amount);
if (toPerpetual) {
const depositLogs = _.filter(logs, { name: 'LogDeposit' });
expect(depositLogs.length, 'log deposit count').to.equal(1);
const depositLog = depositLogs[0];
expect(depositLog.args.account, 'log deposit account').to.equal(transfer.account);
expectBN(depositLog.args.amount, 'log deposit amount').to.equal(transfer.amount);
} else {
const withdrawalLogs = _.filter(logs, { name: 'LogWithdraw' });
expect(withdrawalLogs.length, 'log withdrawal count').to.equal(1);
const withdrawalLog = withdrawalLogs[0];
expect(withdrawalLog.args.account, 'log withdrawal account').to.equal(transfer.account);
expect(withdrawalLog.args.destination, 'log withdrawal destination').to.equal(
ctx.perpetual.soloBridgeProxy.address,
);
expectBN(withdrawalLog.args.amount, 'log withdrawal amount').to.equal(transfer.amount);
}
}
}); | the_stack |
import base64url from 'base64url';
import { toBigIntBE } from 'bigint-buffer';
import { Multiaddr, protocols } from 'multiaddr';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore: No types available
import muConvert from 'multiaddr/src/convert';
import PeerId from 'peer-id';
import * as RLP from 'rlp';
import { encode as varintEncode } from 'varint';
import {
ERR_INVALID_ID,
ERR_NO_SIGNATURE,
MAX_RECORD_SIZE,
MULTIADDR_LENGTH_SIZE,
} from './constants';
import {
createKeypair,
createKeypairFromPeerId,
createPeerIdFromKeypair,
IKeypair,
KeypairType,
} from './keypair';
import { ENRKey, ENRValue, NodeId, SequenceNumber } from './types';
import * as v4 from './v4';
export class ENR extends Map<ENRKey, ENRValue> {
public seq: SequenceNumber;
public signature: Buffer | null;
constructor(
kvs: Record<ENRKey, ENRValue> = {},
seq: SequenceNumber = 1n,
signature: Buffer | null = null
) {
super(Object.entries(kvs));
this.seq = seq;
this.signature = signature;
}
static createV4(publicKey: Buffer, kvs: Record<ENRKey, ENRValue> = {}): ENR {
return new ENR({
...kvs,
id: Buffer.from('v4'),
secp256k1: publicKey,
});
}
static createFromPeerId(
peerId: PeerId,
kvs: Record<ENRKey, ENRValue> = {}
): ENR {
const keypair = createKeypairFromPeerId(peerId);
switch (keypair.type) {
case KeypairType.secp256k1:
return ENR.createV4(keypair.publicKey, kvs);
default:
throw new Error();
}
}
static decodeFromValues(decoded: Buffer[]): ENR {
if (!Array.isArray(decoded)) {
throw new Error('Decoded ENR must be an array');
}
if (decoded.length % 2 !== 0) {
throw new Error('Decoded ENR must have an even number of elements');
}
const [signature, seq, ...kvs] = decoded;
if (!signature || Array.isArray(signature)) {
throw new Error('Decoded ENR invalid signature: must be a byte array');
}
if (!seq || Array.isArray(seq)) {
throw new Error(
'Decoded ENR invalid sequence number: must be a byte array'
);
}
const obj: Record<ENRKey, ENRValue> = {};
for (let i = 0; i < kvs.length; i += 2) {
obj[kvs[i].toString()] = Buffer.from(kvs[i + 1]);
}
const enr = new ENR(obj, toBigIntBE(seq), signature);
if (!enr.verify(RLP.encode([seq, ...kvs]), signature)) {
throw new Error('Unable to verify ENR signature');
}
return enr;
}
static decode(encoded: Buffer): ENR {
const decoded = RLP.decode(encoded) as unknown as Buffer[];
return ENR.decodeFromValues(decoded);
}
static decodeTxt(encoded: string): ENR {
if (!encoded.startsWith('enr:')) {
throw new Error("string encoded ENR must start with 'enr:'");
}
return ENR.decode(base64url.toBuffer(encoded.slice(4)));
}
set(k: ENRKey, v: ENRValue): this {
this.signature = null;
this.seq++;
return super.set(k, v);
}
get id(): string {
const id = this.get('id') as Buffer;
if (!id) throw new Error('id not found.');
return id.toString('utf8');
}
get keypairType(): KeypairType {
switch (this.id) {
case 'v4':
return KeypairType.secp256k1;
default:
throw new Error(ERR_INVALID_ID);
}
}
get publicKey(): Buffer {
switch (this.id) {
case 'v4':
return this.get('secp256k1') as Buffer;
default:
throw new Error(ERR_INVALID_ID);
}
}
get keypair(): IKeypair {
return createKeypair(this.keypairType, undefined, this.publicKey);
}
async peerId(): Promise<PeerId> {
return createPeerIdFromKeypair(this.keypair);
}
get nodeId(): NodeId {
switch (this.id) {
case 'v4':
return v4.nodeId(this.publicKey);
default:
throw new Error(ERR_INVALID_ID);
}
}
get ip(): string | undefined {
const raw = this.get('ip');
if (raw) {
return muConvert.toString(protocols.names.ip4.code, raw) as string;
} else {
return undefined;
}
}
set ip(ip: string | undefined) {
if (ip) {
this.set('ip', muConvert.toBytes(protocols.names.ip4.code, ip));
} else {
this.delete('ip');
}
}
get tcp(): number | undefined {
const raw = this.get('tcp');
if (raw) {
return Number(muConvert.toString(protocols.names.tcp.code, raw));
} else {
return undefined;
}
}
set tcp(port: number | undefined) {
if (port === undefined) {
this.delete('tcp');
} else {
this.set('tcp', muConvert.toBytes(protocols.names.tcp.code, port));
}
}
get udp(): number | undefined {
const raw = this.get('udp');
if (raw) {
return Number(muConvert.toString(protocols.names.udp.code, raw));
} else {
return undefined;
}
}
set udp(port: number | undefined) {
if (port === undefined) {
this.delete('udp');
} else {
this.set('udp', muConvert.toBytes(protocols.names.udp.code, port));
}
}
get ip6(): string | undefined {
const raw = this.get('ip6');
if (raw) {
return muConvert.toString(protocols.names.ip6.code, raw) as string;
} else {
return undefined;
}
}
set ip6(ip: string | undefined) {
if (ip) {
this.set('ip6', muConvert.toBytes(protocols.names.ip6.code, ip));
} else {
this.delete('ip6');
}
}
get tcp6(): number | undefined {
const raw = this.get('tcp6');
if (raw) {
return Number(muConvert.toString(protocols.names.tcp.code, raw));
} else {
return undefined;
}
}
set tcp6(port: number | undefined) {
if (port === undefined) {
this.delete('tcp6');
} else {
this.set('tcp6', muConvert.toBytes(protocols.names.tcp.code, port));
}
}
get udp6(): number | undefined {
const raw = this.get('udp6');
if (raw) {
return Number(muConvert.toString(protocols.names.udp.code, raw));
} else {
return undefined;
}
}
set udp6(port: number | undefined) {
if (port === undefined) {
this.delete('udp6');
} else {
this.set('udp6', muConvert.toBytes(protocols.names.udp.code, port));
}
}
/**
* Get the `multiaddrs` field from ENR.
*
* This field is used to store multiaddresses that cannot be stored with the current ENR pre-defined keys.
* These can be a multiaddresses that include encapsulation (e.g. wss) or do not use `ip4` nor `ip6` for the host
* address (e.g. `dns4`, `dnsaddr`, etc)..
*
* If the peer information only contains information that can be represented with the ENR pre-defined keys
* (ip, tcp, etc) then the usage of [[getLocationMultiaddr]] should be preferred.
*
* The multiaddresses stored in this field are expected to be location multiaddresses, ie, peer id less.
*/
get multiaddrs(): Multiaddr[] | undefined {
const raw = this.get('multiaddrs');
if (raw) {
const multiaddrs = [];
try {
let index = 0;
while (index < raw.length) {
const sizeBytes = raw.slice(index, index + 2);
const size = Buffer.from(sizeBytes).readUInt16BE(0);
const multiaddrBytes = raw.slice(
index + MULTIADDR_LENGTH_SIZE,
index + size + MULTIADDR_LENGTH_SIZE
);
const multiaddr = new Multiaddr(multiaddrBytes);
multiaddrs.push(multiaddr);
index += size + MULTIADDR_LENGTH_SIZE;
}
} catch (e) {
throw new Error('Invalid value in multiaddrs field');
}
return multiaddrs;
} else {
return undefined;
}
}
/**
* Set the `multiaddrs` field on the ENR.
*
* This field is used to store multiaddresses that cannot be stored with the current ENR pre-defined keys.
* These can be a multiaddresses that include encapsulation (e.g. wss) or do not use `ip4` nor `ip6` for the host
* address (e.g. `dns4`, `dnsaddr`, etc)..
*
* If the peer information only contains information that can be represented with the ENR pre-defined keys
* (ip, tcp, etc) then the usage of [[setLocationMultiaddr]] should be preferred.
*
* The multiaddresses stored in this field must to be location multiaddresses, ie, peer id less.
*/
set multiaddrs(multiaddrs: Multiaddr[] | undefined) {
if (multiaddrs === undefined) {
this.delete('multiaddrs');
} else {
let multiaddrsBuf = Buffer.from([]);
multiaddrs.forEach((multiaddr) => {
if (multiaddr.getPeerId())
throw new Error('`multiaddr` field MUST not contain peer id');
const bytes = multiaddr.bytes;
let buf = Buffer.alloc(2);
// Prepend the size of the next entry
const written = buf.writeUInt16BE(bytes.length, 0);
if (written !== MULTIADDR_LENGTH_SIZE) {
throw new Error(
`Internal error: unsigned 16-bit integer was not written in ${MULTIADDR_LENGTH_SIZE} bytes`
);
}
buf = Buffer.concat([buf, bytes]);
multiaddrsBuf = Buffer.concat([multiaddrsBuf, buf]);
});
this.set('multiaddrs', multiaddrsBuf);
}
}
getLocationMultiaddr(
protocol: 'udp' | 'udp4' | 'udp6' | 'tcp' | 'tcp4' | 'tcp6'
): Multiaddr | undefined {
if (protocol === 'udp') {
return (
this.getLocationMultiaddr('udp4') || this.getLocationMultiaddr('udp6')
);
}
if (protocol === 'tcp') {
return (
this.getLocationMultiaddr('tcp4') || this.getLocationMultiaddr('tcp6')
);
}
const isIpv6 = protocol.endsWith('6');
const ipVal = this.get(isIpv6 ? 'ip6' : 'ip');
if (!ipVal) {
return undefined;
}
const isUdp = protocol.startsWith('udp');
const isTcp = protocol.startsWith('tcp');
let protoName, protoVal;
if (isUdp) {
protoName = 'udp';
protoVal = isIpv6 ? this.get('udp6') : this.get('udp');
} else if (isTcp) {
protoName = 'tcp';
protoVal = isIpv6 ? this.get('tcp6') : this.get('tcp');
} else {
return undefined;
}
if (!protoVal) {
return undefined;
}
// Create raw multiaddr buffer
// multiaddr length is:
// 1 byte for the ip protocol (ip4 or ip6)
// N bytes for the ip address
// 1 or 2 bytes for the protocol as buffer (tcp or udp)
// 2 bytes for the port
const ipMa = protocols.names[isIpv6 ? 'ip6' : 'ip4'];
const ipByteLen = ipMa.size / 8;
const protoMa = protocols.names[protoName];
const protoBuf = varintEncode(protoMa.code);
const maBuf = new Uint8Array(3 + ipByteLen + protoBuf.length);
maBuf[0] = ipMa.code;
maBuf.set(ipVal, 1);
maBuf.set(protoBuf, 1 + ipByteLen);
maBuf.set(protoVal, 1 + ipByteLen + protoBuf.length);
return new Multiaddr(maBuf);
}
setLocationMultiaddr(multiaddr: Multiaddr): void {
const protoNames = multiaddr.protoNames();
if (
protoNames.length !== 2 &&
protoNames[1] !== 'udp' &&
protoNames[1] !== 'tcp'
) {
throw new Error('Invalid multiaddr');
}
const tuples = multiaddr.tuples();
if (!tuples[0][1] || !tuples[1][1]) {
throw new Error('Invalid multiaddr');
}
// IPv4
if (tuples[0][0] === 4) {
this.set('ip', tuples[0][1]);
this.set(protoNames[1], tuples[1][1]);
} else {
this.set('ip6', tuples[0][1]);
this.set(protoNames[1] + '6', tuples[1][1]);
}
}
async getFullMultiaddr(
protocol: 'udp' | 'udp4' | 'udp6' | 'tcp' | 'tcp4' | 'tcp6'
): Promise<Multiaddr | undefined> {
const locationMultiaddr = this.getLocationMultiaddr(protocol);
if (locationMultiaddr) {
const peerId = await this.peerId();
return locationMultiaddr.encapsulate(`/p2p/${peerId.toB58String()}`);
}
return;
}
verify(data: Buffer, signature: Buffer): boolean {
if (!this.get('id') || this.id !== 'v4') {
throw new Error(ERR_INVALID_ID);
}
if (!this.publicKey) {
throw new Error('Failed to verify enr: No public key');
}
return v4.verify(this.publicKey, data, signature);
}
sign(data: Buffer, privateKey: Buffer): Buffer {
switch (this.id) {
case 'v4':
this.signature = v4.sign(privateKey, data);
break;
default:
throw new Error(ERR_INVALID_ID);
}
return this.signature;
}
encodeToValues(privateKey?: Buffer): (ENRKey | ENRValue | number)[] {
// sort keys and flatten into [k, v, k, v, ...]
const content: Array<ENRKey | ENRValue | number> = Array.from(this.keys())
.sort((a, b) => a.localeCompare(b))
.map((k) => [k, this.get(k)] as [ENRKey, ENRValue])
.flat();
content.unshift(Number(this.seq));
if (privateKey) {
content.unshift(this.sign(RLP.encode(content), privateKey));
} else {
if (!this.signature) {
throw new Error(ERR_NO_SIGNATURE);
}
content.unshift(this.signature);
}
return content;
}
encode(privateKey?: Buffer): Buffer {
const encoded = RLP.encode(this.encodeToValues(privateKey));
if (encoded.length >= MAX_RECORD_SIZE) {
throw new Error('ENR must be less than 300 bytes');
}
return encoded;
}
encodeTxt(privateKey?: Buffer): string {
return 'enr:' + base64url.encode(this.encode(privateKey));
}
} | the_stack |
import * as m4 from "./m4";
let LAF = 0;
export function cubeRotationRotation(canvas) {
function main() {
var gl = canvas.getContext("webgl");
if (!gl) {
return;
}
const vertexShader3d = `
attribute vec4 a_position;
attribute vec2 a_texcoord;
uniform mat4 u_matrix;
varying vec2 v_texcoord;
void main() {
// Multiply the position by the matrix.
gl_Position = u_matrix * a_position;
// Pass the texcoord to the fragment shader.
v_texcoord = a_texcoord;
}`;
const fragmentShader3d = `
precision mediump float;
// Passed in from the vertex shader.
varying vec2 v_texcoord;
// The texture.
uniform sampler2D u_texture;
void main() {
gl_FragColor = texture2D(u_texture, v_texcoord);
}`;
// setup GLSL program
// Create the shader object
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
// Load the shader source
gl.shaderSource(vertexShader, vertexShader3d);
// Compile the shader
gl.compileShader(vertexShader);
// Check the compile status
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 shader '" + vertexShader + "':" + lastError
);
gl.deleteShader(vertexShader);
return null;
}
// Create the shader object
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
// Load the shader source
gl.shaderSource(fragmentShader, fragmentShader3d);
// Compile the shader
gl.compileShader(fragmentShader);
// Check the compile status
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 shader '" + fragmentShader + "':" + lastError
);
gl.deleteShader(fragmentShader);
return null;
}
const 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 positionLocation = gl.getAttribLocation(program, "a_position");
var texcoordLocation = gl.getAttribLocation(program, "a_texcoord");
// lookup uniforms
var matrixLocation = gl.getUniformLocation(program, "u_matrix");
var textureLocation = gl.getUniformLocation(program, "u_texture");
// Create a buffer for positions
var positionBuffer = gl.createBuffer();
// Bind it to ARRAY_BUFFER (think of it as ARRAY_BUFFER = positionBuffer)
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
// Put the positions in the buffer
setGeometry(gl);
// provide texture coordinates for the rectangle.
var texcoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, texcoordBuffer);
// Set Texcoords.
setTexcoords(gl);
// Create a texture.
var texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
{
// fill texture with 3x2 pixels
const level = 0;
const internalFormat = gl.LUMINANCE;
const width = 3;
const height = 2;
const border = 0;
const format = gl.LUMINANCE;
const type = gl.UNSIGNED_BYTE;
const data = new Uint8Array([128, 64, 128, 0, 192, 0]);
const alignment = 1;
gl.pixelStorei(gl.UNPACK_ALIGNMENT, alignment);
gl.texImage2D(
gl.TEXTURE_2D,
level,
internalFormat,
width,
height,
border,
format,
type,
data
);
// set the filtering so we don't need mips and it's not filtered
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
}
// Create a texture to render to
const targetTextureWidth = 256 * 3;
const targetTextureHeight = 256 * 3;
const targetTexture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, targetTexture);
{
// define size and format of level 0
const level = 0;
const internalFormat = gl.RGBA;
const border = 0;
const format = gl.RGBA;
const type = gl.UNSIGNED_BYTE;
const data = null;
gl.texImage2D(
gl.TEXTURE_2D,
level,
internalFormat,
targetTextureWidth,
targetTextureHeight,
border,
format,
type,
data
);
// set the filtering so we don't need mips
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
}
// Create and bind the framebuffer
const fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
// attach the texture as the first color attachment
const attachmentPoint = gl.COLOR_ATTACHMENT0;
const level = 0;
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
attachmentPoint,
gl.TEXTURE_2D,
targetTexture,
level
);
function degToRad(d) {
return (d * Math.PI) / 180;
}
var fieldOfViewRadians = degToRad(60);
var modelXRotationRadians = degToRad(0);
var modelYRotationRadians = degToRad(0);
// Get the starting time.
var then = 0;
requestAnimationFrame(drawScene);
function drawCube(aspect) {
// Tell it to use our program (pair of shaders)
gl.useProgram(program);
// Turn on the position attribute
gl.enableVertexAttribArray(positionLocation);
// Bind the position buffer.
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
// Tell the position attribute how to get data out of positionBuffer (ARRAY_BUFFER)
var size = 3; // 3 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(
positionLocation,
size,
type,
normalize,
stride,
offset
);
// Turn on the teccord attribute
gl.enableVertexAttribArray(texcoordLocation);
// Bind the position buffer.
gl.bindBuffer(gl.ARRAY_BUFFER, texcoordBuffer);
// Tell the position 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(
texcoordLocation,
size,
type,
normalize,
stride,
offset
);
// Compute the projection matrix
var projectionMatrix = m4.perspective(
fieldOfViewRadians,
aspect,
1,
2000
);
var cameraPosition = [0, 0, 2];
var up = [0, 1, 0];
var target = [0, 0, 0];
// Compute the camera's matrix using look at.
var cameraMatrix = m4.lookAt(cameraPosition, target, up);
// Make a view matrix from the camera matrix.
var viewMatrix = m4.inverse(cameraMatrix);
var viewProjectionMatrix = m4.multiply(projectionMatrix, viewMatrix);
var matrix = m4.xRotate(viewProjectionMatrix, modelXRotationRadians);
matrix = m4.yRotate(matrix, modelYRotationRadians);
// Set the matrix.
gl.uniformMatrix4fv(matrixLocation, false, matrix);
// Tell the shader to use texture unit 0 for u_texture
gl.uniform1i(textureLocation, 0);
// Draw the geometry.
gl.drawArrays(gl.TRIANGLES, 0, 6 * 6);
}
// Draw the scene.
function drawScene(time) {
// convert to seconds
time *= 0.001;
// Subtract the previous time from the current time
var deltaTime = time - then;
// Remember the current time for the next frame.
then = time;
// Animate the rotation
modelYRotationRadians += -0.7 * deltaTime;
modelXRotationRadians += -0.4 * deltaTime;
//webglUtils.resizeCanvasToDisplaySize(gl.canvas);
gl.enable(gl.CULL_FACE);
gl.enable(gl.DEPTH_TEST);
{
// render to our targetTexture by binding the framebuffer
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
// render cube with our 3x2 texture
gl.bindTexture(gl.TEXTURE_2D, texture);
// Tell WebGL how to convert from clip space to pixels
gl.viewport(0, 0, targetTextureWidth, targetTextureHeight);
// Clear the attachment(s).
gl.clearColor(0, 0, 1, 1); // clear to blue
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
const aspect = targetTextureWidth / targetTextureHeight;
drawCube(aspect);
}
{
// render to the canvas
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
// render the cube with the texture we just rendered to
gl.bindTexture(gl.TEXTURE_2D, targetTexture);
// Tell WebGL how to convert from clip space to pixels
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
// Clear the canvas AND the depth buffer.
gl.clearColor(1, 1, 1, 1); // clear to white
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
const aspect = gl.drawingBufferWidth / gl.drawingBufferHeight;
drawCube(aspect);
}
LAF = requestAnimationFrame(drawScene);
}
}
// Fill the buffer with the values that define a cube.
function setGeometry(gl) {
var positions = new Float32Array([
-0.5,
-0.5,
-0.5,
-0.5,
0.5,
-0.5,
0.5,
-0.5,
-0.5,
-0.5,
0.5,
-0.5,
0.5,
0.5,
-0.5,
0.5,
-0.5,
-0.5,
-0.5,
-0.5,
0.5,
0.5,
-0.5,
0.5,
-0.5,
0.5,
0.5,
-0.5,
0.5,
0.5,
0.5,
-0.5,
0.5,
0.5,
0.5,
0.5,
-0.5,
0.5,
-0.5,
-0.5,
0.5,
0.5,
0.5,
0.5,
-0.5,
-0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
-0.5,
-0.5,
-0.5,
-0.5,
0.5,
-0.5,
-0.5,
-0.5,
-0.5,
0.5,
-0.5,
-0.5,
0.5,
0.5,
-0.5,
-0.5,
0.5,
-0.5,
0.5,
-0.5,
-0.5,
-0.5,
-0.5,
-0.5,
0.5,
-0.5,
0.5,
-0.5,
-0.5,
-0.5,
0.5,
-0.5,
0.5,
0.5,
-0.5,
0.5,
-0.5,
0.5,
-0.5,
-0.5,
0.5,
0.5,
-0.5,
0.5,
-0.5,
0.5,
0.5,
-0.5,
0.5,
0.5,
0.5,
-0.5,
0.5,
0.5,
0.5,
]);
gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);
}
// Fill the buffer with texture coordinates the cube.
function setTexcoords(gl) {
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array([
0,
0,
0,
1,
1,
0,
0,
1,
1,
1,
1,
0,
0,
0,
0,
1,
1,
0,
1,
0,
0,
1,
1,
1,
0,
0,
0,
1,
1,
0,
0,
1,
1,
1,
1,
0,
0,
0,
0,
1,
1,
0,
1,
0,
0,
1,
1,
1,
0,
0,
0,
1,
1,
0,
0,
1,
1,
1,
1,
0,
0,
0,
0,
1,
1,
0,
1,
0,
0,
1,
1,
1,
]),
gl.STATIC_DRAW
);
}
main();
}
export function cancelCubeRotationRotation(){
cancelAnimationFrame(LAF);
LAF = 0;
} | the_stack |
(function web() {
"use strict";
let editor:any,
options:any = window.sparser.options,
lang:[string, string, string] = ["", "", ""],
language:string = options.language,
lexer:string = options.lexer;
const sparser:sparser = window.sparser,
def:optionDef = sparser.libs.optionDef,
acetest:boolean = (location.href.toLowerCase().indexOf("ace=false") < 0 && typeof ace === "object"),
aceControl:HTMLInputElement = <HTMLInputElement>document.getElementById("aceControl"),
input:HTMLTextAreaElement = <HTMLTextAreaElement>document.getElementById("input"),
dataarea:HTMLElement = document.getElementById("data"),
datatext:HTMLTextAreaElement = <HTMLTextAreaElement>document.getElementById("datatext"),
element_language:HTMLInputElement = <HTMLInputElement>document.getElementById("option-language"),
element_lexer:HTMLInputElement = <HTMLInputElement>document.getElementById("option-lexer"),
textsize = (navigator.userAgent.indexOf("like Gecko") < 0 && navigator.userAgent.indexOf("Gecko") > 0 && navigator.userAgent.indexOf("Firefox") > 0)
? 13
: 13.33,
// eliminate page navigation by clicking the backspace key
backspace = function web_backspace(event):boolean {
const e = event || window.event,
f = e.srcElement || e.target;
if (e.keyCode === 8 && f.nodeName !== "textarea" && ((f.nodeName === "input" && f.type !== "text") || f.nodeName !== "input")) {
e.preventDefault();
return false;
}
},
saveOptions = function web_saveOptions():void {
options.language = element_language.value;
options.lexer = element_lexer.value;
localStorage.setItem("demo", JSON.stringify(options));
options.language = language;
options.lexer = lexer;
},
// sparser event handler
handler = function web_handler():void {
let output:any,
startTime:number = 0;
const value:string = (acetest === true)
? editor.getValue()
: input.value,
startTotal:number = Math.round(performance.now() * 1000),
builder = function web_handler_builder():void {
let a:number = 0,
body = document.createElement("thead");
const len:number = window.sparser.parse.count + 1,
table = document.createElement("table"),
cell = function web_handler_builder_cell(data:htmlCellBuilder):void {
const el = document.createElement(data.type);
if (data.className !== "") {
el.setAttribute("class", data.className);
}
el.innerHTML = data.text;
data.row.appendChild(el);
},
row = function web_handler_builder_row():void {
const tr = document.createElement("tr");
cell({
text: a.toString(),
type: "th",
row: tr,
className: "numb"
});
cell({
text: output.begin[a].toString(),
type: "td",
row: tr,
className: "numb"
});
cell({
text: output.ender[a].toString(),
type: "td",
row: tr,
className: "numb"
});
cell({
text: output.lexer[a],
type: "td",
row: tr,
className: ""
});
cell({
text: output.lines[a].toString(),
type: "td",
row: tr,
className: "numb"
});
cell({
text: output.stack[a].replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"),
type: "td",
row: tr,
className: ""
});
cell({
text: output.types[a],
type: "td",
row: tr,
className: ""
});
cell({
text: output.token[a].replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"),
type: "td",
row: tr,
className: ""
});
if (a % 2 === 0) {
tr.setAttribute("class", output.lexer[a] + " even");
} else {
tr.setAttribute("class", output.lexer[a] + " odd");
}
body.appendChild(tr);
},
header = function web_handler_builder_header(parent):void {
const tr = document.createElement("tr");
cell({
text: "index",
type: "th",
row: tr,
className: "numb"
});
cell({
text: "begin",
type: "th",
row: tr,
className: "numb"
});
cell({
text: "ender",
type: "th",
row: tr,
className: "numb"
});
cell({
text: "lexer",
type: "th",
row: tr,
className: ""
});
cell({
text: "lines",
type: "th",
row: tr,
className: "numb"
});
cell({
text: "stack",
type: "th",
row: tr,
className: ""
});
cell({
text: "types",
type: "th",
row: tr,
className: ""
});
cell({
text: "token",
type: "th",
row: tr,
className: ""
});
tr.setAttribute("class", "header");
parent.appendChild(tr);
};
header(body);
table.appendChild(body);
body = document.createElement("tbody");
table.appendChild(body);
if (len === 0) {
return;
}
do {
if (a % 100 === 0 && a > 0) {
header(body);
}
row();
a = a + 1;
} while (a < len);
dataarea.innerHTML = "";
dataarea.appendChild(table);
},
lexVal = element_lexer.value.replace(/\s+/g, ""),
langVal = element_language.value.replace(/\s+/g, "");
options.source = value;
language = options.language;
lexer = options.lexer;
saveOptions();
lang = sparser.libs.language.auto(value, "javascript");
options.lexer = (lexVal === "" || lexVal === "auto")
? lang[1]
: lexVal;
if (options.lexer === "javascript") {
options.lexer = "script";
}
if (langVal === "" || langVal === "auto") {
if (editor !== undefined && (acetest === true || lang[0] !== "")) {
if (lang[0] === "vapor" && (/^\s*#/).test(options.source) === false) {
editor.getSession().setMode(`ace/mode/html`);
} else {
editor.getSession().setMode(`ace/mode/${lang[0]}`);
}
}
document.getElementById("language").getElementsByTagName("span")[0].innerHTML = lang[2];
options.language = lang[0];
options.lexer = lang[1];
} else {
document.getElementById("language").getElementsByTagName("span")[0].innerHTML = "";
options.language = langVal;
}
startTime = Math.round(performance.now() * 1000);
output = sparser.parser();
(function web_handler_perfParse() {
const endTime = Math.round(performance.now() * 1000),
time = (endTime - startTime) / 1000;
document.getElementById("timeparse").getElementsByTagName("span")[0].innerHTML = time + " milliseconds.";
}());
if (sparser.parseerror !== "") {
document.getElementById("errors").getElementsByTagName("span")[0].innerHTML = sparser.parseerror.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
} else {
document.getElementById("errors").getElementsByTagName("span")[0].innerHTML = "";
}
if (options.format === "html") {
builder();
} else {
if (typeof output === "object") {
datatext.value = JSON.stringify(output);
} else {
datatext.value = output;
}
}
(function web_handler_perfTotal():void {
const endTime:number = Math.round(performance.now() * 1000),
time:number = (endTime - startTotal) / 1000;
document.getElementById("timetotal").getElementsByTagName("span")[0].innerHTML = time + " milliseconds.";
}());
},
// toggle display of options
toggleOptions = function web_toggleOptions():void {
const toggle:HTMLInputElement = <HTMLInputElement>document.getElementById("toggle-options"),
opts:HTMLElement = document.getElementById("options");
if (toggle.checked === true) {
opts.style.display = "block";
} else {
opts.style.display = "none";
}
localStorage.setItem("toggle-options", toggle.checked.toString());
},
// maintain state by centeralizing interactions and storing options in localStorage
optControls = function web_optControls(event:Event) {
const node:HTMLElement = <HTMLElement>event.srcElement || <HTMLElement>event.target,
sel:HTMLSelectElement = (node.nodeName.toLowerCase() === "select")
? <HTMLSelectElement>node
: null,
input:HTMLInputElement = (node.nodeName.toLowerCase() === "input")
? <HTMLInputElement>node
: null,
id:string = node.getAttribute("id").replace(/option-(((false)|(true))-)?/, ""),
lex:string[] = def[id].lexer,
type:string = def[id].type,
lexlen:number = lex.length,
value:string = (sel === null)
? input.value
: sel[sel.selectedIndex].innerHTML;
let a:number = 0;
if (type === "number" && isNaN(Number(value)) === true) {
return;
}
if (type === "boolean" && value !== "true" && value !== "false") {
return;
}
if (def[id].values !== undefined && def[id].values[value] === undefined) {
if (id !== "format" || (id === "format" && value !== "html")) {
return;
}
}
if (lex[0] === "all") {
if (type === "number") {
options[id] = Number(value);
} else if (type === "boolean") {
if (value === "true") {
options[id] = true;
} else {
options[id] = false;
}
} else {
options[id] = value;
}
} else {
do {
if (type === "number") {
options.lexer_options[lex[a]][id] = Number(value);
} else if (type === "boolean") {
if (value === "true") {
options.lexer_options[lex[a]][id] = true;
} else {
options.lexer_options[lex[a]][id] = false;
}
} else {
options.lexer_options[lex[a]][id] = value;
}
a = a + 1;
} while (a < lexlen);
}
if (id === "format") {
const data:HTMLElement = document.getElementById("data"),
dataparent:HTMLElement = <HTMLElement>data.parentNode,
text:HTMLElement = document.getElementById("datatext"),
textparent:HTMLElement = <HTMLElement>text.parentNode;
if (value === "html") {
dataparent.style.display = "block";
textparent.style.display = "none";
height.html();
} else {
dataparent.style.display = "none";
textparent.style.display = "block";
height.textout();
}
}
saveOptions();
},
// math for vertically scalling the input and output areas
height = {
// actives height scaling for the ace editor
ace: function web_height_ace():void {
document.getElementById("input").style.height = height.math(12, -3.2);
editor.setStyle(`height:${height.math(12, -3.2)}`);
editor.resize();
},
// actives height scaling for the html table output
html: function web_height_html():void {
dataarea.style.height = height.math(10, 0);
},
math: function web_height_math(scale:number, offset:number):string {
const ff:number = (textsize === 13) // variability for Gecko
? (scale === 10) // pull the output down to align to input
? -0.2
: (offset < -4) // pull input down to eliminate a white bar
? 0
: -0.2
: 0;
let heightn:number = Math.max(document.documentElement.scrollHeight, document.getElementsByTagName("body")[0].scrollHeight);
if (heightn > window.innerHeight) {
heightn = window.innerHeight;
}
heightn = (heightn / scale) - (18.975 + offset + ff);
return `${heightn}em`;
},
// actives height scaling for the textarea input
textin: function web_height_textin():void {
input.style.height = height.math(textsize, -4.45);
},
// activates height scaling for the textarea output
textout: function web_height_textout():void {
datatext.style.height = height.math(textsize, -4.45);
}
};
window.onresize = function web_fixHeight():void {
if (typeof ace === "object" && location.href.indexOf("ace=false") < 0) {
height.ace();
} else {
height.textin();
}
if (options.format === "html") {
height.html();
} else {
height.textout();
}
};
document.onkeypress = backspace;
document.onkeydown = backspace;
window.onerror = function web_onerror(msg:string, source:string):void {
document.getElementById("errors").getElementsByTagName("span")[0].innerHTML = msg + " " + source;
};
{ // set option defaults and event handlers
const select:HTMLCollectionOf<HTMLSelectElement> = document.getElementsByTagName("select"),
input:HTMLCollectionOf<HTMLInputElement> = document.getElementsByTagName("input"),
lexkeys:string[] = Object.keys(options.lexer_options),
lexlen:number = lexkeys.length,
inputValues = function web_inputValues(node:HTMLInputElement):void {
const name:string = node.getAttribute("id").replace(/option-(((false)|(true))-)?/, ""),
saved:string|boolean = (function web_selectValues_saved():string|boolean {
let c:number = 0;
if (options[name] !== undefined) {
return options[name];
}
if (options.lexer !== "auto" && options.lexer !== "" && options.lexer_options[options.lexer] !== undefined && options.lexer_options[options.lexer][name] !== undefined) {
return options.lexer_options[options.lexer][name];
}
do {
if (options.lexer_options[lexkeys[c]][name] !== undefined) {
return options.lexer_options[lexkeys[c]][name];
}
c = c + 1;
} while (c < lexlen);
return "";
}());
if (node.type === "text") {
node.onkeyup = optControls;
node.value = String(saved);
} else {
node.onclick = optControls;
if (saved === false && node.getAttribute("id").indexOf("option-false-") === 0) {
node.checked = true;
} else if (saved === true && node.getAttribute("id").indexOf("option-true-") === 0) {
node.checked = true;
}
return;
}
},
selectValues = function web_selectValues(node:HTMLSelectElement):void {
let b:number = 0;
const opts:HTMLCollectionOf<HTMLOptionElement> = node.getElementsByTagName("option"),
olen:number = opts.length,
name:string = node.getAttribute("id").replace("option-", ""),
saved:string = (function web_selectValues_saved():string {
let c:number = 0;
if (name === "format") {
return "html";
}
if (options[name] !== undefined) {
return options[name];
}
if (options.lexer !== "auto" && options.lexer !== "" && options.lexer_options[options.lexer] !== undefined && options.lexer_options[options.lexer][name] !== undefined) {
return options.lexer_options[options.lexer][name];
}
do {
if (options.lexer_options[lexkeys[c]][name] !== undefined) {
return options.lexer_options[lexkeys[c]][name];
}
c = c + 1;
} while (c < lexlen);
return "";
}());
node.onchange = optControls;
do {
if (opts[b].innerHTML === saved) {
node.selectedIndex = b;
break;
}
b = b + 1;
} while (b < olen);
if (name === "format") {
const data:HTMLElement = document.getElementById("data"),
dataparent:HTMLElement = <HTMLElement>data.parentNode,
text:HTMLElement = document.getElementById("datatext"),
textparent:HTMLElement = <HTMLElement>text.parentNode;
if (saved === "html") {
dataparent.style.display = "block";
textparent.style.display = "none";
height.html();
} else {
dataparent.style.display = "none";
textparent.style.display = "block";
height.textout();
}
}
};
let a:number = 0,
len:number = select.length,
id:string = "";
options.format = "html";
if (localStorage.getItem("demo") !== null) {
options = JSON.parse(localStorage.getItem("demo"));
window.sparser.options = options;
}
do {
selectValues(select[a]);
a = a + 1;
} while (a < len);
a = 0;
len = input.length;
do {
id = input[a].getAttribute("id");
if (id.indexOf("ace") !== 0 && id.indexOf("toggle-") !== 0) {
inputValues(input[a]);
}
a = a + 1;
} while (a < len);
if (localStorage.getItem("demo") === null) {
saveOptions();
}
}
{ // evaluate query string of the URI for option assignment
const params:string[] = (location.href.indexOf("?") > 0)
? location.href.split("?")[1].split("&")
: [],
assignValue = function assignValue(object:{}, name:string, value?:string):void {
const type = def[name].type;
if (type === "boolean") {
if (value === undefined || value === "true") {
object[name] = true;
} else if (value === "false") {
object[name] = false;
}
} else if (type === "number" && isNaN(Number(value)) === false) {
object[name] = Number(value);
} else if (type === "string" && value !== undefined) {
if (def[name].values === undefined) {
object[name] = value;
} else if (def[name].values !== undefined) {
object[name] = value;
}
}
};
if (params.length > 1) {
let aa:number = params.length,
bb:number = 0,
lex:string = "",
pair:string[] = [];
if (params[aa - 1].indexOf("#") > 0) {
params[aa - 1] = params[aa - 1].split("#")[0];
}
do {
aa = aa - 1;
pair = params[aa].split("=");
if (def[pair[0]] !== undefined) {
if (def[pair[0]].lexer[0] === "all") {
assignValue(options, pair[0], pair[1]);
} else {
bb = def[pair[0]].lexer.length;
do {
bb = bb - 1;
lex = def[pair[0]].lexer[bb];
assignValue(options.lexer_options[lex][pair[0]], pair[0], pair[1]);
} while (bb > 0);
}
}
} while (aa > 0);
}
}
if (typeof ace === "object") {
aceControl.onclick = function web_aceControl() {
if (aceControl.checked === true) {
location.replace(location.href.replace(/ace=false&?/, "").replace(/\?$/, ""));
} else {
if (location.href.indexOf("?") > 0) {
location.replace(location.href.replace("?", "?ace=false&"));
} else {
location.replace(`${location.href}?ace=false`);
}
}
};
if (location.href.indexOf("ace=false") > 0) {
aceControl.checked = false;
input.onkeyup = handler;
height.textin();
} else {
const div:HTMLDivElement = document.createElement("div"),
parent:HTMLElement = <HTMLElement>input.parentNode.parentNode,
attributes:NamedNodeMap = input.attributes,
dollar:string = "$",
len:number = attributes.length;
let a:number = 0,
edit:any = {},
textarea:HTMLTextAreaElement;
do {
if (attributes[a].name !== "rows" && attributes[a].name !== "cols" && attributes[a].name !== "wrap") {
div.setAttribute(attributes[a].name, attributes[a].value);
}
a = a + 1;
} while (a < len);
parent.removeChild(input.parentNode);
parent.appendChild(div);
edit = ace.edit(div);
textarea = div.getElementsByTagName("textarea")[0];
textarea.onkeyup = handler;
edit.setTheme("ace/theme/textmate");
edit.focus();
edit[`${dollar}blockScrolling`] = Infinity;
editor = edit;
lang = (options.language === "auto" || options.language === "")
? sparser.libs.language.auto(options.source, "javascript")
: [options.language, options.lexer, ""];
editor.setValue(options.source);
if (lang[0] === "vapor" && (/^\s*#/).test(options.source) === false) {
editor.getSession().setMode(`ace/mode/html`);
} else {
editor.getSession().setMode(`ace/mode/${lang[0]}`);
}
editor.clearSelection();
height.ace();
}
} else {
aceControl.checked = false;
input.onkeyup = handler;
input.value = options.source;
height.textin();
}
// web sockets
if (location.href.indexOf("//localhost:") > 0) {
let port:number = (function port():number {
const uri = location.href;
let str:string = uri.slice(location.href.indexOf("host:") + 5),
ind:number = str.indexOf("/");
if (ind > 0) {
str = str.slice(0, ind);
}
ind = str.indexOf("?");
if (ind > 0) {
str = str.slice(0, ind);
}
ind = str.indexOf("#");
if (ind > 0) {
str = str.slice(0, ind);
}
ind = Number(str);
if (isNaN(ind) === true) {
return 8080;
}
return ind;
}()),
ws = new WebSocket("ws://localhost:" + (port + 1));
ws.addEventListener("message", function web_sockets(event) {
if (event.data === "reload") {
location.reload();
}
});
if (location.href.indexOf("scrolldown") > 0) {
const body = document.getElementsByTagName("body")[0],
el = document.getElementById("data");
handler();
body.style.backgroundColor = "#000";
setTimeout(function web_scrolldelay() {
el.scrollTop = el.scrollHeight;
body.style.backgroundColor = "#fff";
}, 200);
}
}
// toggle option display
{
const toggle:HTMLInputElement = <HTMLInputElement>document.getElementById("toggle-options"),
opts:HTMLElement = document.getElementById("options");
toggle.onclick = toggleOptions;
if (localStorage.getItem("toggle-options") === "true" || location.href.indexOf("#options") === location.href.length - 8) {
toggle.checked = true;
opts.style.display = "block";
}
}
}()); | the_stack |
import * as fs from 'fs';
import { bind, each, find, has, includes, isArray, isFunction, kebabCase } from 'lodash';
import * as path from 'path';
import { AsyncSubject, Observable } from 'rxjs';
import { CompositeDisposable, Disposable, IDisposable } from 'ts-disposables';
// TODO: Remove these at some point to stream line startup.
import { Omni } from './server/omni';
const win32 = process.platform === 'win32';
class OmniSharpAtom {
private disposable: CompositeDisposable;
// Internal: Used by unit testing to make sure the plugin is completely activated.
private _started: AsyncSubject<boolean>;
private _activated: AsyncSubject<boolean>;
public activate(state: any) {
this.disposable = new CompositeDisposable();
this._started = new AsyncSubject<boolean>();
this._activated = new AsyncSubject<boolean>();
this.configureKeybindings();
this.disposable.add(atom.commands.add('atom-workspace', 'omnisharp-atom:toggle', () => this.toggle()));
this.disposable.add(atom.commands.add('atom-workspace', 'omnisharp-atom:fix-usings', () => Omni.request(solution => solution.fixusings({}))));
this.disposable.add(atom.commands.add('atom-workspace', 'omnisharp-atom:settings', () => atom.workspace.open('atom://config/packages')
.then(tab => {
if (tab && tab.getURI && tab.getURI() !== 'atom://config/packages/omnisharp-atom') {
atom.workspace.open('atom://config/packages/omnisharp-atom');
}
})));
const grammars = (<any>atom.grammars);
const grammarCb = (grammar: { scopeName: string; }) => {
if (find(Omni.grammars, (gmr: any) => gmr.scopeName === grammar.scopeName)) {
// ensure the scope has been inited
atom.grammars.startIdForScope(grammar.scopeName);
const omnisharpScopeName = `${grammar.scopeName}.omnisharp`;
const scopeId = grammars.idsByScope[grammar.scopeName];
grammars.idsByScope[omnisharpScopeName] = scopeId;
grammars.scopesById[scopeId] = omnisharpScopeName;
grammar.scopeName = omnisharpScopeName;
}
};
each(grammars.grammars, grammarCb);
this.disposable.add(atom.grammars.onDidAddGrammar(grammarCb));
// tslint:disable-next-line:no-require-imports
require('atom-package-deps').install('omnisharp-atom')
.then(() => {
console.info('Activating omnisharp-atom solution tracking...');
Omni.activate();
this.disposable.add(Omni);
this._started.next(true);
this._started.complete();
})
/* tslint:disable:no-string-literal */
.then(() => this.loadFeatures(this.getFeatures('atom').delay(Omni['_kick_in_the_pants_'] ? 0 : 2000)).toPromise())
/* tslint:enable:no-string-literal */
.then(() => {
let startingObservable = Omni.activeSolution
.filter(z => !!z)
.take(1);
/* tslint:disable:no-string-literal */
if (Omni['_kick_in_the_pants_']) {
startingObservable = Observable.of(null);
}
/* tslint:disable:no-string-literal */
// Only activate features once we have a solution!
this.disposable.add(startingObservable
.flatMap(() => this.loadFeatures(this.getFeatures('features')))
.subscribe({
complete: () => {
this.disposable.add(atom.workspace.observeTextEditors((editor: Atom.TextEditor) => {
this.detectAutoToggleGrammar(editor);
}));
this._activated.next(true);
this._activated.complete();
}
}));
});
}
public getFeatures(folder: string) {
const whiteList = atom.config.get<boolean>('omnisharp-atom:feature-white-list');
const featureList = atom.config.get<string[]>('omnisharp-atom:feature-list');
const whiteListUndefined = whiteList === undefined;
console.info(`Getting features for "${folder}"...`);
const featureDir = path.resolve(__dirname, folder);
function loadFeature(file: string) {
// tslint:disable-next-line:no-require-imports non-literal-require
const result = require(`./${folder}/${file}`);
console.info(`Loading feature "${folder}/${file}"...`);
return result; //values(result).filter(feature => !isFunction(feature));
}
return Observable.bindNodeCallback(fs.readdir)(featureDir)
.flatMap(files => files)
.filter(file => /\.js$/.test(file))
.flatMap(file => Observable.bindNodeCallback(fs.stat)(`${featureDir}/${file}`), (file, stat) => ({ file, stat }))
.filter(z => !z.stat.isDirectory())
.map(z => ({
file: `${folder}/${path.basename(z.file)}`.replace(/\.js$/, ''),
load: () => {
const feature = loadFeature(z.file);
const features: { key: string, activate: () => () => void }[] = [];
each(feature, (value: IFeature, key: string) => {
if (!isFunction(value) && !isArray(value)) {
if (!value.required) {
this.config[key] = {
title: `${value.title}`,
description: value.description,
type: 'boolean',
default: (has(value, 'default') ? value.default : true)
};
}
features.push({
key, activate: () => {
return this.activateFeature(whiteListUndefined, key, value);
}
});
}
});
return Observable.from<{ key: string, activate: () => () => void }>(features);
}
}))
.filter(l => {
if (whiteList === undefined) {
return true;
}
if (whiteList) {
return includes(featureList, l.file);
} else {
return !includes(featureList, l.file);
}
});
}
public loadFeatures(features: Observable<{ file: string; load: () => Observable<{ key: string, activate: () => () => void }> }>) {
return features
.concatMap(z => z.load())
.toArray()
.concatMap(x => x)
.map(f => f.activate())
.filter(x => !!x)
.toArray()
.do({
complete: () => {
(<any>atom.config).setSchema('omnisharp-atom', {
type: 'object',
properties: this.config
});
}
})
.concatMap(x => x)
.do(x => x());
}
public activateFeature(whiteListUndefined: boolean, key: string, value: IFeature) {
let result: () => void = null;
let firstRun = true;
// Whitelist is used for unit testing, we don"t want the config to make changes here
if (whiteListUndefined && has(this.config, key)) {
const configKey = `omnisharp-atom.${key}`;
let enableDisposable: IDisposable;
let disableDisposable: IDisposable;
this.disposable.add(atom.config.observe(configKey, enabled => {
if (!enabled) {
if (disableDisposable) {
disableDisposable.dispose();
this.disposable.remove(disableDisposable);
disableDisposable = null;
}
try { value.dispose(); } catch (ex) { /* */ }
enableDisposable = atom.commands.add(
'atom-workspace',
`omnisharp-feature:enable-${kebabCase(key)}`,
() => atom.config.set(configKey, true));
this.disposable.add(enableDisposable);
} else {
if (enableDisposable) {
enableDisposable.dispose();
this.disposable.remove(disableDisposable);
enableDisposable = null;
}
console.info(`Activating feature "${key}"...`);
value.activate();
if (isFunction(value['attach'])) {
if (firstRun) {
result = () => {
console.info(`Attaching feature "${key}"...`);
value['attach']();
};
} else {
console.info(`Attaching feature "${key}"...`);
value['attach']();
}
}
disableDisposable = atom.commands.add('atom-workspace', `omnisharp-feature:disable-${kebabCase(key)}`, () => atom.config.set(configKey, false));
this.disposable.add(disableDisposable);
}
firstRun = false;
}));
this.disposable.add(atom.commands.add('atom-workspace', `omnisharp-feature:toggle-${kebabCase(key)}`, () => atom.config.set(configKey, !atom.config.get(configKey))));
} else {
value.activate();
if (isFunction(value['attach'])) {
result = () => {
console.info(`Attaching feature "${key}"...`);
value['attach']();
};
}
}
this.disposable.add(Disposable.create(() => { try { value.dispose(); } catch (ex) { /* */ } }));
return result;
}
private detectAutoToggleGrammar(editor: Atom.TextEditor) {
const grammar = editor.getGrammar();
this.detectGrammar(editor, grammar);
this.disposable.add(editor.onDidChangeGrammar((gmr: FirstMate.Grammar) => this.detectGrammar(editor, gmr)));
}
private detectGrammar(editor: Atom.TextEditor, grammar: FirstMate.Grammar) {
if (!atom.config.get('omnisharp-atom.autoStartOnCompatibleFile')) {
return; //short out, if setting to not auto start is enabled
}
if (Omni.isValidGrammar(grammar)) {
if (Omni.isOff) {
this.toggle();
}
} else if (grammar.name === 'JSON') {
if (path.basename(editor.getPath()) === 'project.json') {
if (Omni.isOff) {
this.toggle();
}
}
}
}
public toggle() {
if (Omni.isOff) {
Omni.connect();
} else if (Omni.isOn) {
Omni.disconnect();
}
}
public deactivate() {
this.disposable.dispose();
}
public consumeStatusBar(statusBar: any) {
let f = require('./atom/status-bar');
f.statusBar.setup(statusBar);
f = require('./atom/framework-selector');
f.frameworkSelector.setup(statusBar);
f = require('./atom/feature-buttons');
f.featureEditorButtons.setup(statusBar);
}
/* tslint:disable:variable-name */
public consumeYeomanEnvironment(generatorService: any) {
const {generatorAspnet} = require('./atom/generator-aspnet');
generatorAspnet.setup(generatorService);
}
public provideAutocomplete() {
return require('./services/completion-provider');
}
public provideLinter(): any[] {
return [];
//const LinterProvider = require("./services/linter-provider");
//return LinterProvider.provider;
}
public provideProjectJson() {
return require('./services/project-provider').concat(require('./services/framework-provider'));
}
public consumeLinter(linter: any) {
const LinterProvider = require('./services/linter-provider');
const linters = LinterProvider.provider;
this.disposable.add(Disposable.create(() => {
each(linters, l => {
linter.deleteLinter(l);
});
}));
this.disposable.add(LinterProvider.init(linter));
}
public consumeIndieLinter(linter: any) {
require('./services/linter-provider').registerIndie(linter, this.disposable);
}
/* tslint:enable:variable-name */
private configureKeybindings() {
let disposable: EventKit.Disposable;
const omnisharpAdvancedFileNew = Omni.packageDir + '/omnisharp-atom/keymaps/omnisharp-file-new.cson';
this.disposable.add(atom.config.observe('omnisharp-atom.enableAdvancedFileNew', (enabled: boolean) => {
if (enabled) {
disposable = atom.keymaps.loadKeymap(omnisharpAdvancedFileNew);
} else {
if (disposable) disposable.dispose();
atom.keymaps.removeBindingsFromSource(omnisharpAdvancedFileNew);
}
}));
}
public config = {
autoStartOnCompatibleFile: {
title: 'Autostart Omnisharp Roslyn',
description: 'Automatically starts Omnisharp Roslyn when a compatible file is opened.',
type: 'boolean',
default: true
},
developerMode: {
title: 'Developer Mode',
description: 'Outputs detailed server calls in console.log',
type: 'boolean',
default: false
},
showDiagnosticsForAllSolutions: {
title: 'Show Diagnostics for all Solutions',
description: 'Advanced: This will show diagnostics for all open solutions. NOTE: May take a restart or change to each server to take effect when turned on.',
type: 'boolean',
default: false
},
enableAdvancedFileNew: {
title: 'Enable `Advanced File New`',
description: 'Enable `Advanced File New` when doing ctrl-n/cmd-n within a C# editor.',
type: 'boolean',
default: false
},
useLeftLabelColumnForSuggestions: {
title: 'Use Left-Label column in Suggestions',
description: 'Shows return types in a right-aligned column to the left of the completion suggestion text.',
type: 'boolean',
default: false
},
useIcons: {
title: 'Use unique icons for kind indicators in Suggestions',
description: 'Shows kinds with unique icons rather than autocomplete default styles.',
type: 'boolean',
default: true
},
autoAdjustTreeView: {
title: 'Adjust the tree view to match the solution root.',
descrption: 'This will automatically adjust the treeview to be the root of the solution.',
type: 'boolean',
default: false
},
nagAdjustTreeView: {
title: 'Show the notifications to Adjust the tree view',
type: 'boolean',
default: true
},
autoAddExternalProjects: {
title: 'Add external projects to the tree view.',
descrption: 'This will automatically add external sources to the tree view.\n External sources are any projects that are loaded outside of the solution root.',
type: 'boolean',
default: false
},
nagAddExternalProjects: {
title: 'Show the notifications to add or remove external projects',
type: 'boolean',
default: true
},
hideLinterInterface: {
title: 'Hide the linter interface when using omnisharp-atom editors',
type: 'boolean',
default: true
},
wantMetadata: {
title: 'Request metadata definition with Goto Definition',
descrption: 'Request symbol metadata from the server, when using go-to-definition. This is disabled by default on Linux, due to issues with Roslyn on Mono.',
type: 'boolean',
default: win32
},
altGotoDefinition: {
title: 'Alt Go To Definition',
descrption: 'Use the alt key instead of the ctrl/cmd key for goto defintion mouse over.',
type: 'boolean',
default: false
},
showHiddenDiagnostics: {
title: 'Show \'Hidden\' diagnostics in the linter',
descrption: 'Show or hide hidden diagnostics in the linter, this does not affect greying out of namespaces that are unused.',
type: 'boolean',
default: true
}
};
}
module.exports = new OmniSharpAtom; | the_stack |
import './side_panel.css';
import {DisplayContext} from 'neuroglancer/display_context';
import {popDragStatus, pushDragStatus} from 'neuroglancer/ui/drag_and_drop';
import {Side, TrackableSidePanelLocation} from 'neuroglancer/ui/side_panel_location';
import {RefCounted} from 'neuroglancer/util/disposable';
import {updateChildren} from 'neuroglancer/util/dom';
import {startRelativeMouseDrag} from 'neuroglancer/util/mouse_drag';
import {Signal} from 'neuroglancer/util/signal';
import {WatchableVisibilityPriority} from 'neuroglancer/visibility_priority/frontend';
import {makeCloseButton} from 'neuroglancer/widget/close_button';
export const DRAG_OVER_CLASSNAME = 'neuroglancer-drag-over';
type FlexDirection = 'row'|'column';
const LOCATION_KEY_FOR_DIRECTION: Record<FlexDirection, 'row'|'col'> = {
'row': 'row',
'column': 'col'
};
const OPPOSITE_SIDE: Record<Side, Side> = {
'left': 'right',
'right': 'left',
'top': 'bottom',
'bottom': 'top',
};
const FLEX_DIRECTION_FOR_SIDE: Record<Side, FlexDirection> = {
'left': 'column',
'right': 'column',
'top': 'row',
'bottom': 'row',
};
const CROSS_DIRECTION_FOR_SIDE: Record<Side, FlexDirection> = {
'left': 'row',
'right': 'row',
'top': 'column',
'bottom': 'column',
};
const SIZE_FOR_DIRECTION: Record<FlexDirection, 'width'|'height'> = {
'row': 'width',
'column': 'height'
};
const BEGIN_SIDE_FOR_DIRECTION: Record<FlexDirection, Side> = {
'row': 'left',
'column': 'top',
};
const END_SIDE_FOR_DIRECTION: Record<FlexDirection, Side> = {
'row': 'right',
'column': 'bottom',
};
const MARGIN_FOR_SIDE: Record<Side, 'marginLeft'|'marginRight'|'marginTop'|'marginBottom'> = {
'left': 'marginLeft',
'right': 'marginRight',
'top': 'marginTop',
'bottom': 'marginBottom',
};
const OUTWARDS_SIGN_FOR_SIDE: Record<Side, number> = {
'left': -1,
'right': +1,
'top': -1,
'bottom': +1
};
export class SidePanel extends RefCounted {
element: HTMLElement = document.createElement('div');
visibility = new WatchableVisibilityPriority(WatchableVisibilityPriority.VISIBLE);
constructor(
public sidePanelManager: SidePanelManager,
public location: TrackableSidePanelLocation = new TrackableSidePanelLocation()) {
super();
const {element} = this;
element.classList.add('neuroglancer-side-panel');
element.draggable = true;
element.addEventListener('dragstart', (event: DragEvent) => {
this.sidePanelManager.startDrag(this.makeDragSource(), event);
element.style.backgroundColor = 'black';
setTimeout(() => {
element.style.backgroundColor = '';
}, 0);
pushDragStatus(element, 'drag', () => {
return document.createTextNode(
'Drag side panel to move it to the left/right/top/bottom of another panel');
});
});
element.addEventListener('dragend', (event: DragEvent) => {
event;
this.sidePanelManager.endDrag();
popDragStatus(element, 'drag');
});
}
makeDragSource(): DragSource {
return {
dropAsNewPanel: location => {
const oldLocation = this.location.value;
this.location.value = {...oldLocation, ...location};
this.location.locationChanged.dispatch();
}
};
}
close() {
this.location.visible = false;
}
addTitleBar(options: {title?: string}) {
const titleBar = document.createElement('div');
titleBar.classList.add('neuroglancer-side-panel-titlebar');
const {title} = options;
let titleElement: HTMLElement|undefined;
if (title !== undefined) {
titleElement = document.createElement('div');
titleElement.classList.add('neuroglancer-side-panel-title');
titleElement.textContent = title;
titleBar.appendChild(titleElement);
}
const closeButton = makeCloseButton({
title: 'Close panel',
onClick: () => {
this.close();
},
});
closeButton.style.order = '100';
titleBar.appendChild(closeButton);
this.element.appendChild(titleBar);
return {titleBar, titleElement, closeButton};
}
addBody(body: HTMLElement) {
body.draggable = true;
body.addEventListener('dragstart', (event: DragEvent) => {
event.preventDefault();
event.stopPropagation();
});
this.element.appendChild(body);
}
}
interface SidePanelCell {
registeredPanel: RegisteredSidePanel;
gutterElement: HTMLElement|undefined;
}
interface SidePanelFlex {
element: HTMLElement;
visible: boolean;
crossSize: number;
// Maximum minWidth over all visible panels in the column.
minSize: number;
gutterElement: HTMLElement;
cells: SidePanelCell[];
beginDropZone: HTMLElement;
endDropZone: HTMLElement;
}
interface SidePanelSideState {
flexGroups: SidePanelFlex[];
outerDropZoneElement: HTMLElement;
}
export interface SidePanelDropLocation {
side: Side;
row: number;
col: number;
}
export interface DragSource {
canDropAsTabs?: (target: SidePanel) => number;
dropAsTab?: (target: SidePanel) => void;
dropAsNewPanel: (location: SidePanelDropLocation) => void;
}
export interface RegisteredSidePanel {
location: TrackableSidePanelLocation;
makePanel: () => SidePanel;
panel?: SidePanel|undefined;
}
export class SidePanelManager extends RefCounted {
public element = document.createElement('div');
public centerColumn = document.createElement('div');
beforeRender = new Signal();
private sides: Record<Side, SidePanelSideState> = {
'left': this.makeSidePanelSideState('left'),
'right': this.makeSidePanelSideState('right'),
'top': this.makeSidePanelSideState('top'),
'bottom': this.makeSidePanelSideState('bottom'),
};
private registeredPanels = new Set<RegisteredSidePanel>();
dragSource: DragSource|undefined;
private layoutNeedsUpdate = false;
get visible() {
return this.visibility.visible;
}
constructor(
public display: DisplayContext, public center: HTMLElement,
public visibility = new WatchableVisibilityPriority(WatchableVisibilityPriority.VISIBLE)) {
super();
const {element, centerColumn} = this;
element.style.display = 'flex';
element.style.flex = '1';
element.style.flexDirection = 'row';
centerColumn.style.display = 'flex';
centerColumn.style.flex = '1';
centerColumn.style.flexDirection = 'column';
centerColumn.style.flexBasis = '0px';
centerColumn.style.minWidth = '0px';
this.render();
this.registerDisposer(display.updateStarted.add(() => {
this.beforeRender.dispatch();
if (!this.layoutNeedsUpdate) return;
this.render();
// Changing the side panel layout can affect the bounds of rendered panels as well.
++display.resizeGeneration;
}));
this.registerDisposer(this.visibility.changed.add(this.invalidateLayout));
}
private makeSidePanelSideState(side: Side): SidePanelSideState {
return {
flexGroups: [],
outerDropZoneElement: this.makeDropZone(
side, /*crossIndex=*/ OUTWARDS_SIGN_FOR_SIDE[side] * Infinity, /*flexIndex=*/ 0,
/*zoneSide=*/ side, /*centered=*/ false),
};
}
hasDroppablePanel() {
return this.dragSource !== undefined;
}
startDrag(dragSource: DragSource, event: DragEvent) {
// Use setTimeout to set the attribute that enables the drop zones, rather than setting it
// synchronously, as otherwise Chrome sometimes fires dragend immediately.
//
// https://stackoverflow.com/questions/14203734/dragend-dragenter-and-dragleave-firing-off-immediately-when-i-drag
setTimeout(() => {
if (this.dragSource === dragSource) {
this.element.dataset.neuroglancerSidePanelDrag = 'true';
}
}, 0);
this.dragSource = dragSource;
event.stopPropagation();
event.dataTransfer!.setData('neuroglancer-side-panel', '');
}
endDrag() {
delete this.element.dataset.neuroglancerSidePanelDrag;
this.dragSource = undefined;
}
private makeDropZone(
side: Side, crossIndex: number, flexIndex: number, zoneSide: Side,
centered: boolean = false): HTMLElement {
const element = document.createElement('div');
element.className = 'neuroglancer-side-panel-drop-zone';
const size = 10;
const zoneFlexDirection = FLEX_DIRECTION_FOR_SIDE[zoneSide];
const zoneCrossDirection = CROSS_DIRECTION_FOR_SIDE[zoneSide];
element.style[SIZE_FOR_DIRECTION[zoneCrossDirection]] = `${size}px`;
element.style[SIZE_FOR_DIRECTION[zoneFlexDirection]] = '100%';
if (centered) {
element.style.position = 'absolute';
element.style[zoneSide] = '50%';
element.style[MARGIN_FOR_SIDE[zoneSide]] = '-${size/2}px';
} else {
element.style.position = 'relative';
element.style[MARGIN_FOR_SIDE[OPPOSITE_SIDE[zoneSide]]] = `-${size}px`;
}
element.addEventListener('dragenter', event => {
if (!this.hasDroppablePanel()) return;
element.classList.add(DRAG_OVER_CLASSNAME);
event.preventDefault();
pushDragStatus(
element, 'drop',
() => document.createTextNode(`Drop side panel as new ${zoneFlexDirection}`));
});
element.addEventListener('dragleave', () => {
popDragStatus(element, 'drop');
element.classList.remove(DRAG_OVER_CLASSNAME);
});
element.addEventListener('dragover', event => {
if (!this.hasDroppablePanel()) return;
event.preventDefault();
});
element.addEventListener('drop', event => {
const {dragSource} = this;
if (dragSource === undefined) return;
popDragStatus(element, 'drop');
element.classList.remove(DRAG_OVER_CLASSNAME);
const flexDirection = FLEX_DIRECTION_FOR_SIDE[side];
dragSource.dropAsNewPanel({
side,
row: flexDirection === 'column' ? flexIndex : crossIndex,
col: flexDirection === 'row' ? flexIndex : crossIndex,
});
this.dragSource = undefined;
event.preventDefault();
event.stopPropagation();
});
return element;
}
registerPanel(registeredPanel: RegisteredSidePanel) {
this.registeredPanels.add(registeredPanel);
this.invalidateLayout();
registeredPanel.location.locationChanged.add(this.invalidateLayout);
return () => {
this.unregisterPanel(registeredPanel);
};
}
unregisterPanel(registeredPanel: RegisteredSidePanel) {
this.registeredPanels.delete(registeredPanel);
registeredPanel.location.locationChanged.remove(this.invalidateLayout);
registeredPanel.panel?.dispose();
this.invalidateLayout();
}
disposed() {
for (const {panel} of this.registeredPanels) {
panel?.dispose();
}
super.disposed();
}
invalidateLayout = () => {
this.layoutNeedsUpdate = true;
this.display.scheduleRedraw();
};
render() {
this.layoutNeedsUpdate = false;
const sides:
Record<Side, RegisteredSidePanel[]> = {'left': [], 'right': [], 'top': [], 'bottom': []};
for (const panel of this.registeredPanels) {
sides[panel.location.value.side].push(panel);
}
const getSideChildren = (side: Side) =>
this.renderSide(side, this.sides[side].flexGroups, sides[side]);
const self = this;
function* getRowChildren() {
yield self.sides['left'].outerDropZoneElement;
yield* getSideChildren('left');
yield self.centerColumn;
yield* getSideChildren('right');
yield self.sides['right'].outerDropZoneElement;
}
updateChildren(this.element, getRowChildren());
function* getColumnChildren() {
yield self.sides['top'].outerDropZoneElement;
yield* getSideChildren('top');
yield self.center;
yield* getSideChildren('bottom');
yield self.sides['bottom'].outerDropZoneElement;
}
updateChildren(this.centerColumn, getColumnChildren());
}
private makeCrossGutter(side: Side, crossIndex: number) {
const gutter = document.createElement('div');
gutter.style.position = 'relative';
const direction = CROSS_DIRECTION_FOR_SIDE[side];
gutter.className =
`neuroglancer-resize-gutter-${direction === 'row' ? 'horizontal' : 'vertical'}`;
gutter.addEventListener('pointerdown', event => {
if ('button' in event && event.button !== 0) {
return;
}
event.preventDefault();
const flexGroup = this.sides[side].flexGroups[crossIndex];
if (flexGroup === undefined || !flexGroup.visible) return;
// Get initial size
const initialRect = flexGroup.element.getBoundingClientRect();
let size = initialRect[SIZE_FOR_DIRECTION[direction]];
const minSize = flexGroup.minSize;
const updateMessage = () => {
pushDragStatus(
gutter, 'drag',
`Drag to resize, current ${SIZE_FOR_DIRECTION[direction]} is ${flexGroup.crossSize}px`);
};
updateMessage();
startRelativeMouseDrag(
event,
(_event, deltaX: number, deltaY: number) => {
const delta = (direction === 'row') ? deltaX : deltaY;
size -= OUTWARDS_SIGN_FOR_SIDE[side] * delta;
flexGroup.crossSize = Math.max(minSize, Math.round(size));
updateMessage();
this.invalidateLayout();
},
() => {
popDragStatus(gutter, 'drag');
});
});
const dropZone = this.makeDropZone(
side, crossIndex - OUTWARDS_SIGN_FOR_SIDE[side] * 0.5, /*flexIndex=*/ 0, /*zoneSide=*/ side,
/*centered=*/ true);
gutter.appendChild(dropZone);
return gutter;
}
private makeFlexGutter(side: Side, crossIndex: number, flexIndex: number) {
const gutter = document.createElement('div');
gutter.style.position = 'relative';
const direction = FLEX_DIRECTION_FOR_SIDE[side];
gutter.className =
`neuroglancer-resize-gutter-${direction === 'row' ? 'horizontal' : 'vertical'}`;
gutter.addEventListener('pointerdown', event => {
if ('button' in event && event.button !== 0) {
return;
}
event.preventDefault();
const flexGroup = this.sides[side].flexGroups[crossIndex];
if (flexGroup === undefined || !flexGroup.visible) return;
const {cells} = flexGroup;
const cell = cells[flexIndex];
if (cell === undefined || !cell.registeredPanel.location.visible) return;
// Determine the cell index of the next visible panel.
let nextFlexIndex = flexIndex + 1;
while (nextFlexIndex < cells.length &&
!cells[nextFlexIndex].registeredPanel.location.visible) {
++nextFlexIndex;
}
if (nextFlexIndex === cells.length) return;
const nextCell = cells[nextFlexIndex];
const updateMessage = () => {
pushDragStatus(
gutter, 'drag',
`Drag to resize, current ${SIZE_FOR_DIRECTION[direction]} ratio is ` +
`${cell.registeredPanel.location.value.flex} : ` +
`${nextCell.registeredPanel.location.value.flex}`);
};
updateMessage();
startRelativeMouseDrag(
event,
newEvent => {
const firstPanel = cell.registeredPanel.panel;
const secondPanel = nextCell.registeredPanel.panel;
if (firstPanel === undefined || secondPanel === undefined) return;
const firstRect = firstPanel.element.getBoundingClientRect();
const secondRect = secondPanel.element.getBoundingClientRect();
const firstFraction = Math.max(
0.1,
Math.min(
0.9,
direction === 'column' ?
(newEvent.clientY - firstRect.top) / (secondRect.bottom - firstRect.top) :
(newEvent.clientX - firstRect.left) / (secondRect.right - firstRect.left)));
const firstLocation = cell.registeredPanel.location.value;
const secondLocation = nextCell.registeredPanel.location.value;
const existingFlexSum = firstLocation.flex + secondLocation.flex;
cell.registeredPanel.location.value = {
...firstLocation,
flex: Math.round(firstFraction * existingFlexSum * 100) / 100,
};
nextCell.registeredPanel.location.value = {
...secondLocation,
flex: Math.round((1 - firstFraction) * existingFlexSum * 100) / 100,
};
updateMessage();
cell.registeredPanel.location.locationChanged.dispatch();
nextCell.registeredPanel.location.locationChanged.dispatch();
this.invalidateLayout();
},
() => {
popDragStatus(gutter, 'drag');
});
});
const dropZone = this.makeDropZone(
side, crossIndex, /*flexIndex=*/ flexIndex + 0.5,
/*zoneSide=*/ BEGIN_SIDE_FOR_DIRECTION[FLEX_DIRECTION_FOR_SIDE[side]],
/*centered=*/ true);
gutter.appendChild(dropZone);
return gutter;
}
private renderSide(side: Side, flexGroups: SidePanelFlex[], panels: RegisteredSidePanel[]) {
const flexKey = LOCATION_KEY_FOR_DIRECTION[CROSS_DIRECTION_FOR_SIDE[side]];
const crossKey = LOCATION_KEY_FOR_DIRECTION[FLEX_DIRECTION_FOR_SIDE[side]];
panels.sort((a, b) => {
const aLoc = a.location.value, bLoc = b.location.value;
const crossDiff = aLoc[crossKey] - bLoc[crossKey];
if (crossDiff !== 0) return crossDiff;
return aLoc[flexKey] - bLoc[flexKey];
});
const self = this;
function* getFlexGroups() {
let panelIndex = 0, numPanels = panels.length;
let crossIndex = 0;
for (; panelIndex < numPanels;) {
const origCrossIndex = panels[panelIndex].location.value[crossKey];
let endPanelIndex = panelIndex;
let numVisible = 0;
let minSize = 0;
do {
const location = panels[endPanelIndex].location.value;
if (location[crossKey] !== origCrossIndex) break;
if (location.visible) {
++numVisible;
minSize = Math.max(minSize, location.minSize);
}
++endPanelIndex;
} while (endPanelIndex < numPanels);
const visible = numVisible > 0;
let flexGroup = flexGroups[crossIndex];
if (flexGroup === undefined) {
const gutter = self.makeCrossGutter(side, crossIndex);
const flexGroupElement = document.createElement('div');
flexGroupElement.className = `neuroglancer-side-panel-${FLEX_DIRECTION_FOR_SIDE[side]}`;
flexGroup = flexGroups[crossIndex] = {
element: flexGroupElement,
gutterElement: gutter,
cells: [],
crossSize: -1,
minSize,
visible,
beginDropZone: self.makeDropZone(
side, crossIndex, /*flexIndex=*/ -Infinity,
BEGIN_SIDE_FOR_DIRECTION[FLEX_DIRECTION_FOR_SIDE[side]]),
endDropZone: self.makeDropZone(
side, crossIndex, /*flexIndex=*/ +Infinity,
END_SIDE_FOR_DIRECTION[FLEX_DIRECTION_FOR_SIDE[side]]),
};
} else {
flexGroup.visible = visible;
flexGroup.minSize = minSize;
flexGroup.crossSize = Math.max(flexGroup.crossSize, minSize);
}
function* getCells() {
yield flexGroup.beginDropZone;
let prevVisible = 0;
for (let i = panelIndex, flexIndex = 0; i < endPanelIndex; ++i, ++flexIndex) {
const registeredPanel = panels[i];
let cell = flexGroup.cells[flexIndex];
if (cell === undefined) {
cell = flexGroup.cells[flexIndex] = {
registeredPanel,
gutterElement: undefined,
};
} else {
cell.registeredPanel = registeredPanel;
}
const oldLocation = cell.registeredPanel.location.value;
if (flexGroup.crossSize == -1) {
flexGroup.crossSize = Math.max(minSize, oldLocation.size);
}
if (oldLocation[crossKey] !== crossIndex || oldLocation[flexKey] !== flexIndex ||
(oldLocation.visible && oldLocation.size !== flexGroup.crossSize)) {
cell.registeredPanel.location.value = {
...oldLocation,
[crossKey]: crossIndex,
[flexKey]: flexIndex,
size: oldLocation.visible ? flexGroup.crossSize : oldLocation.size,
};
cell.registeredPanel.location.changed.dispatch();
}
const visible = oldLocation.visible && self.visibility.visible;
let {panel} = registeredPanel;
if (!visible) {
if (panel !== undefined) {
panel.dispose();
registeredPanel.panel = undefined;
}
continue;
}
++prevVisible;
if (panel === undefined) {
panel = registeredPanel.panel = registeredPanel.makePanel();
}
panel.element.style.flex = numVisible > 1 ? `${oldLocation.flex}` : '1';
yield panel.element;
if (prevVisible === numVisible) {
// Last cell does not need its own resize gutter.
cell.gutterElement = undefined;
} else {
if (cell.gutterElement === undefined) {
cell.gutterElement = self.makeFlexGutter(side, crossIndex, flexIndex);
}
yield cell.gutterElement;
}
}
yield flexGroup.endDropZone;
}
updateChildren(flexGroup.element, getCells());
flexGroup.cells.length = endPanelIndex - panelIndex;
if (visible) {
flexGroup.element.style[SIZE_FOR_DIRECTION[CROSS_DIRECTION_FOR_SIDE[side]]] =
`${flexGroup.crossSize}px`;
if (OUTWARDS_SIGN_FOR_SIDE[side] > 0) {
yield flexGroup.gutterElement;
yield flexGroup.element;
} else {
yield flexGroup.element;
yield flexGroup.gutterElement;
}
}
panelIndex = endPanelIndex;
++crossIndex;
}
flexGroups.length = crossIndex;
}
return getFlexGroups();
}
} | the_stack |
* @module Rendering
*/
import { assert } from "@itwin/core-bentley";
import { Point2d, Point3d, Range2d } from "@itwin/core-geometry";
import { ColorDef, ColorIndex, FeatureIndex, FeatureIndexType, QParams2d, QParams3d, QPoint2d, QPoint3dList } from "@itwin/core-common";
import { IModelApp } from "../../IModelApp";
import { AuxChannelTable } from "./AuxChannelTable";
import { MeshArgs, Point3dList, PolylineArgs } from "./mesh/MeshPrimitives";
import { createSurfaceMaterial, SurfaceParams, SurfaceType } from "./SurfaceParams";
import { EdgeParams } from "./EdgeParams";
/**
* Holds an array of indices into a VertexTable. Each index is a 24-bit unsigned integer.
* The order of the indices specifies the order in which vertices are drawn.
* @internal
*/
export class VertexIndices {
public readonly data: Uint8Array;
/**
* Directly construct from an array of bytes in which each index occupies 3 contiguous bytes.
* The length of the array must be a multiple of 3. This object takes ownership of the array.
*/
public constructor(data: Uint8Array) {
this.data = data;
assert(0 === this.data.length % 3);
}
/** Get the number of 24-bit indices. */
public get length(): number { return this.data.length / 3; }
/** Convert an array of 24-bit unsigned integer values into a VertexIndices object. */
public static fromArray(indices: number[]): VertexIndices {
const bytes = new Uint8Array(indices.length * 3);
for (let i = 0; i < indices.length; i++)
this.encodeIndex(indices[i], bytes, i * 3);
return new VertexIndices(bytes);
}
public static encodeIndex(index: number, bytes: Uint8Array, byteIndex: number): void {
assert(byteIndex + 2 < bytes.length);
bytes[byteIndex + 0] = index & 0x000000ff;
bytes[byteIndex + 1] = (index & 0x0000ff00) >> 8;
bytes[byteIndex + 2] = (index & 0x00ff0000) >> 16;
}
public setNthIndex(n: number, value: number): void {
VertexIndices.encodeIndex(value, this.data, n * 3);
}
public decodeIndex(index: number): number {
assert(index < this.length);
const byteIndex = index * 3;
return this.data[byteIndex] | (this.data[byteIndex + 1] << 8) | (this.data[byteIndex + 2] << 16);
}
public decodeIndices(): number[] {
const indices = [];
for (let i = 0; i < this.length; i++)
indices.push(this.decodeIndex(i));
return indices;
}
}
/** @internal */
export interface Dimensions {
width: number;
height: number;
}
/** @internal */
export function computeDimensions(nEntries: number, nRgbaPerEntry: number, nExtraRgba: number): Dimensions {
const maxSize = IModelApp.renderSystem.maxTextureSize;
const nRgba = nEntries * nRgbaPerEntry + nExtraRgba;
if (nRgba < maxSize)
return { width: nRgba, height: 1 };
// Make roughly square to reduce unused space in last row
let width = Math.ceil(Math.sqrt(nRgba));
// Ensure a given entry's RGBA values all fit on the same row.
const remainder = width % nRgbaPerEntry;
if (0 !== remainder) {
width += nRgbaPerEntry - remainder;
}
// Compute height
let height = Math.ceil(nRgba / width);
if (width * height < nRgba)
++height;
assert(height <= maxSize);
assert(width <= maxSize);
assert(width * height >= nRgba);
assert(Math.floor(height) === height);
assert(Math.floor(width) === width);
// Row padding should never be necessary...
assert(0 === width % nRgbaPerEntry);
return { width, height };
}
/** Describes a VertexTable.
* @internal
*/
export interface VertexTableProps {
/** The rectangular array of vertex data, of size width*height*numRgbaPerVertex bytes. */
readonly data: Uint8Array;
/** If true, positions are not quantized but instead stored as 32-bit floats.
* [[qparams]] will still be defined; it can be used to derive the range of positions in the table.
*/
readonly usesUnquantizedPositions?: boolean;
/** Quantization parameters for the vertex positions encoded into the array, if the positions are quantized;
* and for deriving the range of positions in the table, whether quantized or not.
*/
readonly qparams: QParams3d;
/** The number of 4-byte 'RGBA' values in each row of the array. Must be divisible by numRgbaPerVertex. */
readonly width: number;
/** The number of rows in the array. */
readonly height: number;
/** Whether or not the vertex colors contain translucent colors. */
readonly hasTranslucency: boolean;
/** If no color table exists, the color to use for all vertices. */
readonly uniformColor?: ColorDef;
/** Describes the number of features (none, one, or multiple) contained. */
readonly featureIndexType: FeatureIndexType;
/** If featureIndexType is 'Uniform', the feature ID associated with all vertices. */
readonly uniformFeatureID?: number;
/** The number of vertices in the table. Must be less than (width*height)/numRgbaPerVertex. */
readonly numVertices: number;
/** The number of 4-byte 'RGBA' values associated with each vertex. */
readonly numRgbaPerVertex: number;
/** If vertex data include texture UV coordinates, the quantization params for those coordinates. */
readonly uvParams?: QParams2d;
}
/**
* Represents vertex data (position, color, normal, UV params, etc) in a rectangular array.
* Each vertex is described by one or more contiguous 4-byte ('RGBA') values.
* This allows vertex data to be uploaded to the GPU as a texture and vertex data to be sampled
* from that texture using a single vertex ID representing an index into the array.
* Vertex color is identified by a 16-bit index into a color table appended to the vertex data.
* @internal
*/
export class VertexTable implements VertexTableProps {
/** The rectangular array of vertex data, of size width*height*numRgbaPerVertex bytes. */
public readonly data: Uint8Array;
/** If true, positions are not quantized but instead stored as 32-bit floats.
* [[qparams]] will still be defined; it can be used to derive the range of positions in the table.
*/
public readonly usesUnquantizedPositions?: boolean;
/** Quantization parameters for the vertex positions encoded into the array, the positions are quantized;
* and for deriving the range of positions in the table, whether quantized or not.
*/
public readonly qparams: QParams3d;
/** The number of 4-byte 'RGBA' values in each row of the array. Must be divisible by numRgbaPerVertex. */
public readonly width: number;
/** The number of rows in the array. */
public readonly height: number;
/** Whether or not the vertex colors contain translucent colors. */
public readonly hasTranslucency: boolean;
/** If no color table exists, the color to use for all vertices. */
public readonly uniformColor?: ColorDef;
/** Describes the number of features (none, one, or multiple) contained. */
public readonly featureIndexType: FeatureIndexType;
/** If featureIndexType is 'Uniform', the feature ID associated with all vertices. */
public readonly uniformFeatureID?: number;
/** The number of vertices in the table. Must be less than (width*height)/numRgbaPerVertex. */
public readonly numVertices: number;
/** The number of 4-byte 'RGBA' values associated with each vertex. */
public readonly numRgbaPerVertex: number;
/** If vertex data include texture UV coordinates, the quantization params for those coordinates. */
public readonly uvParams?: QParams2d;
/** Construct a VertexTable. The VertexTable takes ownership of all input data - it must not be later modified by the caller. */
public constructor(props: VertexTableProps) {
this.data = props.data;
this.qparams = props.qparams;
this.usesUnquantizedPositions = !!props.usesUnquantizedPositions;
this.width = props.width;
this.height = props.height;
this.hasTranslucency = true === props.hasTranslucency;
this.uniformColor = props.uniformColor;
this.featureIndexType = props.featureIndexType;
this.uniformFeatureID = props.uniformFeatureID;
this.numVertices = props.numVertices;
this.numRgbaPerVertex = props.numRgbaPerVertex;
this.uvParams = props.uvParams;
}
public static buildFrom(builder: VertexTableBuilder, colorIndex: ColorIndex, featureIndex: FeatureIndex): VertexTable {
const { numVertices, numRgbaPerVertex } = builder;
const numColors = colorIndex.isUniform ? 0 : colorIndex.numColors;
const dimensions = computeDimensions(numVertices, numRgbaPerVertex, numColors);
assert(0 === dimensions.width % numRgbaPerVertex || (0 < numColors && 1 === dimensions.height));
const data = new Uint8Array(dimensions.width * dimensions.height * 4);
builder.data = data;
for (let i = 0; i < numVertices; i++)
builder.appendVertex(i);
builder.appendColorTable(colorIndex);
builder.data = undefined;
return new VertexTable({
data,
qparams: builder.qparams,
usesUnquantizedPositions: builder.usesUnquantizedPositions,
width: dimensions.width,
height: dimensions.height,
hasTranslucency: colorIndex.hasAlpha,
uniformColor: colorIndex.uniform,
numVertices,
numRgbaPerVertex,
uvParams: builder.uvParams,
featureIndexType: featureIndex.type,
uniformFeatureID: featureIndex.type === FeatureIndexType.Uniform ? featureIndex.featureID : undefined,
});
}
public static createForPolylines(args: PolylineArgs): VertexTable | undefined {
const polylines = args.polylines;
if (0 < polylines.length)
return this.buildFrom(createPolylineBuilder(args), args.colors, args.features);
else
return undefined;
}
}
/**
* Describes mesh geometry to be submitted to the rendering system.
* A mesh consists of a surface and its edges, which may include any combination of silhouettes, polylines, and single segments.
* The surface and edges all refer to the same vertex table.
*/
export class MeshParams {
public readonly vertices: VertexTable;
public readonly surface: SurfaceParams;
public readonly edges?: EdgeParams;
public readonly isPlanar: boolean;
public readonly auxChannels?: AuxChannelTable;
/** Directly construct a MeshParams. The MeshParams takes ownership of all input data. */
public constructor(vertices: VertexTable, surface: SurfaceParams, edges?: EdgeParams, isPlanar?: boolean, auxChannels?: AuxChannelTable) {
this.vertices = vertices;
this.surface = surface;
this.edges = edges;
this.isPlanar = !!isPlanar;
this.auxChannels = auxChannels;
}
/** Construct from a MeshArgs. */
public static create(args: MeshArgs): MeshParams {
const builder = createMeshBuilder(args);
const vertices = VertexTable.buildFrom(builder, args.colors, args.features);
const surfaceIndices = VertexIndices.fromArray(args.vertIndices);
const surface: SurfaceParams = {
type: builder.type,
indices: surfaceIndices,
fillFlags: args.fillFlags,
hasBakedLighting: true === args.hasBakedLighting,
hasFixedNormals: true === args.hasFixedNormals,
textureMapping: undefined !== args.textureMapping ? { texture: args.textureMapping.texture, alwaysDisplayed: false } : undefined,
material: createSurfaceMaterial(args.material),
};
const channels = undefined !== args.auxChannels ? AuxChannelTable.fromChannels(args.auxChannels, vertices.numVertices) : undefined;
const edges = EdgeParams.fromMeshArgs(args);
return new MeshParams(vertices, surface, edges, args.isPlanar, channels);
}
}
/** Builds a VertexTable from some data type supplying the vertex data. */
export abstract class VertexTableBuilder {
public data?: Uint8Array;
private _curIndex: number = 0;
public abstract get numVertices(): number;
public abstract get numRgbaPerVertex(): number;
public abstract get qparams(): QParams3d;
public abstract get usesUnquantizedPositions(): boolean;
public get uvParams(): QParams2d | undefined { return undefined; }
public abstract appendVertex(vertIndex: number): void;
public appendColorTable(colorIndex: ColorIndex) {
if (undefined !== colorIndex.nonUniform) {
for (const color of colorIndex.nonUniform.colors) {
this.appendColor(color);
}
}
}
protected advance(nBytes: number) {
this._curIndex += nBytes;
assert(this._curIndex <= this.data!.length);
}
protected append8(val: number) {
assert(0 <= val);
assert(val <= 0xff);
assert(val === Math.floor(val));
this.data![this._curIndex] = val;
this.advance(1);
}
protected append16(val: number) {
this.append8(val & 0x00ff);
this.append8(val >>> 8);
}
protected append32(val: number) {
this.append16(val & 0x0000ffff);
this.append16(val >>> 16);
}
private appendColor(tbgr: number) {
const colors = ColorDef.getColors(tbgr);
// invert transparency => alpha
colors.t = 255 - colors.t;
// premultiply alpha...
switch (colors.t) {
case 0:
colors.r = colors.g = colors.b = 0;
break;
case 255:
break;
default: {
const f = colors.t / 255.0;
colors.r = Math.floor(colors.r * f + 0.5);
colors.g = Math.floor(colors.g * f + 0.5);
colors.b = Math.floor(colors.b * f + 0.5);
break;
}
}
// Store 32-bit value in little-endian order (red first)
this.append8(colors.r);
this.append8(colors.g);
this.append8(colors.b);
this.append8(colors.t);
}
}
type VertexData = PolylineArgs | MeshArgs;
type Quantized<T extends VertexData> = Omit<T, "points"> & { points: QPoint3dList };
type Unquantized<T extends VertexData> = Omit<T, "points"> & { points: Omit<Point3dList, "add"> };
namespace Quantized { // eslint-disable-line @typescript-eslint/no-redeclare
/**
* Supplies vertex data from a PolylineArgs or MeshArgs. Each vertex consists of 12 bytes:
* pos.x 00
* pos.y 02
* pos.z 04
* colorIndex 06
* featureIndex 08 (24 bits)
* materialIndex 0B (for meshes that use a material atlas; otherwise unused). NOTE: Currently front-end code does not produce material atlases.
*/
export class SimpleBuilder<T extends Quantized<VertexData>> extends VertexTableBuilder {
public args: T;
protected _qpoints: QPoint3dList;
public constructor(args: T) {
super();
this._qpoints = args.points;
this.args = args;
assert(undefined !== this.args.points);
}
public get numVertices() { return this.args.points.length; }
public get numRgbaPerVertex() { return 3; }
public get usesUnquantizedPositions() { return false; }
public get qparams() {
return this._qpoints.params;
}
public appendVertex(vertIndex: number): void {
this.appendPosition(vertIndex);
this.appendColorIndex(vertIndex);
this.appendFeatureIndex(vertIndex);
}
protected appendPosition(vertIndex: number) {
this.append16(this._qpoints.list[vertIndex].x);
this.append16(this._qpoints.list[vertIndex].y);
this.append16(this._qpoints.list[vertIndex].z);
}
protected appendColorIndex(vertIndex: number) {
if (undefined !== this.args.colors.nonUniform) {
this.append16(this.args.colors.nonUniform.indices[vertIndex]);
} else {
this.advance(2);
}
}
protected appendFeatureIndex(vertIndex: number) {
if (undefined !== this.args.features.featureIDs) {
this.append32(this.args.features.featureIDs[vertIndex]);
} else {
this.advance(4);
}
}
}
/** Supplies vertex data from a MeshArgs. */
export class MeshBuilder extends SimpleBuilder<Quantized<MeshArgs>> {
public readonly type: SurfaceType;
protected constructor(args: Quantized<MeshArgs>, type: SurfaceType) {
super(args);
this.type = type;
}
public static create(args: Quantized<MeshArgs>): MeshBuilder {
if (args.isVolumeClassifier)
return new MeshBuilder(args, SurfaceType.VolumeClassifier);
const isLit = undefined !== args.normals && 0 < args.normals.length;
const isTextured = undefined !== args.textureMapping;
let uvParams: QParams2d | undefined;
if (args.textureMapping) {
const uvRange = Range2d.createNull();
const fpts = args.textureMapping.uvParams;
const pt2d = new Point2d();
if (undefined !== fpts && fpts.length > 0)
for (let i = 0; i < args.points.length; i++)
uvRange.extendPoint(Point2d.create(fpts[i].x, fpts[i].y, pt2d));
uvParams = QParams2d.fromRange(uvRange);
}
if (isLit)
return isTextured ? new TexturedLitMeshBuilder(args, uvParams!) : new LitMeshBuilder(args);
else
return isTextured ? new TexturedMeshBuilder(args, uvParams!) : new MeshBuilder(args, SurfaceType.Unlit);
}
}
/** Supplies vertex data from a MeshArgs where each vertex consists of 16 bytes.
* In addition to the SimpleBuilder data, the final 4 bytes hold the quantized UV params
* The color index is left uninitialized as it is unused.
*/
class TexturedMeshBuilder extends MeshBuilder {
private _qparams: QParams2d;
private _qpoint = new QPoint2d();
public constructor(args: Quantized<MeshArgs>, qparams: QParams2d, type: SurfaceType = SurfaceType.Textured) {
super(args, type);
this._qparams = qparams;
assert(undefined !== args.textureMapping);
}
public override get numRgbaPerVertex() { return 4; }
public override get uvParams() { return this._qparams; }
public override appendVertex(vertIndex: number) {
this.appendPosition(vertIndex);
this.appendNormal(vertIndex);
this.appendFeatureIndex(vertIndex);
this.appendUVParams(vertIndex);
}
protected appendNormal(_vertIndex: number): void { this.advance(2); } // no normal for unlit meshes
protected appendUVParams(vertIndex: number) {
this._qpoint.init(this.args.textureMapping!.uvParams[vertIndex], this._qparams);
this.append16(this._qpoint.x);
this.append16(this._qpoint.y);
}
}
/** As with TexturedMeshBuilder, but the color index is replaced with the oct-encoded normal value. */
class TexturedLitMeshBuilder extends TexturedMeshBuilder {
public constructor(args: Quantized<MeshArgs>, qparams: QParams2d) {
super(args, qparams, SurfaceType.TexturedLit);
assert(undefined !== args.normals);
}
protected override appendNormal(vertIndex: number) { this.append16(this.args.normals![vertIndex].value); }
}
/** 16 bytes. The last 2 bytes are unused; the 2 immediately preceding it hold the oct-encoded normal value. */
class LitMeshBuilder extends MeshBuilder {
public constructor(args: Quantized<MeshArgs>) {
super(args, SurfaceType.Lit);
assert(undefined !== args.normals);
}
public override get numRgbaPerVertex() { return 4; }
public override appendVertex(vertIndex: number) {
super.appendVertex(vertIndex);
this.append16(this.args.normals![vertIndex].value);
this.advance(2); // 2 unused bytes
}
}
}
/** Builders in this namespace store vertex positions as 32-bit floats instead of quantizing to 16-bit unsigned integers.
* This is preferred for decoration graphics, which might contain ranges of positions that exceed the limits for quantization; if quantized,
* they could produce visual artifacts.
* Each builder produces a VertexTable that starts with the following layout:
* pos.x: 00
* pos.y: 04
* pos.z: 08
* featureIndex: 0C
* materialIndex:0F (NOTE: frontend code currently doesn't produce material atlases, so this is always zero).
* Followed (by default) by:
* colorIndex: 10
* unused: 12
* Subclasses may add 4 more bytes and/or overwrite the final 4 bytes above.
*/
namespace Unquantized { // eslint-disable-line @typescript-eslint/no-redeclare
const u32Array = new Uint32Array(1);
const f32Array = new Float32Array(u32Array.buffer);
// colorIndex: 10
// unused: 12
export class SimpleBuilder<T extends Unquantized<VertexData>> extends VertexTableBuilder {
public args: T;
protected _points: Point3d[];
private _qparams3d: QParams3d;
public constructor(args: T) {
super();
assert(!(args.points instanceof QPoint3dList));
this._qparams3d = QParams3d.fromRange(args.points.range);
this.args = args;
this._points = args.points;
}
public get numVertices() { return this._points.length; }
public get numRgbaPerVertex() { return 5; }
public get usesUnquantizedPositions() { return true; }
public get qparams() { return this._qparams3d; }
public appendVertex(vertIndex: number): void {
this.appendTransposePosAndFeatureNdx(vertIndex);
this.appendColorIndex(vertIndex);
}
private appendFloat32(val: number) {
f32Array[0] = val;
this.append32(u32Array[0]);
}
private convertFloat32(val: number): number {
f32Array[0] = val;
return u32Array[0];
}
protected appendTransposePosAndFeatureNdx(vertIndex: number) {
// transpose position xyz vals into [0].xyz - [3].xyz, and add feature index at .w
// this is to order things to let shader code access much more efficiently
const pt = this._points[vertIndex];
const x = this.convertFloat32 (pt.x);
const y = this.convertFloat32 (pt.y);
const z = this.convertFloat32 (pt.z);
const featID = (this.args.features.featureIDs) ? this.args.features.featureIDs[vertIndex] : 0;
this.append8(x & 0x000000ff);
this.append8(y & 0x000000ff);
this.append8(z & 0x000000ff);
this.append8(featID & 0x000000ff);
this.append8((x >>> 8) & 0x000000ff);
this.append8((y >>> 8) & 0x000000ff);
this.append8((z >>> 8) & 0x000000ff);
this.append8((featID >>> 8) & 0x000000ff);
this.append8((x >>> 16) & 0x000000ff);
this.append8((y >>> 16) & 0x000000ff);
this.append8((z >>> 16) & 0x000000ff);
this.append8((featID >>> 16) & 0x000000ff);
this.append8(x >>> 24);
this.append8(y >>> 24);
this.append8(z >>> 24);
this.append8(featID >>> 24);
}
protected appendPosition(vertIndex: number) {
const pt = this._points[vertIndex];
this.appendFloat32(pt.x);
this.appendFloat32(pt.y);
this.appendFloat32(pt.z);
}
protected appendFeatureIndex(vertIndex: number) {
if (this.args.features.featureIDs)
this.append32(this.args.features.featureIDs[vertIndex]);
else
this.advance(4);
}
protected _appendColorIndex(vertIndex: number) {
if (undefined !== this.args.colors.nonUniform)
this.append16(this.args.colors.nonUniform.indices[vertIndex]);
else
this.advance(2);
}
protected appendColorIndex(vertIndex: number) {
this._appendColorIndex(vertIndex);
this.advance(2);
}
}
export class MeshBuilder extends SimpleBuilder<Unquantized<MeshArgs>> {
public readonly type: SurfaceType;
protected constructor(args: Unquantized<MeshArgs>, type: SurfaceType) {
super(args);
this.type = type;
}
public static create(args: Unquantized<MeshArgs>): MeshBuilder {
if (args.isVolumeClassifier)
return new MeshBuilder(args, SurfaceType.VolumeClassifier);
const isLit = undefined !== args.normals && 0 < args.normals.length;
const isTextured = undefined !== args.textureMapping;
let uvParams: QParams2d | undefined;
if (args.textureMapping) {
const uvRange = Range2d.createNull();
const fpts = args.textureMapping.uvParams;
const pt2d = new Point2d();
if (undefined !== fpts && fpts.length > 0)
for (let i = 0; i < args.points.length; i++)
uvRange.extendPoint(Point2d.create(fpts[i].x, fpts[i].y, pt2d));
uvParams = QParams2d.fromRange(uvRange);
}
if (isLit)
return isTextured ? new TexturedLitMeshBuilder(args, uvParams!) : new LitMeshBuilder(args);
else
return isTextured ? new TexturedMeshBuilder(args, uvParams!) : new MeshBuilder(args, SurfaceType.Unlit);
}
}
// u: 10
// v: 12
class TexturedMeshBuilder extends MeshBuilder {
private _qparams: QParams2d;
private _qpoint = new QPoint2d();
public constructor(args: Unquantized<MeshArgs>, qparams: QParams2d, type = SurfaceType.Textured) {
super(args, type);
this._qparams = qparams;
assert(undefined !== args.textureMapping);
}
public override get uvParams() { return this._qparams; }
public override appendVertex(vertIndex: number) {
super.appendVertex(vertIndex);
this._qpoint.init(this.args.textureMapping!.uvParams[vertIndex], this._qparams);
this.append16(this._qpoint.x);
this.append16(this._qpoint.y);
}
protected override appendColorIndex() { }
}
// u: 10
// v: 12
// normal: 14
// unused: 16
class TexturedLitMeshBuilder extends TexturedMeshBuilder {
public constructor(args: Unquantized<MeshArgs>, qparams: QParams2d) {
super(args, qparams, SurfaceType.TexturedLit);
assert(undefined !== args.normals);
}
public override get numRgbaPerVertex() { return 6; }
public override appendVertex(vertIndex: number) {
super.appendVertex(vertIndex);
this.append16(this.args.normals![vertIndex].value);
this.advance(2);
}
}
// color: 10
// normal: 12
class LitMeshBuilder extends MeshBuilder {
public constructor(args: Unquantized<MeshArgs>) {
super(args, SurfaceType.Lit);
assert(undefined !== args.normals);
}
protected override appendColorIndex(vertIndex: number) {
super._appendColorIndex(vertIndex);
}
public override appendVertex(vertIndex: number) {
super.appendVertex(vertIndex);
this.append16(this.args.normals![vertIndex].value);
}
}
}
function createMeshBuilder(args: MeshArgs): VertexTableBuilder & { type: SurfaceType } {
if (args.points instanceof QPoint3dList)
return Quantized.MeshBuilder.create(args as Quantized<MeshArgs>); // wtf compiler?
else
return Unquantized.MeshBuilder.create(args as Unquantized<MeshArgs>); // seriously wtf?
}
function createPolylineBuilder(args: PolylineArgs): VertexTableBuilder {
if (args.points instanceof QPoint3dList)
return new Quantized.SimpleBuilder(args as Quantized<PolylineArgs>); // wtf compiler?
else
return new Unquantized.SimpleBuilder(args as Unquantized<PolylineArgs>); // seriously wtf?
} | the_stack |
import { trimStart, trim, find, range, throttle, some, endsWith, map } from 'lodash';
import { Models } from 'omnisharp-client';
import { Observable } from 'rxjs';
import { CompositeDisposable, Disposable, IDisposable } from 'ts-disposables';
import { augmentEditor, getEnhancedGrammar, ExcludeClassifications } from '../features/highlight-v1.9';
import { Omni } from '../server/omni';
const customExcludes = ExcludeClassifications.concat([
Models.HighlightClassification.Identifier,
Models.HighlightClassification.PreprocessorKeyword,
Models.HighlightClassification.ExcludedCode,
]);
const pool = (function () {
const NUM_TO_KEEP = 10;
const POOL: { editor: Atom.TextEditor; element: Atom.TextEditorComponent; }[] = [];
const cleanupPool = throttle(function cleanupPool() {
if (POOL.length > NUM_TO_KEEP) {
const len = Math.min(POOL.length - NUM_TO_KEEP, 10);
const remove = POOL.splice(0, len);
remove.forEach(x => x.editor.destroy());
cleanupPool();
}
}, 10000, { trailing: true });
class Result implements IDisposable {
private _disposable = Disposable.create(() => {
const {editor, element} = this;
(element as any).remove();
POOL.push({ editor, element });
editor.setGrammar(Omni.grammars[0]);
editor.setText('');
cleanupPool();
});
constructor(public editor: Atom.TextEditor, public element: Atom.TextEditorComponent) { }
public dispose() {
this._disposable.dispose();
}
}
function populatePool() {
return Observable.interval(50)
.take(10)
.map(() => {
const editorElement = <any>document.createElement('atom-text-editor');
editorElement.setAttributeNode(document.createAttribute('gutter-hidden'));
editorElement.removeAttribute('tabindex'); // make read-only
const editor = (<any>editorElement).getModel();
editor.getDecorations({ class: 'cursor-line', type: 'line' })[0].destroy(); // remove the default selection of a line in each editor
editor.setGrammar(Omni.grammars[0]);
editor.setSoftWrapped(true);
augmentEditor(editor);
return <Atom.TextEditorComponent>editorElement;
})
.do(element => POOL.push({ element, editor: (<any>element).getModel() }))
.toArray();
}
setTimeout(() => populatePool(), 10000);
function request(): Observable<Result> {
if (POOL.length) {
const {editor, element} = POOL.pop();
return Observable.of(new Result(editor, element));
} else {
return populatePool().flatMap(() => request());
}
}
return {
getNext() {
if (!POOL.length) { return { success: false, result: null }; }
const {editor, element} = POOL.pop();
return { success: true, result: new Result(editor, element) };
},
request
};
})();
export class EditorElement extends HTMLSpanElement implements WebComponent {
private _pre: HTMLPreElement;
private _disposable: CompositeDisposable;
private _release: IDisposable;
private _editorElement: Atom.TextEditorComponent;
private _editor: Atom.TextEditor;
private _whitespace: number;
private _grammar: FirstMate.Grammar;
private _usage: Models.QuickFix;
public get usage() { return this._usage; }
public set usage(value) {
this._editorText = null;
this._usage = value;
this._whitespace = 0;
const text = this._usage.Text;
const usageLength = this._usage.EndColumn - this._usage.Column;
for (let i = this._usage.Column; i > -1; i--) {
const chunk = text.substr(i);
console.log(chunk);
// This regex perhaps needs to be improved
const match = chunk.match(/^((?:@|_|[a-zA-Z])[\w]*)(?:[\W]|$)/);
if (!match) continue;
console.log(match);
const v = match[1];
if (v.length === usageLength) {
this._whitespace = this._usage.Column - i;
break;
}
}
if (this._pre) {
this._pre.innerText = trimStart(value.Text);
}
if (this._editor) {
this.setEditorText(this._grammar);
}
}
private _editorText: string;
public get editorText() { return this._editorText; }
public set editorText(value) {
this._usage = null;
this._editorText = value;
if (this._pre) {
this._pre.innerText = trimStart(value);
}
if (this._editor) {
this.setEditorText(this._grammar);
}
}
private setEditorText(grammar: FirstMate.Grammar) {
if (this._usage) {
const text = this._usage.Text;
(this._editor as any)._setGrammar(<any>grammar);
this._editor.setText(trimStart(text));
const marker = this._editor.markBufferRange([[0, +this._usage.Column - this._whitespace], [+this._usage.EndLine - +this._usage.Line, +this._usage.EndColumn - this._whitespace]]);
this._editor.decorateMarker(marker, { type: 'highlight', class: 'findusages-underline' });
} else {
this._editor.setText(trim(this._editorText));
}
}
public attachedCallback() {
this._disposable = new CompositeDisposable();
if (!this._pre) {
this._pre = document.createElement('pre');
this._pre.innerText = this._usage && this._usage.Text || this.editorText;
this._pre.style.fontSize = `${atom.config.get('editor.fontSize')}px !important`;
}
this.appendChild(this._pre);
}
public revert() {
this._detachEditor(true);
}
private _enhanced: boolean;
public enhance() {
if (this._enhanced) return;
this._enhanced = true;
const next = pool.getNext();
if (next.success) {
if (this._usage && atom.config.get<boolean>('omnisharp-atom.enhancedHighlighting')) {
const s = request({ filePath: this._usage.FileName, startLine: this._usage.Line, endLine: this._usage.EndLine, whitespace: this._whitespace })
.subscribe(response => {
const grammar = this._grammar = getEnhancedGrammar(next.result.editor, find(Omni.grammars, g => some((<any>g).fileTypes, ft => endsWith(this._usage.FileName, `.${ft}`))), { readonly: true });
(<any>grammar).setResponses(response);
this._attachEditor(next.result, grammar);
});
this._disposable.add(s);
return;
}
this._attachEditor(next.result);
} else {
const s = pool.request().subscribe(result => {
if (this._usage && atom.config.get<boolean>('omnisharp-atom.enhancedHighlighting')) {
const s = request({ filePath: this._usage.FileName, startLine: this._usage.Line, endLine: this._usage.EndLine, whitespace: this._whitespace })
.subscribe(response => {
const grammar = this._grammar = getEnhancedGrammar(result.editor, find(Omni.grammars, g => some((<any>g).fileTypes, ft => endsWith(this._usage.FileName, `.${ft}`))), { readonly: true });
(<any>grammar).setResponses(response);
this._attachEditor(result, grammar);
});
this._disposable.add(s);
return;
}
this._attachEditor(result);
this._disposable.remove(s);
});
this._disposable.add(s);
}
}
private _attachEditor(result: { editor: Atom.TextEditor; element: Atom.TextEditorComponent; dispose: () => void }, grammar?: FirstMate.Grammar) {
if (this._pre) {
this._pre.remove();
this._pre = null;
}
this._release = result;
this._disposable.add(result);
this._editorElement = result.element;
this._editor = result.editor;
this.setEditorText(grammar || this._grammar);
this.appendChild(<any>this._editorElement);
}
private _detachEditor(append?: boolean) {
if (append) {
this._pre = document.createElement('pre');
this._pre.innerText = this._usage && this._usage.Text || this.editorText;
this._pre.style.fontSize = `${atom.config.get('editor.fontSize')}px !important`;
this.appendChild(this._pre);
}
if (this._release) {
this._disposable.remove(this._release);
this._release.dispose();
}
if (this._editorElement)
(this._editorElement as any).remove();
this._editor = null;
this._editorElement = null;
this._enhanced = false;
}
public detachedCallback() {
this._detachEditor();
if (this._pre) {
this._pre.remove();
this._pre.innerText = '';
}
this._disposable.dispose();
}
}
function request({filePath, startLine, endLine, whitespace}: { filePath: string; startLine: number; endLine: number; whitespace: number; }) {
return Omni.request(client => client.highlight({
Buffer: null,
FileName: filePath,
Lines: range(startLine, endLine),
ExcludeClassifications: customExcludes
}, { silent: true }))
.map(response => map(response.Highlights,
//.filter(x => x.StartLine >= request.startLine && x.EndLine <= request.endLine)
x => ({
StartLine: x.StartLine - startLine,
StartColumn: (x.StartLine === startLine ? x.StartColumn - whitespace : x.StartColumn),
EndLine: x.EndLine - startLine,
EndColumn: (x.StartLine === startLine ? x.EndColumn - whitespace : x.EndColumn),
Kind: x.Kind,
Projects: x.Projects
})))
.filter(x => x.length > 0);
}
(<any>exports).EditorElement = (<any>document).registerElement('omnisharp-editor-element', { prototype: EditorElement.prototype }); | the_stack |
import { EffectClientConfig } from './../types/effectClientConfig';
import Web3 from 'web3';
/**
* Build default configuration object to be passed to client instantiation.
* @param environment Parameter to define which configuratoin object will be used, defaults ot testnet
* @param config? Configuration object. Pass configuraiton object in order to set any of the following properties:
* { network, signatureProvider, relayerKey, eosNodeUrl, web3, apiKey, secure, authentication, authUrl, ipfsNode, forceContract,
* accountContract, efxTokenContract, efxSymbol, efx_precision, efxExtendedSymbol, eosRelayerAccount, eoelayerPermission }
* @example defaultConfiguration(environment = 'mainnet', config = {network: 'mainnet, bscRpcUrl: 'wss://bsc-ws-node.nariox.org:443', ipfsNode: 'https://ifps.effect.ai'})
*/
// TODO - The user should pass a config object, but it is not nessecary to specify all the properties, some of them should be optional.
// Should a new interface be created to pass a user defined config object?
export const defaultConfiguration = (environment: string = 'testnet', config?: EffectClientConfig): EffectClientConfig => {
if (environment === 'mainnet' || environment === 'main' || environment === 'app') {
return {
network: config?.network ?? 'mainnet',
signatureProvider: config?.signatureProvider ?? null,
web3: config?.web3 ?? new Web3(config?.bscRpcUrl ?? 'https://bsc-dataseed.binance.org'),
ipfsNode: config?.ipfsNode ?? 'https://ipfs.effect.ai',
forceContract: config?.forceContract ?? 'force.efx',
accountContract: config?.accountContract ?? 'vaccount.efx',
efxTokenContract: config?.efxTokenContract ?? 'effecttokens',
efxSymbol: config?.efxSymbol ?? 'EFX',
efxPrecision: config?.efxPrecision ?? 4,
efxExtendedSymbol: config?.efxExtendedSymbol ?? '4,EFX',
eosRelayerAccount: config?.eosRelayerAccount ?? 'efxtxrelayer',
eosRelayerPermission: config?.eosRelayerPermission ?? 'active',
eosRelayerUrl: config?.eosRelayerUrl ?? 'https://vaccount-relayer-service-mainnet-qyy9z.ondigitalocean.app',
forceVaccountId: config?.forceVaccountId ?? 0,
payoutDelaySec: config?.payoutDelaySec ?? 3600,
releaseTaskDelaySec: config?.releaseTaskDelaySec ?? 1800,
bscNetworkId: config?.bscNetworkId ?? 56,
bscHexId: config?.bscHexId ?? '0x38',
bscChainName: config?.bscChainName ?? 'Binance Smart Chain',
bscNetworkType: config?.bscNetworkType ?? 'Mainnet',
bscTokenName: config?.bscTokenName ?? 'Binance Coin',
bscTokenSymbol: config?.bscTokenSymbol ?? 'BNB',
bscTokenDecimals: config?.bscTokenDecimals ?? 18,
bscRpcUrl: config?.bscRpcUrl ?? 'https://bsc-dataseed.binance.org',
bscExplorerUrl: config?.bscExplorerUrl ?? 'https://bscscan.com',
bscEfxTokenContract: config?.bscEfxTokenContract ?? '0xC51Ef828319b131B595b7ec4B28210eCf4d05aD0',
eosExplorerUrl: config?.eosExplorerUrl ?? 'https://bloks.io',
eosNodeUrl: config?.eosNodeUrl ?? 'https://api.eostitan.com',
eosNodeProtocol: config?.eosNodeProtocol ?? 'https',
eosNodePort: config?.eosNodePort ?? 443,
eosNodeHost: config?.eosNodeHost ?? 'api.eostitan.com',
eosChainId: config?.eosChainId ?? 'aca376f206b8fc25a6ed44dbdc66547c36c6c33e3a119ffbeaef943642f0e906',
batchSizeLimit: 300,
taskEstimatedTime: 1.5
}
} else if (environment === 'jungle' || environment === 'jungle3' || environment === 'testnet') {
return {
network: config?.network ?? 'testnet',
signatureProvider: config?.signatureProvider ?? null,
web3: config?.web3 ?? new Web3(config?.bscRpcUrl ?? 'https://bsc-dataseed.binance.org'),
ipfsNode: config?.ipfsNode ?? 'https://ipfs.effect.ai',
forceContract: config?.forceContract ?? 'efxforce1112',
forceVaccountId: config?.forceVaccountId ?? 333,
accountContract: config?.accountContract ?? 'efxaccount11',
efxTokenContract: config?.efxTokenContract ?? 'efxtoken1112',
efxSymbol: config?.efxSymbol ?? 'EFX',
efxPrecision: config?.efxPrecision ?? 4,
efxExtendedSymbol: config?.efxExtendedSymbol ?? '4,EFX',
eosRelayerAccount: config?.eosRelayerAccount ?? 'efxrelayer11',
eosRelayerPermission: config?.eosRelayerPermission ?? 'active',
eosRelayerUrl: config?.eosRelayerUrl ?? 'https://vaccount-relayer-service-jungle-rn7et.ondigitalocean.app',
payoutDelaySec: config?.payoutDelaySec ?? 3600,
releaseTaskDelaySec: config?.releaseTaskDelaySec ?? 1800,
bscNetworkId: config?.bscNetworkId ?? 56,
bscHexId: config?.bscHexId ?? '0x38',
bscChainName: config?.bscChainName ?? 'Binance Smart Chain',
bscNetworkType: config?.bscNetworkType ?? 'Mainnet',
bscTokenName: config?.bscTokenName ?? 'Binance Coin',
bscTokenSymbol: config?.bscTokenSymbol ?? 'BNB',
bscTokenDecimals: config?.bscTokenDecimals ?? 18,
bscRpcUrl: config?.bscRpcUrl ?? 'https://bsc-dataseed.binance.org',
bscExplorerUrl: config?.bscExplorerUrl ?? 'https://bscscan.com',
bscEfxTokenContract: config?.bscEfxTokenContract ?? '0xC51Ef828319b131B595b7ec4B28210eCf4d05aD0',
eosExplorerUrl: config?.eosExplorerUrl ?? 'https://jungle3.bloks.io',
eosNodeUrl: config?.eosNodeUrl ?? 'https://jungle3.cryptolions.io/',
eosNodeProtocol: config?.eosNodeProtocol ?? 'https',
eosNodePort: config?.eosNodePort ?? 443,
eosNodeHost: config?.eosNodeHost ?? 'jungle3.cryptolions.io',
eosChainId: config?.eosChainId ?? '2a02a0053e5a8cf73a56ba0fda11e4d92e0238a4a2aa74fccf46d5a910746840',
batchSizeLimit: 300,
taskEstimatedTime: 1.5
}
} else if (environment === 'local') {
/**
* INFO When spinning up the local node, the first account created should be the force_account.
* INFO deploy the local relayer service.
* TODO Add deployment of local efx token on bsc.
*/
return {
network: config?.network ?? 'local',
signatureProvider: config?.signatureProvider ?? null,
web3: config?.web3 ?? new Web3(config?.bscRpcUrl ?? 'https://bsc-dataseed.binance.org'),
ipfsNode: config?.ipfsNode ?? 'https://ipfs.effect.ai',
forceContract: config?.forceContract ?? 'effect.force',
forceVaccountId: config?.forceVaccountId ?? 0,
accountContract: config?.accountContract ?? 'effect.accnt',
efxTokenContract: config?.efxTokenContract ?? 'effect.token',
efxSymbol: config?.efxSymbol ?? 'EFX',
efxPrecision: config?.efxPrecision ?? 4,
efxExtendedSymbol: config?.efxExtendedSymbol ?? '4,EFX',
eosRelayerAccount: config?.eosRelayerAccount ?? 'effect.relay',
eosRelayerPermission: config?.eosRelayerPermission ?? 'active',
eosRelayerUrl: config?.eosRelayerUrl ?? 'http://localhost:3001',
payoutDelaySec: config?.payoutDelaySec ?? 1,
releaseTaskDelaySec: config?.releaseTaskDelaySec ?? 1,
bscNetworkId: config?.bscNetworkId ?? 97,
bscHexId: config?.bscHexId ?? '0x61',
bscChainName: config?.bscChainName ?? 'Binance Smart Chain',
bscNetworkType: config?.bscNetworkType ?? 'Testnet',
bscTokenName: config?.bscTokenName ?? 'Binance Coin',
bscTokenSymbol: config?.bscTokenSymbol ?? 'BNB',
bscTokenDecimals: config?.bscTokenDecimals ?? 18,
bscRpcUrl: config?.bscRpcUrl ?? 'https://bsc-dataseed.binance.org',
bscExplorerUrl: config?.bscExplorerUrl ?? 'https://bscscan.com',
bscEfxTokenContract: config?.bscEfxTokenContract ?? '0xC51Ef828319b131B595b7ec4B28210eCf4d05aD0',
eosExplorerUrl: config?.eosExplorerUrl ?? 'https://local.bloks.io',
eosNodeUrl: config?.eosNodeUrl ?? 'http://localhost:8888',
eosNodeProtocol: config?.eosNodeProtocol ?? 'http',
eosNodePort: config?.eosNodePort ?? 8888,
eosNodeHost: config?.eosNodeHost ?? 'localhost',
eosChainId: config?.eosChainId ?? '8a34ec7df1b8cd06ff4a8abbaa7cc50300823350cadc59ab296cb00d104d2b8f',
batchSizeLimit: 300,
taskEstimatedTime: 1.5
}
} else {
throw new Error('no default config is being used, make sure you specified configuration object for the environment you are using when creating a client effectSDK.EffectClient("main"). ')
}
} | the_stack |
import { Antialias } from './entities/Antialias';
import { BigBlur } from './entities/BigBlur';
import { Bloom } from './entities/Bloom';
import { BufferRenderTarget } from './heck/BufferRenderTarget';
import { CanvasRenderTarget } from './heck/CanvasRenderTarget';
import { Component } from './heck/components/Component';
import { CubemapCameraEntity } from './entities/CubemapCameraEntity';
import { DVi } from './entities/DVi';
import { DeferredCamera } from './entities/DeferredCamera';
import { Dog } from './heck/Dog';
import { Entity } from './heck/Entity';
import { EnvironmentMap } from './entities/EnvironmentMap';
import { FlashyBall } from './entities/FlashyBall';
import { FlickyParticles } from './entities/FlickyParticles';
import { ForwardCamera } from './entities/ForwardCamera';
import { Glitch } from './entities/Glitch';
import { IBLLUT } from './entities/IBLLUT';
import { IFSAsUsual } from './entities/IFSAsUsual';
import { Lambda } from './heck/components/Lambda';
import { NoiseVoxels } from './entities/NoiseVoxels';
import { PixelSorter } from './entities/PixelSorter';
import { Post } from './entities/Post';
import { RTInspector } from './entities/RTInspector';
import { SSR } from './entities/SSR';
import { SceneBegin } from './entities/SceneBegin';
import { SceneCrystals } from './entities/SceneCrystals';
import { SceneDynamic } from './entities/SceneDynamic';
import { SceneNeuro } from './entities/SceneNeuro';
import { ScenePsy } from './entities/ScenePsy';
import { Serial } from './entities/Serial';
import { SphereParticles } from './entities/SphereParticles';
import { SufferTexts } from './entities/SufferTexts';
import { Swap, Vector3 } from '@fms-cat/experimental';
import { TestScreen } from './entities/TestScreen';
import { Tetrahedron } from './entities/Tetrahedron';
import { TextOverlay } from './entities/TextOverlay';
import { arraySetDelete } from './utils/arraySetDelete';
import { auto, automaton } from './globals/automaton';
import { music } from './globals/music';
import { randomTexture } from './globals/randomTexture';
// -- dog ------------------------------------------------------------------------------------------
export const dog = new Dog();
const canvasRenderTarget = new CanvasRenderTarget();
// Mr. Update Everything
dog.root.components.push( new Lambda( {
onUpdate: () => {
if ( process.env.DEV ) {
Component.gpuTimer!.update();
}
randomTexture.update();
automaton.update( music.time );
},
name: process.env.DEV && 'main/update',
} ) );
// -- util -----------------------------------------------------------------------------------------
class EntityReplacer<T extends Entity> {
public current!: T;
public creator: () => T;
public constructor( creator: () => T, name?: string ) {
this.creator = creator;
this.replace();
if ( name ) {
auto( `${ name }/active`, ( { uninit } ) => {
const entity = this.current;
if ( entity ) {
entity.active = !uninit;
entity.visible = !uninit;
}
} );
}
}
public replace(): void {
if ( process.env.DEV ) {
if ( this.current ) {
arraySetDelete( dog.root.children, this.current );
}
}
this.current = this.creator();
dog.root.children.push( this.current );
// not visible by default
this.current.active = false;
this.current.visible = false;
}
}
// -- bake -----------------------------------------------------------------------------------------
const ibllut = new IBLLUT();
dog.root.children.push( ibllut );
const replacerFlickyParticles = new EntityReplacer(
() => new FlickyParticles(),
'FlickyParticles',
);
if ( process.env.DEV && module.hot ) {
module.hot.accept( './entities/FlickyParticles', () => {
replacerFlickyParticles.replace();
} );
}
const replacerSufferTexts = new EntityReplacer(
() => new SufferTexts(),
'SufferTexts',
);
if ( process.env.DEV && module.hot ) {
module.hot.accept( './entities/SufferTexts', () => {
replacerSufferTexts.replace();
} );
}
const replacerSphereParticles = new EntityReplacer(
() => new SphereParticles(),
'SphereParticles',
);
if ( process.env.DEV && module.hot ) {
module.hot.accept( './entities/SphereParticles', () => {
replacerSphereParticles.replace();
} );
}
const replacerFlashyBall = new EntityReplacer(
() => new FlashyBall(),
'FlashyBall',
);
if ( process.env.DEV && module.hot ) {
module.hot.accept( './entities/FlashyBall', () => {
replacerFlashyBall.replace();
} );
}
const replacerTetrahedron = new EntityReplacer(
() => new Tetrahedron(),
'Tetrahedron',
);
if ( process.env.DEV && module.hot ) {
module.hot.accept( './entities/Tetrahedron', () => {
replacerTetrahedron.replace();
} );
}
const replacerNoiseVoxels = new EntityReplacer(
() => new NoiseVoxels(),
'NoiseVoxels',
);
if ( process.env.DEV && module.hot ) {
module.hot.accept( './entities/NoiseVoxels', () => {
replacerNoiseVoxels.replace();
} );
}
const replacerIFSAsUsual = new EntityReplacer(
() => new IFSAsUsual(),
'IFSAsUsual',
);
if ( process.env.DEV && module.hot ) {
module.hot.accept( './entities/IFSAsUsual', () => {
replacerIFSAsUsual.replace();
} );
}
const replacerSceneBegin = new EntityReplacer(
() => new SceneBegin( { scenes: [ dog.root ] } ),
'SceneBegin'
);
if ( process.env.DEV && module.hot ) {
module.hot.accept( './entities/SceneBegin', () => {
replacerSceneBegin.current.lights.map( ( light ) => arraySetDelete( lights, light ) );
replacerSceneBegin.replace();
lights.push( ...replacerSceneBegin.current.lights );
} );
}
const replacerSceneCrystals = new EntityReplacer(
() => new SceneCrystals( { scenes: [ dog.root ] } ),
'SceneCrystals',
);
if ( process.env.DEV && module.hot ) {
module.hot.accept( './entities/SceneCrystals', () => {
replacerSceneCrystals.current.lights.map( ( light ) => arraySetDelete( lights, light ) );
replacerSceneCrystals.replace();
lights.push( ...replacerSceneCrystals.current.lights );
replacerSceneCrystals.current.setDefferedCameraTarget( deferredCamera.cameraTarget );
} );
}
const replacerSceneDynamic = new EntityReplacer(
() => new SceneDynamic( { scenes: [ dog.root ] } ),
'SceneDynamic',
);
if ( process.env.DEV && module.hot ) {
module.hot.accept( './entities/SceneDynamic', () => {
replacerSceneDynamic.current.lights.map( ( light ) => arraySetDelete( lights, light ) );
replacerSceneDynamic.replace();
lights.push( ...replacerSceneDynamic.current.lights );
replacerSceneDynamic.current.setDefferedCameraTarget( deferredCamera.cameraTarget );
} );
}
const replacerSceneNeuro = new EntityReplacer(
() => new SceneNeuro( { scenes: [ dog.root ] } ),
'SceneNeuro'
);
if ( process.env.DEV && module.hot ) {
module.hot.accept( './entities/SceneNeuro', () => {
replacerSceneNeuro.current.lights.map( ( light ) => arraySetDelete( lights, light ) );
replacerSceneNeuro.replace();
lights.push( ...replacerSceneNeuro.current.lights );
replacerSceneNeuro.current.setDefferedCameraTarget( deferredCamera.cameraTarget );
} );
}
const replacerScenePsy = new EntityReplacer(
() => new ScenePsy( { scenes: [ dog.root ] } ),
'ScenePsy'
);
if ( process.env.DEV && module.hot ) {
module.hot.accept( './entities/ScenePsy', () => {
replacerScenePsy.current.lights.map( ( light ) => arraySetDelete( lights, light ) );
replacerScenePsy.replace();
lights.push( ...replacerScenePsy.current.lights );
} );
}
// -- things that is not an "object" ---------------------------------------------------------------
const swapOptions = {
width: canvasRenderTarget.width,
height: canvasRenderTarget.height
};
const swap = new Swap(
new BufferRenderTarget( {
...swapOptions,
name: process.env.DEV && 'main/postSwap0',
} ),
new BufferRenderTarget( {
...swapOptions,
name: process.env.DEV && 'main/postSwap1',
} ),
);
const lights = [
...replacerSceneBegin.current.lights,
...replacerSceneNeuro.current.lights,
...replacerSceneDynamic.current.lights,
...replacerSceneCrystals.current.lights,
...replacerScenePsy.current.lights,
];
// const light2 = new LightEntity( {
// root: dog.root,
// shadowMapFov: 90.0,
// shadowMapNear: 1.0,
// shadowMapFar: 20.0,
// namePrefix: process.env.DEV && 'light2',
// } );
// light2.color = [ 50.0, 30.0, 40.0 ];
// light2.transform.lookAt( new Vector3( [ -4.0, -2.0, 6.0 ] ) );
// dog.root.children.push( light2 );
const cubemapCamera = new CubemapCameraEntity( {
scenes: [ dog.root ],
lights,
} );
dog.root.children.push( cubemapCamera );
const environmentMap = new EnvironmentMap( {
cubemap: cubemapCamera.target,
} );
dog.root.children.push( environmentMap );
// -- camera ---------------------------------------------------------------------------------------
const deferredCamera = new DeferredCamera( {
scenes: [ dog.root ],
target: swap.o,
lights,
textureIBLLUT: ibllut.texture,
textureEnv: environmentMap.texture,
} );
dog.root.children.push( deferredCamera );
replacerSceneNeuro.current.setDefferedCameraTarget( deferredCamera.cameraTarget );
replacerSceneDynamic.current.setDefferedCameraTarget( deferredCamera.cameraTarget );
replacerSceneCrystals.current.setDefferedCameraTarget( deferredCamera.cameraTarget );
const forwardCamera = new ForwardCamera( {
scenes: [ dog.root ],
target: swap.o,
lights,
} );
dog.root.children.push( forwardCamera );
dog.root.components.push( new Lambda( {
onUpdate: ( { time } ) => {
const r = auto( 'Camera/rot/r' );
const t = auto( 'Camera/rot/t' );
const p = auto( 'Camera/rot/p' );
const x = auto( 'Camera/pos/x' );
const y = auto( 'Camera/pos/y' );
const z = auto( 'Camera/pos/z' );
const roll = auto( 'Camera/roll' );
const shake = auto( 'Camera/shake' );
const st = Math.sin( t );
const ct = Math.cos( t );
const sp = Math.sin( p );
const cp = Math.cos( p );
const wubPosAmp = 0.01;
const wubPosTheta = 3.0 * time;
const wubTarAmp = 0.02;
const wubTarTheta = 4.21 * time;
[ deferredCamera, forwardCamera ].map( ( camera ) => {
camera.transform.lookAt(
new Vector3( [
r * ct * sp + wubPosAmp * Math.sin( wubPosTheta ),
r * st + wubPosAmp * Math.sin( 2.0 + wubPosTheta ),
r * ct * cp + wubPosAmp * Math.sin( 4.0 + wubPosTheta ),
] ),
new Vector3( [
wubTarAmp * Math.sin( wubTarTheta ),
wubTarAmp * Math.sin( 2.0 + wubTarTheta ),
wubTarAmp * Math.sin( 4.0 + wubTarTheta ),
] ),
undefined,
0.02 * Math.sin( 2.74 * time ) + roll,
);
camera.transform.position = camera.transform.position.add(
new Vector3( [ x, y, z ] )
);
if ( shake > 0.0 ) {
camera.transform.position = camera.transform.position.add(
new Vector3( [
Math.sin( 45.0 * time ),
Math.sin( 2.0 + 48.0 * time ),
Math.sin( 4.0 + 51.0 * time )
] ).scale( shake )
);
}
auto( 'Camera/fov', ( { value } ) => {
camera.camera.fov = 90.0 * value;
} );
} );
},
name: process.env.DEV && 'main/updateCamera',
} ) );
swap.swap();
const ssr = new SSR( {
camera: deferredCamera,
shaded: swap.i,
target: swap.o,
} );
dog.root.children.push( ssr );
// -- post -----------------------------------------------------------------------------------------
swap.swap();
const antialias = new Antialias( {
input: swap.i,
target: swap.o
} );
dog.root.children.push( antialias );
swap.swap();
const bigBlur = new BigBlur( {
input: swap.i,
target: swap.o,
} );
dog.root.children.push( bigBlur );
const textOverlay = new TextOverlay( {
target: swap.o,
} );
dog.root.children.push( textOverlay );
swap.swap();
const bloom = new Bloom( {
input: swap.i,
target: swap.o
} );
dog.root.children.push( bloom );
swap.swap();
const glitch = new Glitch( {
input: swap.i,
target: swap.o,
} );
dog.root.children.push( glitch );
swap.swap();
const pixelSorter = new PixelSorter( {
input: swap.i,
target: swap.o,
} );
dog.root.children.push( pixelSorter );
swap.swap();
const serial = new Serial( {
input: swap.i,
target: swap.o,
} );
dog.root.children.push( serial );
swap.swap();
const dvi = new DVi( {
input: swap.i,
target: swap.o,
} );
dog.root.children.push( dvi );
swap.swap();
const post = new Post( {
input: swap.i,
target: canvasRenderTarget
} );
dog.root.children.push( post );
const testScreen = new TestScreen( {
target: canvasRenderTarget
} );
dog.root.children.push( testScreen );
if ( process.env.DEV ) {
const rtInspector = new RTInspector( {
target: canvasRenderTarget
} );
dog.root.children.push( rtInspector );
} | the_stack |
import * as admin from 'firebase-admin'
import fetch from 'node-fetch'
import { omit } from 'lodash'
import { PROJECTS_COLLECTION } from '../constants/firebasePaths'
import {
authClientFromServiceAccount,
serviceAccountFromFirestorePath
} from '../utils/serviceAccounts'
import { ACTION_RUNNER_EVENT_PATH } from './constants'
import { to } from '../utils/async'
import {
writeDocsInBatches,
isDocPath
} from '../utils/firestore'
const ACTION_RUNNER_RESPONSES_PATH = `responses/${ACTION_RUNNER_EVENT_PATH}`
interface ErrorInfo {
message?: string
status?: string
}
interface DataObject {
id: string
data: any
}
/**
* Create data object with values for each document with keys being doc.id.
* @param snap - Data for which to create
* an ordered array.
* @returns Object documents from snapshot or null
*/
function dataArrayFromSnap(
snap: admin.firestore.DocumentSnapshot | admin.firestore.QuerySnapshot | any
): DataObject[] {
const data: DataObject[] = []
if (snap.data && snap.exists) {
data.push({ id: snap.id, data: snap.data() })
} else if (snap.forEach) {
snap.forEach((doc) => {
data.push({ id: doc.id, data: doc.data() || doc })
})
}
return data
}
/**
* Write response object with status "success" or "error". If
* status is "error", message is also included.
* @param snap - Functions snapshot object
* @param context - Functions context object
* @param error - Error object
* @returns Resolves with results of database write promise
*/
export function updateResponseOnRTDB(snap, context, error?: ErrorInfo) {
const response: any = {
completed: true,
completedAt: admin.database.ServerValue.TIMESTAMP
}
if (error) {
response.error = error.message || error
response.status = 'error'
} else {
response.status = 'success'
}
return admin
.database()
.ref(`${ACTION_RUNNER_RESPONSES_PATH}/${context.params.pushId}`)
.set(response)
}
/**
* Update request with status "started"
* @param snap - Functions snapshot object
* @returns Resolves with results of database update promise
*/
export async function updateRequestAsStarted(snap: admin.database.DataSnapshot): Promise<any> {
const response = {
status: 'started',
startedAt: admin.database.ServerValue.TIMESTAMP
}
const [dbUpdateError, updateRes] = await to(snap.ref.update(response))
if (dbUpdateError) {
console.error(
'Error updating request as started within RTDB:',
dbUpdateError.message || dbUpdateError
)
throw dbUpdateError
}
return updateRes
}
/**
* Write event to project events subcollection
* @param eventData - Functions snapshot object
* @param eventData.projectId - Functions snapshot object
* @returns Resolves with results of firstore add promise
*/
export async function emitProjectEvent(eventData): Promise<any> {
const { projectId } = eventData
const [writeErr, writeRes] = await to(
admin
.firestore()
.collection(`${PROJECTS_COLLECTION}/${projectId}/events`)
.add({
...eventData,
createdBy: 'system',
createdAt: admin.firestore.FieldValue.serverTimestamp()
})
)
if (writeErr) {
console.error(
'Error writing event to project',
writeErr.message || writeErr
)
throw writeErr
}
return writeRes
}
/**
* Update response object within Real Time Database with progress information
* about an action.
* @param snap - Snapshot
* @param context - event context
* @param actionInfo - Info about action
* @param actionInfo.stepIdx - Index of current step
* @param actionInfo.totalNumSteps - Total number of steps in action
* @returns Resolves with results of database write promise
*/
export function updateResponseWithProgress(
responseId: string,
{ stepIdx, totalNumSteps }: { stepIdx: number, totalNumSteps: number }
): Promise<any> {
const response = {
status: 'running',
stepStatus: {
complete: {
[stepIdx]: true
}
},
progress: stepIdx / totalNumSteps,
updatedAt: admin.database.ServerValue.TIMESTAMP
}
return admin
.database()
.ref(`${ACTION_RUNNER_RESPONSES_PATH}/${responseId}`)
.update(response)
}
/**
* Write error to response object within Database
* @param snap - Functions snapshot object
* @param context - Functions context object
* @returns Resolves with results of database write promise
*/
export function updateResponseWithError(responseId: string): Promise<any> {
const response = {
status: 'error',
complete: true,
updatedAt: admin.database.ServerValue.TIMESTAMP
}
return admin
.database()
.ref(`${ACTION_RUNNER_RESPONSES_PATH}/${responseId}`)
.update(response)
}
/**
* Update response object within Real Time Database with error information about
* an action
* @param snap - Functions snapshot object
* @param context - Context of event
* @param actionInfo - Info about action
* @param actionInfo.stepIdx - Index of current step
* @param actionInfo.totalNumSteps - Total number of steps in action
* @returns {Promise} Resolves with results of database write promise
*/
export function updateResponseWithActionError(
responseId: string,
{ stepIdx, totalNumSteps }
): Promise<any> {
const response = {
status: 'error',
stepCompleteStatus: {
complete: {
[stepIdx]: false
},
error: {
[stepIdx]: true
}
},
progress: stepIdx / totalNumSteps,
updatedAt: admin.database.ServerValue.TIMESTAMP
}
return admin
.database()
.ref(`${ACTION_RUNNER_RESPONSES_PATH}/${responseId}`)
.update(response)
}
/**
* Write an event to a project's "events" subcollection
* @param projectId - id of project in which event should be placed
* @param extraEventAttributes - Data to attach to the event
* @returns Resolves with results of pushing event object
*/
export async function writeProjectEvent(projectId: string, extraEventAttributes = {}) {
const eventObject = {
createdByType: 'system',
createdAt: admin.firestore.FieldValue.serverTimestamp(),
...omit(extraEventAttributes, ['updatedAt', '_highlightResult'])
}
const eventsRef = admin
.firestore()
.collection(`${PROJECTS_COLLECTION}/${projectId}/events`)
const [addErr, addRes] = await to(eventsRef.add(eventObject))
if (addErr) {
const errMsg = `Error adding event data to Project events for project: ${projectId}`
console.error(errMsg, addErr)
throw new Error(errMsg)
}
return addRes
}
/**
* Convert a collection snapshot into an array (uses forEach).
* @param collectionsSnap - Collection snap object with forEach
* @returns List of collection snapshot ids
*/
function collectionsSnapToArray(collectionsSnap): string[] {
const collectionsIds: string[] = []
if (collectionsSnap.forEach) {
collectionsSnap.forEach((collectionSnap) => {
collectionsIds.push(collectionSnap.id)
})
}
return collectionsIds
}
/**
* Get collection names from provided settings falling back to getting all
* collection names for the provided Firestore ref using getCollections.
* @param subcollectionSetting - Current subcollection setting (list of names)
* @param ref - Firestore reference
* @returns Resolves with an array of collection names
*/
async function getSubcollectionNames(subcollectionSetting: string[] | boolean, ref: admin.firestore.DocumentReference): Promise<any> {
// Return if the provided setting is an array (assuming it is an array of names)
if (Array.isArray(subcollectionSetting)) {
return subcollectionSetting
}
// Throw an error is listCollections method does not exist
// In place since getCollections was no longer a method which threw an unclear error
if (typeof ref.listCollections !== 'function') {
console.error('Document ref does not have listCollections method', {
subcollectionSetting,
ref,
path: ref.path,
type: typeof ref
})
throw new Error('Document ref does not have listCollections method')
}
// Get collection refs
const [getCollectionsErr, collections] = await to(ref.listCollections())
// Handle errors in batch write
if (getCollectionsErr) {
console.error(
'Error getting collections: ',
getCollectionsErr.message || getCollectionsErr
)
throw getCollectionsErr
}
return collectionsSnapToArray(collections)
}
interface FirestoreBatchCopyOptions {
copySubcollections?: boolean
merge?: boolean
}
/**
* Write document updates in a batch process.
* @param params - Params object
* @param params.srcRef - Instance on which to create ref
* @param params.destRef - Destination path under which data should be written
* @param params.opts - Options object (can contain merge)
* @returns Resolves with results of batch commit
*/
export async function batchCopyBetweenFirestoreRefs({
srcRef,
destRef,
opts
}: {
srcRef: FirebaseFirestore.DocumentReference | FirebaseFirestore.CollectionReference | any
destRef: FirebaseFirestore.DocumentReference | FirebaseFirestore.CollectionReference | any
opts: FirestoreBatchCopyOptions
}): Promise<any> {
const { copySubcollections } = opts || {}
// TODO: Switch to querying in batches limited to 500 so reads/writes match
// Get data from src reference
const [getErr, firstSnap] = await to(srcRef.get())
// Handle errors getting original data
if (getErr) {
console.error(
'Error getting data from first instance: ',
getErr.message || getErr
)
throw getErr
}
// Handle single document copy
if (isDocPath(destRef.path)) {
const docData = firstSnap.data()
// Handle source document data not existing
if (!docData) {
throw new Error(`Document at path ${srcRef.path} not found`)
}
const [docWriteErr] = await to(destRef.set(docData, { merge: true }))
// Handle errors in single document write
if (docWriteErr) {
console.error(
`Error copying doc from "${srcRef.path}" to "${destRef.path}": `,
docWriteErr.message || docWriteErr
)
throw docWriteErr
}
// Set with merge to do updating while also handling docs not existing
return destRef.set(docData, { merge: true })
}
// Get data into array (regardless of single doc or collection)
const dataFromSrc = dataArrayFromSnap(firstSnap)
// Write docs (batching if necessary)
const [writeErr] = await to(
writeDocsInBatches(destRef.firestore, destRef.path, dataFromSrc, opts)
)
// Handle errors in batch write
if (writeErr) {
console.error(
`Error batch copying docs from "${srcRef.id}" to "${destRef.id}": `,
writeErr.message || writeErr
)
throw writeErr
}
// Exit if not copying subcollections
if (!copySubcollections) {
console.log(
`Successfully copied docs from Firestore collection "${srcRef.id}"`
)
return null
}
console.log(
`Successfully copied docs from Firestore collection "${srcRef.id}" starting subcollections copy...`
)
// Write subcollections of all documents
const [subcollectionWriteErr] = await to(
Promise.all(
dataFromSrc.map(async ({ id: childDocId }) => {
const docSrcRef = srcRef.doc(childDocId)
const docDestRef = destRef.doc(childDocId)
// Get subcollection names from settings falling back to all subcollections
const subcollectionNames = await getSubcollectionNames(
copySubcollections,
docSrcRef
)
// Exit if the document does not have any subcollections
if (!subcollectionNames.length) {
return null
}
// Copy subcollections in batches of 500 docs at a time
return Promise.all(
subcollectionNames.map((collectionName) =>
batchCopyBetweenFirestoreRefs({
srcRef: docSrcRef.collection(collectionName),
destRef: docDestRef.collection(collectionName),
opts
})
)
)
})
)
)
if (subcollectionWriteErr) {
console.error(
`Error writing subcollections for collection "${srcRef.id}": ${
subcollectionWriteErr.message || ''
}`,
subcollectionWriteErr
)
throw subcollectionWriteErr
}
console.log(
`Successfully copied docs from Firestore path: ${srcRef.id} with subcollections: ${copySubcollections}`
)
return null
}
/**
* Request google APIs with auth attached
* @param opts - Google APIs method to call
* @param opts.projectId - Id of fireadmin project
* @param opts.environmentId - Id of fireadmin environment
* @param opts.databaseName - Name of database on which to run (defaults to project base DB)
* @param rtdbPath - Path of RTDB data to get
* @returns Resolves with results of RTDB shallow get
*/
export async function shallowRtdbGet(opts, rtdbPath: string | undefined): Promise<any> {
const { projectId, environmentId, databaseName } = opts
if (!environmentId) {
throw new Error(
'environmentId is required for action to authenticate through serviceAccount'
)
}
// Get Service account data from resource (i.e Storage, Firestore, etc)
const [saErr, serviceAccount] = await to(
serviceAccountFromFirestorePath(
`${PROJECTS_COLLECTION}/${projectId}/environments/${environmentId}`
)
)
if (saErr) {
console.error(
`Error getting service account: ${saErr.message || ''}`,
saErr
)
throw saErr
}
const client: any = await authClientFromServiceAccount(serviceAccount)
const apiUrl = `https://${
databaseName || serviceAccount.project_id
}.firebaseio.com/${rtdbPath || ''}.json?access_token=${
client.credentials.access_token
}&shallow=true`
const [getErr, response] = await to(fetch(apiUrl))
const responseJson = await response.json()
if (getErr) {
console.error(
`Firebase REST API errored when calling path "${rtdbPath}" for environment "${projectId}/${environmentId}" : ${
getErr.statusCode
} \n ${getErr.error ? getErr.error.message : ''}`
)
throw getErr.error || getErr
}
if (typeof responseJson === 'string' || responseJson instanceof String) {
return JSON.parse(response as string)
}
return responseJson
} | the_stack |
import { TxData, TxDataPayable } from "../../types";
import * as promisify from "tiny-promisify";
import { classUtils } from "../../../utils/class_utils";
import { Web3Utils } from "../../../utils/web3_utils";
import { BigNumber } from "../../../utils/bignumber";
import { MockERC721Receiver as ContractArtifacts } from "@dharmaprotocol/contracts";
import * as Web3 from "web3";
import { BaseContract, CONTRACT_WRAPPER_ERRORS } from "./base_contract_wrapper";
export class MockERC721ReceiverContract extends BaseContract {
public getMockReturnValue = {
async callAsync(
functionName: string,
argsSignature: string,
defaultBlock?: Web3.BlockParam,
): Promise<string> {
const self = this as MockERC721ReceiverContract;
const result = await promisify<string>(
self.web3ContractInstance.getMockReturnValue.call,
self.web3ContractInstance,
)(functionName, argsSignature);
return result;
},
};
public setReturnValueForERC721ReceivedHook = {
async sendTransactionAsync(_returnValue: string, txData: TxData = {}): Promise<string> {
const self = this as MockERC721ReceiverContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(
txData,
self.setReturnValueForERC721ReceivedHook.estimateGasAsync.bind(self, _returnValue),
);
const txHash = await promisify<string>(
self.web3ContractInstance.setReturnValueForERC721ReceivedHook,
self.web3ContractInstance,
)(_returnValue, txDataWithDefaults);
return txHash;
},
async estimateGasAsync(_returnValue: string, txData: TxData = {}): Promise<number> {
const self = this as MockERC721ReceiverContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData);
const gas = await promisify<number>(
self.web3ContractInstance.setReturnValueForERC721ReceivedHook.estimateGas,
self.web3ContractInstance,
)(_returnValue, txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(_returnValue: string, txData: TxData = {}): string {
const self = this as MockERC721ReceiverContract;
const abiEncodedTransactionData = self.web3ContractInstance.setReturnValueForERC721ReceivedHook.getData();
return abiEncodedTransactionData;
},
};
public setShouldRevert = {
async sendTransactionAsync(_shouldRevert: boolean, txData: TxData = {}): Promise<string> {
const self = this as MockERC721ReceiverContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(
txData,
self.setShouldRevert.estimateGasAsync.bind(self, _shouldRevert),
);
const txHash = await promisify<string>(
self.web3ContractInstance.setShouldRevert,
self.web3ContractInstance,
)(_shouldRevert, txDataWithDefaults);
return txHash;
},
async estimateGasAsync(_shouldRevert: boolean, txData: TxData = {}): Promise<number> {
const self = this as MockERC721ReceiverContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData);
const gas = await promisify<number>(
self.web3ContractInstance.setShouldRevert.estimateGas,
self.web3ContractInstance,
)(_shouldRevert, txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(_shouldRevert: boolean, txData: TxData = {}): string {
const self = this as MockERC721ReceiverContract;
const abiEncodedTransactionData = self.web3ContractInstance.setShouldRevert.getData();
return abiEncodedTransactionData;
},
};
public mockReturnValue = {
async sendTransactionAsync(
functionName: string,
argsSignature: string,
returnValue: string,
txData: TxData = {},
): Promise<string> {
const self = this as MockERC721ReceiverContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(
txData,
self.mockReturnValue.estimateGasAsync.bind(
self,
functionName,
argsSignature,
returnValue,
),
);
const txHash = await promisify<string>(
self.web3ContractInstance.mockReturnValue,
self.web3ContractInstance,
)(functionName, argsSignature, returnValue, txDataWithDefaults);
return txHash;
},
async estimateGasAsync(
functionName: string,
argsSignature: string,
returnValue: string,
txData: TxData = {},
): Promise<number> {
const self = this as MockERC721ReceiverContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData);
const gas = await promisify<number>(
self.web3ContractInstance.mockReturnValue.estimateGas,
self.web3ContractInstance,
)(functionName, argsSignature, returnValue, txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(
functionName: string,
argsSignature: string,
returnValue: string,
txData: TxData = {},
): string {
const self = this as MockERC721ReceiverContract;
const abiEncodedTransactionData = self.web3ContractInstance.mockReturnValue.getData();
return abiEncodedTransactionData;
},
};
public wasOnERC721ReceivedCalledWith = {
async callAsync(
_address: string,
_tokenId: BigNumber,
_data: string,
defaultBlock?: Web3.BlockParam,
): Promise<boolean> {
const self = this as MockERC721ReceiverContract;
const result = await promisify<boolean>(
self.web3ContractInstance.wasOnERC721ReceivedCalledWith.call,
self.web3ContractInstance,
)(_address, _tokenId, _data);
return result;
},
};
public reset = {
async sendTransactionAsync(txData: TxData = {}): Promise<string> {
const self = this as MockERC721ReceiverContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(
txData,
self.reset.estimateGasAsync.bind(self),
);
const txHash = await promisify<string>(
self.web3ContractInstance.reset,
self.web3ContractInstance,
)(txDataWithDefaults);
return txHash;
},
async estimateGasAsync(txData: TxData = {}): Promise<number> {
const self = this as MockERC721ReceiverContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData);
const gas = await promisify<number>(
self.web3ContractInstance.reset.estimateGas,
self.web3ContractInstance,
)(txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(txData: TxData = {}): string {
const self = this as MockERC721ReceiverContract;
const abiEncodedTransactionData = self.web3ContractInstance.reset.getData();
return abiEncodedTransactionData;
},
};
public onERC721Received = {
async sendTransactionAsync(
_address: string,
_tokenId: BigNumber,
_data: string,
txData: TxData = {},
): Promise<string> {
const self = this as MockERC721ReceiverContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(
txData,
self.onERC721Received.estimateGasAsync.bind(self, _address, _tokenId, _data),
);
const txHash = await promisify<string>(
self.web3ContractInstance.onERC721Received,
self.web3ContractInstance,
)(_address, _tokenId, _data, txDataWithDefaults);
return txHash;
},
async estimateGasAsync(
_address: string,
_tokenId: BigNumber,
_data: string,
txData: TxData = {},
): Promise<number> {
const self = this as MockERC721ReceiverContract;
const txDataWithDefaults = await self.applyDefaultsToTxDataAsync(txData);
const gas = await promisify<number>(
self.web3ContractInstance.onERC721Received.estimateGas,
self.web3ContractInstance,
)(_address, _tokenId, _data, txDataWithDefaults);
return gas;
},
getABIEncodedTransactionData(
_address: string,
_tokenId: BigNumber,
_data: string,
txData: TxData = {},
): string {
const self = this as MockERC721ReceiverContract;
const abiEncodedTransactionData = self.web3ContractInstance.onERC721Received.getData();
return abiEncodedTransactionData;
},
};
constructor(web3ContractInstance: Web3.ContractInstance, defaults: Partial<TxData>) {
super(web3ContractInstance, defaults);
classUtils.bindAll(this, ["web3ContractInstance", "defaults"]);
}
public static async deployed(
web3: Web3,
defaults: Partial<TxData>,
): Promise<MockERC721ReceiverContract> {
const web3Utils = new Web3Utils(web3);
const currentNetwork = await web3Utils.getNetworkIdAsync();
const { abi, networks }: { abi: any; networks: any } = ContractArtifacts;
if (networks[currentNetwork]) {
const { address: contractAddress } = networks[currentNetwork];
const contractExists = await web3Utils.doesContractExistAtAddressAsync(contractAddress);
if (contractExists) {
const web3ContractInstance = web3.eth.contract(abi).at(contractAddress);
return new MockERC721ReceiverContract(web3ContractInstance, defaults);
} else {
throw new Error(
CONTRACT_WRAPPER_ERRORS.CONTRACT_NOT_FOUND_ON_NETWORK(
"DebtKernel",
currentNetwork,
),
);
}
} else {
throw new Error(
CONTRACT_WRAPPER_ERRORS.CONTRACT_NOT_FOUND_ON_NETWORK(
"MockERC721Receiver",
currentNetwork,
),
);
}
}
public static async at(
address: string,
web3: Web3,
defaults: Partial<TxData>,
): Promise<MockERC721ReceiverContract> {
const web3Utils = new Web3Utils(web3);
const { abi }: { abi: any } = ContractArtifacts;
const contractExists = await web3Utils.doesContractExistAtAddressAsync(address);
const currentNetwork = await web3Utils.getNetworkIdAsync();
if (contractExists) {
const web3ContractInstance = web3.eth.contract(abi).at(address);
return new MockERC721ReceiverContract(web3ContractInstance, defaults);
} else {
throw new Error(
CONTRACT_WRAPPER_ERRORS.CONTRACT_NOT_FOUND_ON_NETWORK(
"MockERC721Receiver",
currentNetwork,
),
);
}
}
} // tslint:disable:max-file-line-count | the_stack |
import * as chai from 'chai';
import chaiHttp = require('chai-http');
import {TestHelper} from '../TestHelper';
import {FixtureUtils} from '../../fixtures/FixtureUtils';
import {Course} from '../../src/models/Course';
import {ICourse} from '../../../shared/models/ICourse';
import {User} from '../../src/models/User';
import {Lecture} from '../../src/models/Lecture';
import {ILecture} from '../../../shared/models/ILecture';
import {IUnit} from '../../../shared/models/units/IUnit';
import {Unit} from '../../src/models/units/Unit';
import {IFreeTextUnit} from '../../../shared/models/units/IFreeTextUnit';
import {IFreeTextUnitModel} from '../../src/models/units/FreeTextUnit';
import {ICodeKataModel} from '../../src/models/units/CodeKataUnit';
import {ICodeKataUnit} from '../../../shared/models/units/ICodeKataUnit';
import {ITaskUnitModel} from '../../src/models/units/TaskUnit';
import {ITaskUnit} from '../../../shared/models/units/ITaskUnit';
import {API_NOTIFICATION_TYPE_ALL_CHANGES, NotificationSettings} from '../../src/models/NotificationSettings';
import {Notification} from '../../src/models/Notification';
import {WhitelistUser} from '../../src/models/WhitelistUser';
chai.use(chaiHttp);
const should = chai.should();
const expect = chai.expect;
const BASE_URL = '/api/export';
const testHelper = new TestHelper(BASE_URL);
/**
* Provides simple shared setup functionality used by the export access denial unit tests.
*
* @returns A course with at least one unit/lecture and an unauthorizedTeacher (i.e. a teacher that isn't part of the course).
*/
async function exportAccessDenialSetup() {
const course = await FixtureUtils.getRandomCourseWithAllUnitTypes();
const unauthorizedTeacher = await FixtureUtils.getUnauthorizedTeacherForCourse(course);
return {course, unauthorizedTeacher};
}
async function testNotFound(what: string) {
const admin = await FixtureUtils.getRandomAdmin();
const result = await testHelper.commonUserGetRequest(admin, `/${what}/000000000000000000000000`);
result.status.should.be.equal(404);
}
describe('Export', async () => {
beforeEach(async () => {
await testHelper.resetForNextTest();
});
describe(`GET ${BASE_URL}`, async () => {
it('should export units', async () => {
const admin = await FixtureUtils.getRandomAdmin();
const units = await Unit.find();
for (const unit of units) {
let unitJson: IUnit;
const exportResult = await testHelper.commonUserGetRequest(admin, `/unit/${unit._id}`);
exportResult.status.should.be.equal(200, 'failed to export ' + unit.name);
unitJson = exportResult.body;
should.not.exist(exportResult.body.createdAt);
should.not.exist(exportResult.body.__v);
should.not.exist(exportResult.body.updatedAt);
should.not.exist(unitJson._id);
// TODO: share this check since it is the same one as in import.ts
unitJson.name.should.be.equal(unit.name);
// check nullable fields
if (unit.description != null) {
unitJson.description.should.be.equal(unit.description);
} else {
should.not.exist(unitJson.description);
}
if (unit.weight != null) {
unitJson.weight.should.be.equal(unit.weight);
} else {
should.not.exist(unitJson.weight);
}
// 'progressableUnits' do have some additional fields
if (unit.progressable === true) {
unitJson.progressable.should.be.equal(unit.progressable);
const progressableUnit = <any>unit;
if (progressableUnit.deadline != null) {
(<any>unitJson).deadline.should.be.equal(progressableUnit.deadline);
}
}
// TODO: Do not use any cast
(<any>unitJson).__t.should.be.equal((<any>unit).__t);
// check different types
switch ((<any>unit).__t) {
case 'free-text':
const freeTextUnit = <IFreeTextUnitModel>unit;
(<IFreeTextUnit>unitJson).markdown.should.be.equal(freeTextUnit.markdown);
break;
case 'code-kata':
const codeKataUnit = <ICodeKataModel>unit;
(<ICodeKataUnit>unitJson).definition.should.be.equal(codeKataUnit.definition);
(<ICodeKataUnit>unitJson).code.should.be.equal(codeKataUnit.code);
(<ICodeKataUnit>unitJson).test.should.be.equal(codeKataUnit.test);
break;
case 'task':
const taskUnit = <ITaskUnitModel>unit;
(<ITaskUnit>unitJson).tasks.should.be.instanceOf(Array).and.have.lengthOf(taskUnit.tasks.length);
// maybe further test single tasks?
break;
default:
// should this fail the test?
process.stderr.write('export for "' + unit.type + '" is not completly tested');
break;
}
}
});
it('should export lectures', async () => {
const admin = await FixtureUtils.getRandomAdmin();
const lectures = await Lecture.find();
for (const lecture of lectures) {
let lectureJson: ILecture;
const exportResult = await testHelper.commonUserGetRequest(admin, `/lecture/${lecture._id}`);
exportResult.status.should.be.equal(200, 'failed to export ' + lecture.name);
lectureJson = exportResult.body;
should.not.exist(exportResult.body.createdAt);
should.not.exist(exportResult.body.__v);
should.not.exist(exportResult.body.updatedAt);
should.not.exist(lectureJson._id);
lectureJson.name.should.be.equal(lecture.name);
lectureJson.description.should.be.equal(lecture.description);
lectureJson.units.should.be.instanceOf(Array).and.have.lengthOf(lecture.units.length);
}
});
it('should export courses', async () => {
const courses = await Course.find();
for (const course of courses) {
const teacher = await User.findById(course.courseAdmin);
let courseJson: ICourse;
const exportResult = await testHelper.commonUserGetRequest(teacher, `/course/${course._id}`);
exportResult.status.should.be.equal(200, 'failed to export ' + course.name);
courseJson = exportResult.body;
should.not.exist(exportResult.body.createdAt);
should.not.exist(exportResult.body.__v);
should.not.exist(exportResult.body.updatedAt);
should.not.exist(courseJson._id);
should.not.exist(courseJson.courseAdmin);
should.not.exist(courseJson.teachers);
should.not.exist(courseJson.students);
should.not.exist(courseJson.whitelist);
courseJson.name.should.be.equal(course.name);
courseJson.description.should.be.equal(course.description);
courseJson.lectures.should.be.instanceOf(Array).and.have.lengthOf(course.lectures.length);
}
});
it('should forbid unit export for an unauthorized teacher', async () => {
const {course, unauthorizedTeacher} = await exportAccessDenialSetup();
const unit = await FixtureUtils.getRandomUnitFromCourse(course);
const result = await testHelper.commonUserGetRequest(unauthorizedTeacher, `/unit/${unit._id}`);
result.status.should.be.equal(403);
});
it('should forbid lecture export for an unauthorized teacher', async () => {
const {course, unauthorizedTeacher} = await exportAccessDenialSetup();
const lecture = await FixtureUtils.getRandomLectureFromCourse(course);
const result = await testHelper.commonUserGetRequest(unauthorizedTeacher, `/lecture/${lecture._id}`);
result.status.should.be.equal(403);
});
it('should forbid course export for an unauthorized teacher', async () => {
const {course, unauthorizedTeacher} = await exportAccessDenialSetup();
const result = await testHelper.commonUserGetRequest(unauthorizedTeacher, `/course/${course._id}`);
result.status.should.be.equal(403);
});
it('should respond with 404 for a unit id that doesn\'t exist', async () => await testNotFound('unit'));
it('should respond with 404 for a lecture id that doesn\'t exist', async () => await testNotFound('lecture'));
it('should respond with 404 for a course id that doesn\'t exist', async () => await testNotFound('course'));
});
describe(`GET ${BASE_URL}/user`, async () => {
it('should export student data', async () => {
const course1 = await FixtureUtils.getRandomCourse();
const course2 = await FixtureUtils.getRandomCourse();
const taskUnit = <ITaskUnitModel>await Unit.findOne({progressable: true, __t: 'task'});
const lecture = await Lecture.findOne({units: { $in: [ taskUnit._id ] }});
const course = await Course.findOne({lectures: { $in: [ lecture._id ] }});
const student = await User.findOne({_id: { $in: course.students}});
await new NotificationSettings({
'user': student, 'course': course1,
'notificationType': API_NOTIFICATION_TYPE_ALL_CHANGES, 'emailNotification': false
}).save();
await new NotificationSettings({
'user': student, 'course': course2,
'notificationType': API_NOTIFICATION_TYPE_ALL_CHANGES, 'emailNotification': false
}).save();
await new Notification({
user: student,
changedCourse: course1,
text: 'blubba blubba'
}).save();
await new Notification({
user: student,
changedCourse: course2,
text: 'blubba blubba'
}).save();
await new WhitelistUser({
firstName: student.profile.firstName,
lastName: student.profile.lastName,
uid: student.uid,
courseId: course1._id
}).save();
const result = await testHelper.commonUserGetRequest(student, `/user`);
expect(result).to.have.status(200);
});
it('should export teacher data', async () => {
const teacher = await FixtureUtils.getRandomTeacher();
const result = await testHelper.commonUserGetRequest(teacher, `/user`);
expect(result).to.have.status(200);
});
it('should export admin data', async () => {
const admin = await FixtureUtils.getRandomAdmin();
const result = await testHelper.commonUserGetRequest(admin, `/user`);
expect(result).to.have.status(200);
});
});
}); | the_stack |
import React, { PureComponent } from 'react';
import _ from 'lodash'
import { FieldConfigSource, PanelPlugin } from 'src/packages/datav-core/src';
import { Row, Button, message} from 'antd'
import { cx } from 'emotion';
import AutoSizer from 'react-virtualized-auto-sizer';
import { PanelModel, DashboardModel } from '../../model';
import PanelWrapper from '../../PanelWrapper';
import SplitPane from 'react-split-pane';
import { Unsubscribable } from 'rxjs';
import { DisplayMode, PanelEditorTab, PanelEditorUIState } from './types';
// import { PanelEditorTabs } from './PanelEditorTabs';
import { calculatePanelSize } from './utils';
import { OptionsPaneContent } from './OptionsPane/OptionsPaneContent';
import { VariableModel } from 'src/types/templating';
// import { SubMenuItems } from 'app/features/dashboard/components/SubMenu/SubMenuItems';
import { BackButton } from 'src/views/components/BackButton/BackButton';
// import { SaveDashboardModalProxy } from '../SaveDashboard/SaveDashboardModalProxy';
import { CoreEvents, PanelState } from 'src/types';
import appEvents from 'src/core/library/utils/app_events';
import './PanelEditor.less'
import localStore from 'src/core/library/utils/localStore';
import { connect } from 'react-redux';
import { StoreState } from 'src/types'
import { getPanelEditorTabs } from './get_editor_tabs'
import { SettingOutlined } from '@ant-design/icons';
import { PanelEditorTabs } from './PanelEditorTabs';
import './PanelEditor.less'
import { updateEditorInitState, closeCompleted, setDiscardChanges } from 'src/store/reducers/panelEditor';
import { store } from 'src/store/store';
import { updateLocation ,LocationState} from 'src/store/reducers/location';
import SaveDahboard from '../SaveDashboard/SaveDashboard'
import { cleanUpEditPanel } from 'src/store/reducers/dashboard';
import { getUrlParams } from 'src/core/library/utils/url';
import { FormattedMessage } from 'react-intl';
export const PANEL_EDITOR_UI_STATE_STORAGE_KEY = 'datav.dashboard.editor.ui';
export const DEFAULT_PANEL_EDITOR_UI_STATE: PanelEditorUIState = {
isPanelOptionsVisible: true,
rightPaneSize: 400,
topPaneSize: '45%',
mode: DisplayMode.Fill,
};
enum Pane {
Right,
Top,
}
interface Props {
plugin?: PanelPlugin;
dashboard: DashboardModel;
sourcePanel: PanelModel;
tabs?: PanelEditorTab[];
panel?: PanelModel;
initDone?: boolean;
location?: LocationState;
}
interface State {
uiState: PanelEditorUIState;
saveMoalVisible: boolean
}
export class PanelEditorUnconnected extends PureComponent<Props, State> {
querySubscription: Unsubscribable;
constructor(props) {
super(props)
this.state = {
uiState: {
...DEFAULT_PANEL_EDITOR_UI_STATE,
...localStore.getObject(PANEL_EDITOR_UI_STATE_STORAGE_KEY, DEFAULT_PANEL_EDITOR_UI_STATE),
},
saveMoalVisible: false
}
this.setModalVisible = this.setModalVisible.bind(this)
}
componentDidMount() {
this.initPanelEditor();
}
componentWillUnmount() {
}
exitPanelEditor = () => {
this.panelEditorCleanUp();
store.dispatch(updateLocation({
query: { editPanel: null, tab: null },
partial: true,
}));
}
initPanelEditor = () => {
const panel = this.props.dashboard.initEditPanel(this.props.sourcePanel);
store.dispatch(updateEditorInitState({
panel: panel,
sourcePanel:this.props.sourcePanel
}))
}
panelEditorCleanUp = () => {
const {panel} = this.props
const shouldDiscardChanges = store.getState().panelEditor.shouldDiscardChanges
const { sourcePanel, dashboard } = this.props
if (!shouldDiscardChanges) {
const modifiedSaveModel = panel.getSaveModel();
const panelTypeChanged = this.props.sourcePanel.type !== panel.type;
// restore the source panel id before we update source panel
modifiedSaveModel.id = sourcePanel.id;
sourcePanel.restoreModel(modifiedSaveModel);
// Loaded plugin is not included in the persisted properties
// So is not handled by restoreModel
sourcePanel.plugin = panel.plugin;
if (panelTypeChanged) {
// dispatch(panelModelAndPluginReady({ panelId: sourcePanel.id, plugin: panel.plugin! }));
}
// Resend last query result on source panel query runner
// But do this after the panel edit editor exit process has completed
setTimeout(() => {
sourcePanel.getQueryRunner().useLastResultFrom(panel.getQueryRunner());
}, 20);
}
if (dashboard) {
dashboard.exitPanelEditor();
}
store.dispatch(cleanUpEditPanel())
// store.dispatch(closeCompleted());
}
onPanelExit = () => {
this.exitPanelEditor()
};
onDiscard = () => {
store.dispatch(setDiscardChanges(true))
this.exitPanelEditor()
};
onOpenDashboardSettings = () => {
store.dispatch(updateLocation({ query: { editview: 'settings' }, partial: true }));
};
onSaveDashboard = () => {
appEvents.emit(CoreEvents.KeybindingSaveDashboard,this.props.dashboard)
};
setModalVisible(status) {
setTimeout(() => this.setState({...this.state, saveMoalVisible: status}),100)
}
onChangeTab = (tab: PanelEditorTab) => {
store.dispatch(updateLocation({ query: { tab: tab.id }, partial: true }));
};
onFieldConfigChange = (config: FieldConfigSource) => {
const { panel } = this.props;
panel.updateFieldConfig({
...config,
});
this.forceUpdate();
};
onPanelOptionsChanged = (options: any) => {
this.props.panel.updateOptions(options);
this.forceUpdate();
};
onPanelConfigChanged = (configKey: string, value: any) => {
this.props.panel[configKey] = value;
this.props.panel.render();
this.forceUpdate();
};
onDragFinished = (pane: Pane, size?: number) => {
document.body.style.cursor = 'auto';
// When the drag handle is just clicked size is undefined
if (!size) {
return;
}
const targetPane = pane === Pane.Top ? 'topPaneSize' : 'rightPaneSize';
this.updatePanelEditorUIState({
[targetPane]: size,
});
};
onDragStarted = () => {
document.body.style.cursor = 'row-resize';
};
onDiplayModeChange = (mode: DisplayMode) => {
this.updatePanelEditorUIState({
mode: mode,
});
};
updatePanelEditorUIState(ui: Partial<PanelEditorUIState>) {
const uiState = { ...this.state.uiState, ...ui }
this.setState({
...this.state,
uiState
})
try {
localStore.setObject(PANEL_EDITOR_UI_STATE_STORAGE_KEY, uiState);
} catch (error) {
message.error(error)
}
}
onTogglePanelOptions = () => {
const { uiState } = this.state;
this.updatePanelEditorUIState({ isPanelOptionsVisible: !uiState.isPanelOptionsVisible });
};
renderPanel = () => {
const { dashboard, tabs,panel } = this.props;
const { uiState } = this.state
return (
<div className={cx('mainPaneWrapper', tabs.length === 0 && 'mainPaneWrapperNoTabs')} style={{ paddingRight: uiState.isPanelOptionsVisible ? 0 : '16px' }}>
<div className={'panelWrapper'}>
<AutoSizer>
{({ width, height }) => {
if (width < 3 || height < 3) {
return null;
}
return (
<div className={'centeringContainer'} style={{ width, height }}>
<div style={calculatePanelSize(uiState.mode, width, height, panel)}>
<PanelWrapper
dashboard={dashboard}
panel={panel}
isEditing={true}
isViewing={false}
isInView={true}
/>
</div>
</div>
);
}}
</AutoSizer>
</div>
</div>
);
};
renderHorizontalSplit() {
const { dashboard, tabs ,panel} = this.props;
const { uiState } = this.state
return tabs.length > 0 ? (
<SplitPane
split="horizontal"
minSize={200}
primary="first"
/* Use persisted state for default size */
defaultSize={uiState.topPaneSize}
pane2Style={{ minHeight: 0 }}
resizerClassName={'resizerH'}
onDragStarted={this.onDragStarted}
onDragFinished={size => this.onDragFinished(Pane.Top, size)}
>
{this.renderPanel()}
<div className={'tabsWrapper'}>
<PanelEditorTabs panel={panel} dashboard={dashboard} tabs={tabs} onChangeTab={this.onChangeTab} />
</div>
</SplitPane>
) : (
this.renderPanel()
);
}
renderTemplateVariables() {
// const { variables } = this.props;
// if (!variables.length) {
// return null;
// }
return (
<div className={'variablesWrapper'}>
{/* <SubMenuItems variables={variables} /> */}
</div>
);
}
editorToolbar() {
const { dashboard } = this.props;
return (
<div className={'editorToolbar'}>
<Row justify="space-between" align="middle" style={{width:'100%'}}>
<div className={'toolbarLeft'}>
<BackButton onClick={this.onPanelExit} surface="panel" />
<span className={'editorTitle'}>{dashboard.title} / <FormattedMessage id="panel.edit"/></span>
</div>
<div>
<Row align="middle">
{/* <Button
icon={<SettingOutlined />}
onClick={this.onOpenDashboardSettings}
title="Open dashboad settings"
/> */}
<Button onClick={this.onDiscard} title="Undo all changes">
<FormattedMessage id="common.discard"/>
</Button>
<Button onClick={this.onSaveDashboard} title="Apply changes and save dashboard">
<FormattedMessage id="common.save"/>
</Button>
<Button onClick={this.onPanelExit} title="Apply changes and go back to dashboard">
<FormattedMessage id="common.apply"/>
</Button>
</Row>
</div>
</Row>
</div>
);
}
renderOptionsPane() {
const { plugin, dashboard,panel} = this.props;
const { uiState} = this.state
if (!plugin) {
return <div />;
}
return (
<OptionsPaneContent
plugin={plugin}
dashboard={dashboard}
panel={panel}
width={uiState.rightPaneSize as number}
onClose={this.onTogglePanelOptions}
onFieldConfigsChange={this.onFieldConfigChange}
onPanelOptionsChanged={this.onPanelOptionsChanged}
onPanelConfigChange={this.onPanelConfigChanged}
/>
);
}
renderWithOptionsPane() {
const { uiState } = this.state;
return (
<SplitPane
split="vertical"
minSize={300}
primary="second"
/* Use persisted state for default size */
defaultSize={uiState.rightPaneSize}
resizerClassName={'resizerV'}
onDragStarted={() => (document.body.style.cursor = 'col-resize')}
onDragFinished={size => this.onDragFinished(Pane.Right, size)}
>
{this.renderHorizontalSplit()}
{this.renderOptionsPane()}
</SplitPane>
);
}
render() {
const {initDone} = this.props
const { uiState } = this.state;
if (!initDone) {
return null;
}
return (
<div className="panel-editor">
<div className={'wrapper'}>
{this.editorToolbar()}
<div className={'verticalSplitPanesWrapper'}>
{uiState.isPanelOptionsVisible ? this.renderWithOptionsPane() : this.renderHorizontalSplit()}
</div>
</div>
</div>
);
}
}
export const mapStateToProps = (state: StoreState, props: Props) => {
let panel = state.panelEditor.panel;
if (!panel) {
panel = new PanelModel({})
}
const {plugin} = getPanelStateById(state.dashboard, panel.id);
return {
location: state.location,
initDone: state.panelEditor.initDone,
panel: panel,
plugin: plugin,
tabs: getPanelEditorTabs(plugin,getUrlParams().tab)
}
}
export const PanelEditor = connect(mapStateToProps)(PanelEditorUnconnected);
export function getPanelStateById(state: any, panelId: number): PanelState {
if (!panelId) {
return {} as PanelState;
}
return state.panels[panelId] ?? ({} as PanelState);
} | the_stack |
import {
doubleQuotesEscapeChars,
identSpecialChars,
isHex,
isIdent,
isIdentStart,
singleQuoteEscapeChars
} from "./utils";
import {Rule, RuleAttr, RulePseudo, RuleSet, Selector} from './selector';
export type PseudoSelectorType = 'numeric' | 'selector';
export function parseCssSelector(
str: string,
pos: number,
pseudos: {[key: string]: PseudoSelectorType},
attrEqualityMods: {[key: string]: true},
ruleNestingOperators: {[key: string]: true},
substitutesEnabled: boolean
) {
const l = str.length;
let chr: string = '';
function getStr(quote: string, escapeTable: {[key: string]: string}) {
let result = '';
pos++;
chr = str.charAt(pos);
while (pos < l) {
if (chr === quote) {
pos++;
return result;
} else if (chr === '\\') {
pos++;
chr = str.charAt(pos);
let esc;
if (chr === quote) {
result += quote;
} else if ((esc = escapeTable[chr]) !== undefined) {
result += esc;
} else if (isHex(chr)) {
let hex = chr;
pos++;
chr = str.charAt(pos);
while (isHex(chr)) {
hex += chr;
pos++;
chr = str.charAt(pos);
}
if (chr === ' ') {
pos++;
chr = str.charAt(pos);
}
result += String.fromCharCode(parseInt(hex, 16));
continue;
} else {
result += chr;
}
} else {
result += chr;
}
pos++;
chr = str.charAt(pos);
}
return result;
}
function getIdent() {
let result = '';
chr = str.charAt(pos);
while (pos < l) {
if (isIdent(chr)) {
result += chr;
} else if (chr === '\\') {
pos++;
if (pos >= l) {
throw Error('Expected symbol but end of file reached.');
}
chr = str.charAt(pos);
if (identSpecialChars[chr]) {
result += chr;
} else if (isHex(chr)) {
let hex = chr;
pos++;
chr = str.charAt(pos);
while (isHex(chr)) {
hex += chr;
pos++;
chr = str.charAt(pos);
}
if (chr === ' ') {
pos++;
chr = str.charAt(pos);
}
result += String.fromCharCode(parseInt(hex, 16));
continue;
} else {
result += chr;
}
} else {
return result;
}
pos++;
chr = str.charAt(pos);
}
return result;
}
function skipWhitespace() {
chr = str.charAt(pos);
let result = false;
while (chr === ' ' || chr === "\t" || chr === "\n" || chr === "\r" || chr === "\f") {
result = true;
pos++;
chr = str.charAt(pos);
}
return result;
}
function parse() {
const res = parseSelector();
if (pos < l) {
throw Error('Rule expected but "' + str.charAt(pos) + '" found.');
}
return res;
}
function parseSelector() {
let selector = parseSingleSelector();
if (!selector) {
return null;
}
let res: Selector = selector;
chr = str.charAt(pos);
while (chr === ',') {
pos++;
skipWhitespace();
if (res.type !== 'selectors') {
res = {
type: 'selectors',
selectors: [selector]
};
}
selector = parseSingleSelector();
if (!selector) {
throw Error('Rule expected after ",".');
}
res.selectors.push(selector);
}
return res;
}
function parseSingleSelector(): RuleSet | null {
skipWhitespace();
const selector: Partial<RuleSet> = {
type: 'ruleSet'
};
let rule = parseRule();
if (!rule) {
return null;
}
let currentRule: Partial<RuleSet | Rule> = selector;
while (rule) {
rule.type = 'rule';
currentRule.rule = rule;
currentRule = rule;
skipWhitespace();
chr = str.charAt(pos);
if (pos >= l || chr === ',' || chr === ')') {
break;
}
if (ruleNestingOperators[chr]) {
const op = chr;
pos++;
skipWhitespace();
rule = parseRule();
if (!rule) {
throw Error('Rule expected after "' + op + '".');
}
rule.nestingOperator = op;
} else {
rule = parseRule();
if (rule) {
rule.nestingOperator = null;
}
}
}
return selector as RuleSet | null;
}
// @ts-ignore no-overlap
function parseRule(): Rule | null {
let rule: Partial<Rule> | null = null;
while (pos < l) {
chr = str.charAt(pos);
if (chr === '*') {
pos++;
(rule = rule || {}).tagName = '*';
} else if (isIdentStart(chr) || chr === '\\') {
(rule = rule || {}).tagName = getIdent();
} else if (chr === '.') {
pos++;
rule = rule || {};
(rule.classNames = rule.classNames || []).push(getIdent());
} else if (chr === '#') {
pos++;
(rule = rule || {}).id = getIdent();
} else if (chr === '[') {
pos++;
skipWhitespace();
let attr: any = {
name: getIdent()
};
skipWhitespace();
// @ts-ignore
if (chr === ']') {
pos++;
} else {
let operator = '';
if (attrEqualityMods[chr]) {
operator = chr;
pos++;
chr = str.charAt(pos);
}
if (pos >= l) {
throw Error('Expected "=" but end of file reached.');
}
if (chr !== '=') {
throw Error('Expected "=" but "' + chr + '" found.');
}
attr.operator = operator + '=';
pos++;
skipWhitespace();
let attrValue = '';
attr.valueType = 'string';
// @ts-ignore
if (chr === '"') {
attrValue = getStr('"', doubleQuotesEscapeChars);
// @ts-ignore
} else if (chr === '\'') {
attrValue = getStr('\'', singleQuoteEscapeChars);
// @ts-ignore
} else if (substitutesEnabled && chr === '$') {
pos++;
attrValue = getIdent();
attr.valueType = 'substitute';
} else {
while (pos < l) {
if (chr === ']') {
break;
}
attrValue += chr;
pos++;
chr = str.charAt(pos);
}
attrValue = attrValue.trim();
}
skipWhitespace();
if (pos >= l) {
throw Error('Expected "]" but end of file reached.');
}
if (chr !== ']') {
throw Error('Expected "]" but "' + chr + '" found.');
}
pos++;
attr.value = attrValue;
}
rule = rule || {};
(rule.attrs = rule.attrs || []).push(attr as RuleAttr);
} else if (chr === ':') {
pos++;
const pseudoName = getIdent();
const pseudo: Partial<RulePseudo> = {
name: pseudoName
};
// @ts-ignore
if (chr === '(') {
pos++;
let value: string | Selector | null = '';
skipWhitespace();
if (pseudos[pseudoName] === 'selector') {
pseudo.valueType = 'selector';
value = parseSelector() as any;
} else {
pseudo.valueType = pseudos[pseudoName] || 'string';
// @ts-ignore
if (chr === '"') {
value = getStr('"', doubleQuotesEscapeChars);
// @ts-ignore
} else if (chr === '\'') {
value = getStr('\'', singleQuoteEscapeChars);
// @ts-ignore
} else if (substitutesEnabled && chr === '$') {
pos++;
value = getIdent();
pseudo.valueType = 'substitute';
} else {
while (pos < l) {
if (chr === ')') {
break;
}
value += chr;
pos++;
chr = str.charAt(pos);
}
value = value.trim();
}
skipWhitespace();
}
if (pos >= l) {
throw Error('Expected ")" but end of file reached.');
}
if (chr !== ')') {
throw Error('Expected ")" but "' + chr + '" found.');
}
pos++;
pseudo.value = value as any;
}
rule = rule || {};
(rule.pseudos = rule.pseudos || []).push(pseudo as RulePseudo);
} else {
break;
}
}
return rule as Rule;
}
return parse();
} | the_stack |
import { renderTable } from '../../src/internalTable/internal-table-printer';
import { Table } from '../../index';
describe('Testing Row separator', () => {
it('Batch Row separator by each row', () => {
// Create a table
const p = new Table();
p.addRow({ index: 3, text: 'row without separator', value: 100 });
p.addRow(
{ index: 4, text: 'row with separator', value: 300 },
{ separator: true }
);
p.addRow({ index: 5, text: 'row without separator', value: 100 });
// print
const returned = renderTable(p.table);
const expected = [
'┌───────┬───────────────────────┬───────┐',
'\u001b[37m│\u001b[0m\u001b[37m \u001b[0m\u001b[01mindex\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[01m text\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[01mvalue\u001b[0m\u001b[37m │\u001b[0m',
'├───────┼───────────────────────┼───────┤',
'\u001b[37m│\u001b[0m\u001b[37m \u001b[0m\u001b[37m 3\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37mrow without separator\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37m 100\u001b[0m\u001b[37m │\u001b[0m',
'\u001b[37m│\u001b[0m\u001b[37m \u001b[0m\u001b[37m 4\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37m row with separator\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37m 300\u001b[0m\u001b[37m │\u001b[0m',
'├───────┼───────────────────────┼───────┤',
'\u001b[37m│\u001b[0m\u001b[37m \u001b[0m\u001b[37m 5\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37mrow without separator\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37m 100\u001b[0m\u001b[37m │\u001b[0m',
'└───────┴───────────────────────┴───────┘',
];
expect(returned).toBe(expected.join('\n'));
p.printTable();
});
it('Batch Row default separator is working', () => {
// Create a table
const p = new Table();
p.addRows([
// adding multiple rows are possible
{ index: 3, text: 'row default separator', value: 100 },
{ index: 4, text: 'row default separator', value: 300 },
]);
// print
const returned = renderTable(p.table);
const expected = [
'┌───────┬───────────────────────┬───────┐',
'\u001b[37m│\u001b[0m\u001b[37m \u001b[0m\u001b[01mindex\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[01m text\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[01mvalue\u001b[0m\u001b[37m │\u001b[0m',
'├───────┼───────────────────────┼───────┤',
'\u001b[37m│\u001b[0m\u001b[37m \u001b[0m\u001b[37m 3\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37mrow default separator\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37m 100\u001b[0m\u001b[37m │\u001b[0m',
'\u001b[37m│\u001b[0m\u001b[37m \u001b[0m\u001b[37m 4\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37mrow default separator\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37m 300\u001b[0m\u001b[37m │\u001b[0m',
'└───────┴───────────────────────┴───────┘',
];
expect(returned).toBe(expected.join('\n'));
p.printTable();
});
it('Batch Row table separator option is working', () => {
// Create a table
const p = new Table({ rowSeparator: true });
p.addRows([
// adding multiple rows are possible
{ index: 3, text: 'table row separator', value: 100 },
{ index: 4, text: 'table row separator', value: 300 },
]);
// print
const returned = renderTable(p.table);
const expected = [
'┌───────┬─────────────────────┬───────┐',
'\u001b[37m│\u001b[0m\u001b[37m \u001b[0m\u001b[01mindex\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[01m text\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[01mvalue\u001b[0m\u001b[37m │\u001b[0m',
'├───────┼─────────────────────┼───────┤',
'\u001b[37m│\u001b[0m\u001b[37m \u001b[0m\u001b[37m 3\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37mtable row separator\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37m 100\u001b[0m\u001b[37m │\u001b[0m',
'├───────┼─────────────────────┼───────┤',
'\u001b[37m│\u001b[0m\u001b[37m \u001b[0m\u001b[37m 4\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37mtable row separator\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37m 300\u001b[0m\u001b[37m │\u001b[0m',
'└───────┴─────────────────────┴───────┘',
];
expect(returned).toBe(expected.join('\n'));
p.printTable();
});
it('Batch Row table separator override is working', () => {
// Create a table
const p = new Table({ rowSeparator: true });
p.addRows(
[
// adding multiple rows are possible
{ index: 3, text: 'override table row separator', value: 100 },
{ index: 4, text: 'override table row separator', value: 300 },
],
{ separator: false }
);
// print
const returned = renderTable(p.table);
const expected = [
'┌───────┬──────────────────────────────┬───────┐',
'\u001b[37m│\u001b[0m\u001b[37m \u001b[0m\u001b[01mindex\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[01m text\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[01mvalue\u001b[0m\u001b[37m │\u001b[0m',
'├───────┼──────────────────────────────┼───────┤',
'\u001b[37m│\u001b[0m\u001b[37m \u001b[0m\u001b[37m 3\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37moverride table row separator\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37m 100\u001b[0m\u001b[37m │\u001b[0m',
'\u001b[37m│\u001b[0m\u001b[37m \u001b[0m\u001b[37m 4\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37moverride table row separator\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37m 300\u001b[0m\u001b[37m │\u001b[0m',
'└───────┴──────────────────────────────┴───────┘',
];
expect(returned).toBe(expected.join('\n'));
p.printTable();
});
it('Batch Row separator is working', () => {
// Create a table
const p = new Table();
p.addRows(
[
// adding multiple rows are possible
{ index: 3, text: 'row with separator', value: 100 },
{ index: 4, text: 'row with separator', value: 300 },
],
{ separator: true }
);
// print
const returned = renderTable(p.table);
const expected = [
'┌───────┬────────────────────┬───────┐',
'\u001b[37m│\u001b[0m\u001b[37m \u001b[0m\u001b[01mindex\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[01m text\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[01mvalue\u001b[0m\u001b[37m │\u001b[0m',
'├───────┼────────────────────┼───────┤',
'\u001b[37m│\u001b[0m\u001b[37m \u001b[0m\u001b[37m 3\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37mrow with separator\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37m 100\u001b[0m\u001b[37m │\u001b[0m',
'├───────┼────────────────────┼───────┤',
'\u001b[37m│\u001b[0m\u001b[37m \u001b[0m\u001b[37m 4\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37mrow with separator\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37m 300\u001b[0m\u001b[37m │\u001b[0m',
'└───────┴────────────────────┴───────┘',
];
expect(returned).toBe(expected.join('\n'));
});
it('Batch Row separator combined with sorting', () => {
// Create a table and sort by index
const p = new Table({
sort: (row1, row2) => row1.index - row2.index,
rowSeparator: true,
});
// Row with index 1 will have separator because it inherits from Table options
p.addRow({ index: 1, text: 'row inherit separator', value: 100 });
p.addRow(
{ index: 4, text: 'row without separator', value: 100 },
{ separator: false }
);
// Row with index 5 will be last row so separator will be ignored anyway
p.addRow(
{ index: 5, text: 'row with separator', value: 100 },
{ separator: true }
);
p.addRow(
{ index: 2, text: 'row with separator', value: 100 },
{ separator: true }
);
p.addRow(
{ index: 3, text: 'row without separator', value: 100 },
{ separator: false }
);
// print
const returned = renderTable(p.table);
const expected = [
'┌───────┬───────────────────────┬───────┐',
'\u001b[37m│\u001b[0m\u001b[37m \u001b[0m\u001b[01mindex\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[01m text\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[01mvalue\u001b[0m\u001b[37m │\u001b[0m',
'├───────┼───────────────────────┼───────┤',
'\u001b[37m│\u001b[0m\u001b[37m \u001b[0m\u001b[37m 1\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37mrow inherit separator\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37m 100\u001b[0m\u001b[37m │\u001b[0m',
'├───────┼───────────────────────┼───────┤',
'\u001b[37m│\u001b[0m\u001b[37m \u001b[0m\u001b[37m 2\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37m row with separator\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37m 100\u001b[0m\u001b[37m │\u001b[0m',
'├───────┼───────────────────────┼───────┤',
'\u001b[37m│\u001b[0m\u001b[37m \u001b[0m\u001b[37m 3\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37mrow without separator\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37m 100\u001b[0m\u001b[37m │\u001b[0m',
'\u001b[37m│\u001b[0m\u001b[37m \u001b[0m\u001b[37m 4\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37mrow without separator\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37m 100\u001b[0m\u001b[37m │\u001b[0m',
'\u001b[37m│\u001b[0m\u001b[37m \u001b[0m\u001b[37m 5\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37m row with separator\u001b[0m\u001b[37m │\u001b[0m\u001b[37m \u001b[0m\u001b[37m 100\u001b[0m\u001b[37m │\u001b[0m',
'└───────┴───────────────────────┴───────┘',
];
expect(returned).toBe(expected.join('\n'));
p.printTable();
});
}); | the_stack |
* @fileoverview In this file, we will test the path helper
* functions described in /src/properties/path_helper.js
*/
import { expect } from 'chai';
import { PathHelper } from "../pathHelper";
describe('PathHelper', function() {
describe('tokenizePathString', function() {
it('should work for simple paths separated by dots', function() {
let types = [];
expect(PathHelper.tokenizePathString('', types)).to.deep.equal([]);
expect(types).to.deep.equal([]);
expect(PathHelper.tokenizePathString('test', types)).to.deep.equal(['test']);
expect(types).to.deep.equal([PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN]);
expect(PathHelper.tokenizePathString('test.test2', types)).to.deep.equal(['test', 'test2']);
expect(types).to.deep.equal([
PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN,
PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN
]);
expect(function() { PathHelper.tokenizePathString('.test2'); }).to.throw();
expect(function() { PathHelper.tokenizePathString('test2.'); }).to.throw();
expect(function() { PathHelper.tokenizePathString('.'); }).to.throw();
});
it('should work for arrays', function() {
let types = [];
expect(PathHelper.tokenizePathString('[test]', types)).to.deep.equal(['test']);
expect(types).to.deep.equal([PathHelper.TOKEN_TYPES.ARRAY_TOKEN]);
expect(PathHelper.tokenizePathString('[test][test2]', types)).to.deep.equal(['test', 'test2']);
expect(types).to.deep.equal([PathHelper.TOKEN_TYPES.ARRAY_TOKEN, PathHelper.TOKEN_TYPES.ARRAY_TOKEN]);
expect(function() { PathHelper.tokenizePathString('['); }).to.throw();
expect(function() { PathHelper.tokenizePathString('[abcd'); }).to.throw();
expect(function() { PathHelper.tokenizePathString(']'); }).to.throw();
expect(function() { PathHelper.tokenizePathString('[abcd]]'); }).to.throw();
expect(function() { PathHelper.tokenizePathString('[]'); }).to.throw();
});
it('should work for combinations of arrays and paths separated by dots', function() {
let types = [];
expect(PathHelper.tokenizePathString('map[test]', types)).to.deep.equal(['map', 'test']);
expect(types).to.deep.equal([PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN, PathHelper.TOKEN_TYPES.ARRAY_TOKEN]);
expect(PathHelper.tokenizePathString('[test].parameter', types)).to.deep.equal(['test', 'parameter']);
expect(types).to.deep.equal([PathHelper.TOKEN_TYPES.ARRAY_TOKEN, PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN]);
expect(PathHelper.tokenizePathString('map[test].parameter[test2]', types)).to.deep.equal(
['map', 'test', 'parameter', 'test2']);
expect(types).to.deep.equal([
PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN,
PathHelper.TOKEN_TYPES.ARRAY_TOKEN,
PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN,
PathHelper.TOKEN_TYPES.ARRAY_TOKEN
]);
expect(function() { PathHelper.tokenizePathString('[test]parameter'); }).to.throw();
});
it('should work for quoted tokens', function() {
let types = [];
expect(PathHelper.tokenizePathString('"test"', types)).to.deep.equal(['test']);
expect(types).to.deep.equal([PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN]);
expect(PathHelper.tokenizePathString('"te\\"st"', types)).to.deep.equal(['te"st']);
expect(types).to.deep.equal([PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN]);
expect(PathHelper.tokenizePathString('"te\\\\st"', types)).to.deep.equal(['te\\st']);
expect(types).to.deep.equal([PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN]);
expect(PathHelper.tokenizePathString('""', types)).to.deep.equal(['']);
expect(types).to.deep.equal([PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN]);
expect(PathHelper.tokenizePathString('"test1".test2', types)).to.deep.equal(['test1', 'test2']);
expect(types).to.deep.equal([
PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN, PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN
]);
expect(PathHelper.tokenizePathString('"test1"."test2"', types)).to.deep.equal(['test1', 'test2']);
expect(types).to.deep.equal([
PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN, PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN
]);
expect(PathHelper.tokenizePathString('test1."test2"', types)).to.deep.equal(['test1', 'test2']);
expect(types).to.deep.equal([
PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN, PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN
]);
expect(PathHelper.tokenizePathString('test1["test2"]', types)).to.deep.equal(['test1', 'test2']);
expect(types).to.deep.equal([PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN, PathHelper.TOKEN_TYPES.ARRAY_TOKEN]);
expect(PathHelper.tokenizePathString('"test1"["test2"]', types)).to.deep.equal(['test1', 'test2']);
expect(types).to.deep.equal([PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN, PathHelper.TOKEN_TYPES.ARRAY_TOKEN]);
expect(PathHelper.tokenizePathString('""[""]', types)).to.deep.equal(['', '']);
expect(types).to.deep.equal([PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN, PathHelper.TOKEN_TYPES.ARRAY_TOKEN]);
expect(PathHelper.tokenizePathString('"/"', types)).to.deep.equal(['/']);
expect(types).to.deep.equal([PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN]);
expect(PathHelper.tokenizePathString('/', types)).to.deep.equal(['/']);
expect(types).to.deep.equal([PathHelper.TOKEN_TYPES.PATH_ROOT_TOKEN]);
expect(PathHelper.tokenizePathString('/test', types)).to.deep.equal(['/', 'test']);
expect(types).to.deep.equal([PathHelper.TOKEN_TYPES.PATH_ROOT_TOKEN, PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN]);
expect(PathHelper.tokenizePathString('/[test]', types)).to.deep.equal(['/', 'test']);
expect(types).to.deep.equal([PathHelper.TOKEN_TYPES.PATH_ROOT_TOKEN, PathHelper.TOKEN_TYPES.ARRAY_TOKEN]);
expect(PathHelper.tokenizePathString('*', types)).to.deep.equal(['*']);
expect(types).to.deep.equal([PathHelper.TOKEN_TYPES.DEREFERENCE_TOKEN]);
expect(PathHelper.tokenizePathString('test*', types)).to.deep.equal(['test', '*']);
expect(types).to.deep.equal([
PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN, PathHelper.TOKEN_TYPES.DEREFERENCE_TOKEN
]);
expect(PathHelper.tokenizePathString('*.test', types)).to.deep.equal(['*', 'test']);
expect(types).to.deep.equal([
PathHelper.TOKEN_TYPES.DEREFERENCE_TOKEN, PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN
]);
expect(function() { PathHelper.tokenizePathString('*test', types); }).to.throw();
expect(function() { PathHelper.tokenizePathString('test*test', types); }).to.throw();
expect(PathHelper.tokenizePathString('*.test*.test2*', types)).to.deep.equal(['*', 'test', '*', 'test2', '*']);
expect(types).to.deep.equal([
PathHelper.TOKEN_TYPES.DEREFERENCE_TOKEN,
PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN,
PathHelper.TOKEN_TYPES.DEREFERENCE_TOKEN,
PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN,
PathHelper.TOKEN_TYPES.DEREFERENCE_TOKEN
]);
expect(PathHelper.tokenizePathString('/*', types)).to.deep.equal(['/', '*']);
expect(types).to.deep.equal([PathHelper.TOKEN_TYPES.PATH_ROOT_TOKEN, PathHelper.TOKEN_TYPES.DEREFERENCE_TOKEN]);
expect(PathHelper.tokenizePathString('*[test]', types)).to.deep.equal(['*', 'test']);
expect(types).to.deep.equal([PathHelper.TOKEN_TYPES.DEREFERENCE_TOKEN, PathHelper.TOKEN_TYPES.ARRAY_TOKEN]);
expect(PathHelper.tokenizePathString('[test]*', types)).to.deep.equal(['test', '*']);
expect(types).to.deep.equal([PathHelper.TOKEN_TYPES.ARRAY_TOKEN, PathHelper.TOKEN_TYPES.DEREFERENCE_TOKEN]);
expect(PathHelper.tokenizePathString('[test]*.test2', types)).to.deep.equal(['test', '*', 'test2']);
expect(types).to.deep.equal([
PathHelper.TOKEN_TYPES.ARRAY_TOKEN,
PathHelper.TOKEN_TYPES.DEREFERENCE_TOKEN,
PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN
]);
expect(PathHelper.tokenizePathString('[test]*[test2]', types)).to.deep.equal(['test', '*', 'test2']);
expect(types).to.deep.equal([
PathHelper.TOKEN_TYPES.ARRAY_TOKEN,
PathHelper.TOKEN_TYPES.DEREFERENCE_TOKEN,
PathHelper.TOKEN_TYPES.ARRAY_TOKEN
]);
expect(function() { PathHelper.tokenizePathString('[test]*test', types); }).to.throw();
expect(function() { PathHelper.tokenizePathString('"'); }).to.throw();
expect(function() { PathHelper.tokenizePathString('test"'); }).to.throw();
expect(function() { PathHelper.tokenizePathString('"tests'); }).to.throw();
expect(function() { PathHelper.tokenizePathString('"\\a"'); }).to.throw();
});
it('should work for relative paths', function() {
let types = [];
expect(PathHelper.tokenizePathString('../test', types)).to.deep.equal(['../', 'test']);
expect(types).to.deep.equal([PathHelper.TOKEN_TYPES.RAISE_LEVEL_TOKEN,
PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN
]);
expect(PathHelper.tokenizePathString('../../../test', types)).to.deep.equal(['../', '../', '../', 'test']);
expect(types).to.deep.equal([PathHelper.TOKEN_TYPES.RAISE_LEVEL_TOKEN, PathHelper.TOKEN_TYPES.RAISE_LEVEL_TOKEN,
PathHelper.TOKEN_TYPES.RAISE_LEVEL_TOKEN, PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN
]);
expect(PathHelper.tokenizePathString('../../test[0].test2[key]', types)).to.deep.equal(
['../', '../', 'test', '0', 'test2', 'key']);
expect(types).to.deep.equal([PathHelper.TOKEN_TYPES.RAISE_LEVEL_TOKEN, PathHelper.TOKEN_TYPES.RAISE_LEVEL_TOKEN,
PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN, PathHelper.TOKEN_TYPES.ARRAY_TOKEN,
PathHelper.TOKEN_TYPES.PATH_SEGMENT_TOKEN, PathHelper.TOKEN_TYPES.ARRAY_TOKEN
]);
expect(function() { PathHelper.tokenizePathString('/../test2'); }).to.throw();
});
});
describe('quotePathSegment', function() {
it('should quote simple strings', function() {
expect(PathHelper.quotePathSegment('test')).to.equal('"test"');
expect(JSON.parse(PathHelper.quotePathSegment('test'))).to.equal('test');
});
it('should correctly quote strings with a quotation mark', function() {
expect(PathHelper.quotePathSegment('"')).to.equal('"\\""');
expect(JSON.parse(PathHelper.quotePathSegment('"'))).to.equal('"');
});
it('should correctly quote strings with a backslash', function() {
expect(PathHelper.quotePathSegment('\\')).to.equal('"\\\\"');
expect(JSON.parse(PathHelper.quotePathSegment('\\'))).to.equal('\\');
});
it('should work for paths with multiple occurrences of the test string', function() {
expect(PathHelper.quotePathSegment('test"property"')).to.equal('"test\\"property\\""');
expect(PathHelper.quotePathSegment('test\\property\\')).to.equal('"test\\\\property\\\\"');
expect(PathHelper.quotePathSegment('test"\\property\\"')).to.equal('"test\\"\\\\property\\\\\\""');
});
});
describe('quotePathSegmentIfNeeded', function() {
it('should quote all required strings', function() {
expect(PathHelper.quotePathSegmentIfNeeded('.')).to.equal('"."');
expect(PathHelper.quotePathSegmentIfNeeded('"')).to.equal('"\\""');
expect(PathHelper.quotePathSegmentIfNeeded('\\')).to.equal('"\\\\"');
expect(PathHelper.quotePathSegmentIfNeeded('[')).to.equal('"["');
expect(PathHelper.quotePathSegmentIfNeeded(']')).to.equal('"]"');
expect(PathHelper.quotePathSegmentIfNeeded('')).to.equal('""');
expect(PathHelper.quotePathSegmentIfNeeded('/')).to.equal('"/"');
expect(PathHelper.quotePathSegmentIfNeeded('*')).to.equal('"*"');
});
it('should not quote other strings', function() {
expect(PathHelper.quotePathSegmentIfNeeded('abcd')).to.equal('abcd');
expect(PathHelper.quotePathSegmentIfNeeded('test_string')).to.equal('test_string');
});
});
describe('unquotePathSegment', function() {
it('should unquote simple strings', function() {
expect(PathHelper.unquotePathSegment('"test"')).to.equal('test');
});
it('should correctly unquote strings with a quotation mark', function() {
expect(PathHelper.unquotePathSegment('"\\""')).to.equal('"');
});
it('should correctly unquote strings with a backslash', function() {
expect(PathHelper.unquotePathSegment('"\\\\"')).to.equal('\\');
});
it('should work with empty strings', function() {
expect(PathHelper.unquotePathSegment('')).to.equal('');
});
it('should throw on non strings', function() {
// @ts-ignore
expect(() => PathHelper.unquotePathSegment(5)).to.throw();
});
it('should work for paths with multiple occurrences of the test string', function() {
expect(PathHelper.unquotePathSegment('"test\\"property\\""')).to.equal('test"property"');
expect(PathHelper.unquotePathSegment('"test\\\\property\\\\"')).to.equal('test\\property\\');
expect(PathHelper.unquotePathSegment('"test\\"\\\\property\\\\\\""')).to.equal('test"\\property\\"');
});
});
describe('convertAbsolutePathToCanonical', function() {
it('should remove leading /', function() {
expect(PathHelper.convertAbsolutePathToCanonical('/a.b.c')).to.equal('a.b.c');
});
it('should throw on ../', function() {
expect(() => PathHelper.convertAbsolutePathToCanonical('../a.b.c')).to.throw('../');
});
it('should throw on *', function() {
expect(() => PathHelper.convertAbsolutePathToCanonical('/a.b.c*')).to.throw('*');
});
it('should replace square brackets by periods', function() {
expect(PathHelper.convertAbsolutePathToCanonical('/a.b[c]')).to.equal('a.b.c');
expect(PathHelper.convertAbsolutePathToCanonical('/a[b].c')).to.equal('a.b.c');
});
it('should keep properly escaped property names', function() {
expect(PathHelper.convertAbsolutePathToCanonical('"."')).to.equal('"."');
expect(PathHelper.convertAbsolutePathToCanonical('"\\""')).to.equal('"\\""');
expect(PathHelper.convertAbsolutePathToCanonical('"\\\\"')).to.equal('"\\\\"');
expect(PathHelper.convertAbsolutePathToCanonical('"["')).to.equal('"["');
expect(PathHelper.convertAbsolutePathToCanonical('"]"')).to.equal('"]"');
expect(PathHelper.convertAbsolutePathToCanonical('""')).to.equal('""');
expect(PathHelper.convertAbsolutePathToCanonical('"/"')).to.equal('"/"');
expect(PathHelper.convertAbsolutePathToCanonical('"*"')).to.equal('"*"');
});
it('should properly unescape unusually escaped property names', function() {
expect(PathHelper.convertAbsolutePathToCanonical('"a"."b"')).to.equal('a.b');
expect(PathHelper.convertAbsolutePathToCanonical('"a"[b]["c"]')).to.equal('a.b.c');
});
it('should not modify simple paths', function() {
expect(PathHelper.convertAbsolutePathToCanonical('a.b.c.d')).to.equal('a.b.c.d');
expect(PathHelper.convertAbsolutePathToCanonical('test_string')).to.equal('test_string');
});
});
describe('getPathCoverage', function() {
this.timeout(500);
let paths;
it('should succeed if property is included in a path 1', function() {
paths = ['a.b'];
const res = PathHelper.getPathCoverage('a.b', paths);
expect(res.coverageExtent).to.equal(PathHelper.CoverageExtent.FULLY_COVERED);
expect(res.pathList).to.deep.equal(['a.b']);
});
it('should succeed if property is included in a path 2', function() {
paths = ['a.b'];
const res = PathHelper.getPathCoverage('a.b.c', paths);
expect(res.coverageExtent).to.equal(PathHelper.CoverageExtent.FULLY_COVERED);
expect(res.pathList).to.deep.equal(['a.b']);
});
it('should succeed if property is included in a path 3', function() {
paths = ['a.b'];
const res = PathHelper.getPathCoverage('a.b.c.d', paths);
expect(res.coverageExtent).to.equal(PathHelper.CoverageExtent.FULLY_COVERED);
expect(res.pathList).to.deep.equal(['a.b']);
});
it('should fail if property is not included in any path 1', function() {
paths = ['a.b'];
const res = PathHelper.getPathCoverage('b', paths);
expect(res.coverageExtent).to.equal(PathHelper.CoverageExtent.UNCOVERED);
expect(res.pathList).to.deep.equal([]);
});
it('should fail if property is not included in any path 2', function() {
paths = ['a.b'];
const res = PathHelper.getPathCoverage('b.f.g', paths);
expect(res.coverageExtent).to.equal(PathHelper.CoverageExtent.UNCOVERED);
expect(res.pathList).to.deep.equal([]);
});
it('should fail if property is not included in any path but have common root 1', function() {
paths = ['a.b'];
const res = PathHelper.getPathCoverage('a.h', paths);
expect(res.coverageExtent).to.equal(PathHelper.CoverageExtent.UNCOVERED);
expect(res.pathList).to.deep.equal([]);
});
it('should fail if property is not included in any path but have common root 2', function() {
paths = ['a.b'];
const res = PathHelper.getPathCoverage('a.i.j', paths);
expect(res.coverageExtent).to.equal(PathHelper.CoverageExtent.UNCOVERED);
expect(res.pathList).to.deep.equal([]);
});
it('should succeed if path goes through the property 1', function() {
paths = ['a.b.c', 'a.b.d', 'z'];
const res = PathHelper.getPathCoverage('a.b', paths);
expect(res.coverageExtent).to.equal(PathHelper.CoverageExtent.PARTLY_COVERED);
expect(res.pathList).to.deep.equal(['a.b.c', 'a.b.d']);
});
it('should succeed if path goes through the property 2', function() {
paths = ['z', 'a.b.c', 'a.b.d'];
const res = PathHelper.getPathCoverage('a.b', paths);
expect(res.coverageExtent).to.equal(PathHelper.CoverageExtent.PARTLY_COVERED);
expect(res.pathList).to.deep.equal(['a.b.c', 'a.b.d']);
});
});
}); | the_stack |
import * as React from 'react';
import JqxScheduler, { ISchedulerProps, jqx } from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxscheduler';
class App extends React.PureComponent<{}, ISchedulerProps> {
private myScheduler = React.createRef<JqxScheduler>();
constructor(props: {}) {
super(props);
const appointments = new Array();
const appointment1 = {
calendar: "Zimmer 1",
description: "",
end: new Date(2017, 10, 23, 16, 0, 0),
id: "id1",
location: "",
start: new Date(2017, 10, 23, 9, 0, 0),
subject: "Projektsitzung"
};
const appointment2 = {
calendar: "Zimmer 2",
description: "",
end: new Date(2017, 10, 24, 15, 0, 0),
id: "id2",
location: "",
start: new Date(2017, 10, 24, 10, 0, 0),
subject: "IT Gruppentreffen"
};
const appointment3 = {
calendar: "Zimmer 3",
description: "",
end: new Date(2017, 10, 27, 13, 0, 0),
id: "id3",
location: "",
start: new Date(2017, 10, 27, 11, 0, 0),
subject: "Soziale Treffen"
};
const appointment4 = {
calendar: "Zimmer 2",
description: "",
end: new Date(2017, 10, 23, 18, 0, 0),
id: "id4",
location: "",
start: new Date(2017, 10, 23, 16, 0, 0),
subject: "Projekte Planung"
};
const appointment5 = {
calendar: "Zimmer 1",
description: "",
end: new Date(2017, 10, 25, 17, 0, 0),
id: "id5",
location: "",
start: new Date(2017, 10, 25, 15, 0, 0),
subject: "Interveiw mit Jan"
};
const appointment6 = {
calendar: "Zimmer 4",
description: "",
end: new Date(2017, 10, 26, 16, 0, 0),
id: "id6",
location: "",
start: new Date(2017, 10, 26, 14, 0, 0),
subject: "Interveiw mit Alberta"
};
appointments.push(appointment1);
appointments.push(appointment2);
appointments.push(appointment3);
appointments.push(appointment4);
appointments.push(appointment5);
appointments.push(appointment6);
const source: any = {
dataFields: [
{ name: 'id', type: 'string' },
{ name: 'description', type: 'string' },
{ name: 'location', type: 'string' },
{ name: 'subject', type: 'string' },
{ name: 'calendar', type: 'string' },
{ name: 'start', type: 'date' },
{ name: 'end', type: 'date' }
],
dataType: "array",
id: 'id',
localData: appointments
};
const dataAdapter: any = new jqx.dataAdapter(source);
this.state = {
appointmentDataFields: {
description: "description",
from: "start",
id: "id",
location: "location",
resourceId: "calendar",
subject: "subject",
to: "end"
},
date: new jqx.date(2017, 11, 23),
// called when the dialog is craeted.
editDialogCreate: (dialog: any, fields: any, editAppointment: any) => {
fields.timeZoneContainer.hide();
},
height: 600,
localization: {
/* tslint:disable:object-literal-sort-keys */
// separator of parts of a date (e.g. '/' in 11/05/1955)
'/': '/',
// separator of parts of a time (e.g. ':' in 05:44 PM)
':': ':',
// the first day of the week (0 = Sunday, 1 = Monday, etc)
firstDay: 1,
days: {
// full day names
names: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
// abbreviated day names
namesAbbr: ['Sonn', 'Mon', 'Dien', 'Mitt', 'Donn', 'Fre', 'Sams'],
// shortest day names
namesShort: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa']
},
months: {
// full month names (13 months for lunar calendards -- 13th month should be '' if not lunar)
names: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember', ''],
// abbreviated month names
namesAbbr: ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dez', '']
},
// AM and PM designators in one of these forms:
// The usual view, and the upper and lower case versions
// [standard,lowercase,uppercase]
// The culture does not use AM or PM (likely all standard date formats use 24 hour time)
// null
AM: ['AM', 'am', 'AM'],
PM: ['PM', 'pm', 'PM'],
eras: [
// eras in reverse chronological order.
// name: the name of the era in this culture (e.g. A.D., C.E.)
// start: when the era starts in ticks (gregorian, gmt), null if it is the earliest supported era.
// offset: offset in years from gregorian calendar
{ 'name': 'A.D.', 'start': null, 'offset': 0 }
],
twoDigitYearMax: 2029,
patterns: {
// short date pattern
d: 'M/d/yyyy',
// long date pattern
D: 'dddd, MMMM dd, yyyy',
// short time pattern
t: 'h:mm tt',
// long time pattern
T: 'h:mm:ss tt',
// long date, short time pattern
f: 'dddd, MMMM dd, yyyy h:mm tt',
// long date, long time pattern
F: 'dddd, MMMM dd, yyyy h:mm:ss tt',
// month/day pattern
M: 'MMMM dd',
// month/year pattern
Y: 'yyyy MMMM',
// S is a sortable format that does not lety by culture
S: 'yyyy\u0027-\u0027MM\u0027-\u0027dd\u0027T\u0027HH\u0027:\u0027mm\u0027:\u0027ss',
// formatting of dates in MySQL DataBases
ISO: 'yyyy-MM-dd hh:mm:ss',
ISO2: 'yyyy-MM-dd HH:mm:ss',
d1: 'dd.MM.yyyy',
d2: 'dd-MM-yyyy',
d3: 'dd-MMMM-yyyy',
d4: 'dd-MM-yy',
d5: 'H:mm',
d6: 'HH:mm',
d7: 'HH:mm tt',
d8: 'dd/MMMM/yyyy',
d9: 'MMMM-dd',
d10: 'MM-dd',
d11: 'MM-dd-yyyy'
},
backString: 'Vorhergehende',
forwardString: 'Nächster',
toolBarPreviousButtonString: 'Vorhergehende',
toolBarNextButtonString: 'Nächster',
emptyDataString: 'Nokeine Daten angezeigt',
loadString: 'Loading...',
clearString: 'Löschen',
todayString: 'Heute',
dayViewString: 'Tag',
weekViewString: 'Woche',
monthViewString: 'Monat',
timelineDayViewString: 'Zeitleiste Day',
timelineWeekViewString: 'Zeitleiste Woche',
timelineMonthViewString: 'Zeitleiste Monat',
loadingErrorMessage: 'Die Daten werden noch geladen und Sie können eine Eigenschaft nicht festgelegt oder eine Methode aufrufen . Sie können tun, dass, sobald die Datenbindung abgeschlossen ist. jqxScheduler wirft die \' bindingComplete \' Ereignis, wenn die Bindung abgeschlossen ist.',
editRecurringAppointmentDialogTitleString: 'Bearbeiten Sie wiederkehrenden Termin',
editRecurringAppointmentDialogContentString: 'Wollen Sie nur dieses eine Vorkommen oder die Serie zu bearbeiten ?',
editRecurringAppointmentDialogOccurrenceString: 'Vorkommen bearbeiten',
editRecurringAppointmentDialogSeriesString: 'Bearbeiten Die Serie',
editDialogTitleString: 'Termin bearbeiten',
editDialogCreateTitleString: 'Erstellen Sie Neuer Termin',
contextMenuEditAppointmentString: 'Termin bearbeiten',
contextMenuCreateAppointmentString: 'Erstellen Sie Neuer Termin',
editDialogSubjectString: 'Subjekt',
editDialogLocationString: 'Ort',
editDialogFromString: 'Von',
editDialogToString: 'Bis',
editDialogAllDayString: 'Den ganzen Tag',
editDialogExceptionsString: 'Ausnahmen',
editDialogResetExceptionsString: 'Zurücksetzen auf Speichern',
editDialogDescriptionString: 'Bezeichnung',
editDialogResourceIdString: 'Kalender',
editDialogStatusString: 'Status',
editDialogColorString: 'Farbe',
editDialogColorPlaceHolderString: 'Farbe wählen',
editDialogTimeZoneString: 'Zeitzone',
editDialogSelectTimeZoneString: 'Wählen Sie Zeitzone',
editDialogSaveString: 'Sparen',
editDialogDeleteString: 'Löschen',
editDialogCancelString: 'Abbrechen',
editDialogRepeatString: 'Wiederholen',
editDialogRepeatEveryString: 'Wiederholen alle',
editDialogRepeatEveryWeekString: 'woche(n)',
editDialogRepeatEveryYearString: 'Jahr (en)',
editDialogRepeatEveryDayString: 'Tag (e)',
editDialogRepeatNeverString: 'Nie',
editDialogRepeatDailyString: 'Täglich',
editDialogRepeatWeeklyString: 'Wöchentlich',
editDialogRepeatMonthlyString: 'Monatlich',
editDialogRepeatYearlyString: 'Jährlich',
editDialogRepeatEveryMonthString: 'Monate (n)',
editDialogRepeatEveryMonthDayString: 'Day',
editDialogRepeatFirstString: 'erste',
editDialogRepeatSecondString: 'zweite',
editDialogRepeatThirdString: 'dritte',
editDialogRepeatFourthString: 'vierte',
editDialogRepeatLastString: 'letzte',
editDialogRepeatEndString: 'Ende',
editDialogRepeatAfterString: 'Nach',
editDialogRepeatOnString: 'Am',
editDialogRepeatOfString: 'von',
editDialogRepeatOccurrencesString: 'Eintritt (e)',
editDialogRepeatSaveString: 'Vorkommen Speichern',
editDialogRepeatSaveSeriesString: 'Save Series',
editDialogRepeatDeleteString: 'Vorkommen löschen',
editDialogRepeatDeleteSeriesString: 'Series löschen',
editDialogStatuses:
{
free: 'Frei',
tentative: 'Versuchsweise',
busy: 'Beschäftigt',
outOfOffice: 'Ausserhaus'
}
/* tslint:enable:object-literal-sort-keys */
},
ready: () => {
setTimeout(() => {
this.myScheduler.current!.ensureAppointmentVisible("id1");
});
},
resources: {
colorScheme: "scheme05",
dataField: "calendar",
source: new jqx.dataAdapter(source)
},
source: dataAdapter,
views: [
{ type: 'dayView', timeRuler: { formatString: 'HH:mm' } },
{ type: 'weekView', timeRuler: { formatString: 'HH:mm' } },
{ type: 'monthView' }
]
};
}
public render() {
return (
<JqxScheduler theme={'material-purple'} ref={this.myScheduler}
// @ts-ignore
width={'100%'}
height={this.state.height}
date={this.state.date}
source={this.state.source}
showLegend={true}
view={"weekView"}
appointmentDataFields={this.state.appointmentDataFields}
editDialogCreate={this.state.editDialogCreate}
localization={this.state.localization}
resources={this.state.resources}
views={this.state.views}
ready={this.state.ready}
/>
);
}
}
export default App; | the_stack |
import { DiagnosticSeverity, Program, ProgramBuilder, util } from 'brighterscript';
import { expect } from 'chai';
import { standardizePath as s } from './lib/rooibos/Utils';
import { RooibosPlugin } from './plugin';
import PluginInterface from 'brighterscript/dist/PluginInterface';
import * as fsExtra from 'fs-extra';
import * as path from 'path';
let tmpPath = s`${process.cwd()}/tmp`;
let _rootDir = s`${tmpPath}/rootDir`;
let _stagingFolderPath = s`${tmpPath}/staging`;
import { trimLeading } from './lib/utils/testHelpers.spec';
describe('RooibosPlugin', () => {
let program: Program;
let builder: ProgramBuilder;
let plugin: RooibosPlugin;
let options;
beforeEach(() => {
plugin = new RooibosPlugin();
options = {
rootDir: _rootDir,
stagingFolderPath: _stagingFolderPath
};
fsExtra.ensureDirSync(_stagingFolderPath);
fsExtra.ensureDirSync(_rootDir);
fsExtra.ensureDirSync(tmpPath);
builder = new ProgramBuilder();
builder.options = util.normalizeAndResolveConfig(options);
builder.program = new Program(builder.options);
program = builder.program;
builder.plugins = new PluginInterface([plugin], builder.logger);
program.plugins = new PluginInterface([plugin], builder.logger);
program.createSourceScope(); //ensure source scope is created
plugin.beforeProgramCreate(builder);
plugin.fileFactory.sourcePath = path.resolve(path.join('../framework/src/source'));
});
afterEach(() => {
fsExtra.ensureDirSync(tmpPath);
fsExtra.emptyDirSync(tmpPath);
builder.dispose();
program.dispose();
});
describe('basic tests', () => {
it('does not find tests with no annotations', () => {
program.addOrReplaceFile('source/test.spec.bs', `
class notATest
end class
`);
program.validate();
expect(program.getDiagnostics()).to.be.empty;
expect(plugin.session.sessionInfo.testSuitesToRun).to.be.empty;
});
it('finds a basic suite', () => {
program.addOrReplaceFile('source/test.spec.bs', `
@suite
class ATest
@describe("groupA")
@it("is test1")
function Test()
end function
end class
`);
program.validate();
expect(program.getDiagnostics()).to.be.empty;
expect(plugin.session.sessionInfo.testSuitesToRun).to.not.be.empty;
});
it('finds a suite name, only', () => {
program.addOrReplaceFile('source/test.spec.bs', `
@only
@suite("named")
class ATest
@describe("groupA")
@it("is test1")
function Test()
end function
end class
`);
program.validate();
expect(program.getDiagnostics()).to.be.empty;
expect(plugin.session.sessionInfo.testSuitesToRun).to.not.be.empty;
let suite = plugin.session.sessionInfo.testSuitesToRun[0];
expect(suite.name).to.equal('named');
expect(suite.isSolo).to.be.true;
});
it('ignores a suite', () => {
program.addOrReplaceFile('source/test.spec.bs', `
@ignore
@suite
class ATest
@describe("groupA")
@it("is test1")
function Test()
end function
end class
`);
program.validate();
expect(program.getDiagnostics()).to.be.empty;
expect(plugin.session.sessionInfo.testSuitesToRun).to.be.empty;
});
it('ignores a group', () => {
program.addOrReplaceFile('source/test.spec.bs', `
@suite
class ATest
@ignore
@describe("groupA")
@it("is test1")
function Test()
end function
end class
`);
program.validate();
expect(program.getDiagnostics()).to.be.empty;
expect(plugin.session.sessionInfo.groupsCount).to.equal(0);
expect(plugin.session.sessionInfo.testsCount).to.equal(0);
});
it('ignores a test', () => {
program.addOrReplaceFile('source/test.spec.bs', `
@suite
class ATest
@describe("groupA")
@ignore
@it("is test1")
function Test()
end function
end class
`);
program.validate();
expect(program.getDiagnostics()).to.be.empty;
expect(plugin.session.sessionInfo.groupsCount).to.equal(1);
expect(plugin.session.sessionInfo.testsCount).to.equal(0);
});
it('multiple groups', () => {
program.addOrReplaceFile('source/test.spec.bs', `
@suite
class ATest
@describe("groupA")
@it("is test1")
function Test_1()
end function
@describe("groupB")
@it("is test1")
function Test_2()
end function
@it("is test2")
function Test_3()
end function
end class
`);
program.validate();
expect(program.getDiagnostics()).to.be.empty;
expect(plugin.session.sessionInfo.testSuitesToRun).to.not.be.empty;
let suite = plugin.session.sessionInfo.testSuitesToRun[0];
expect(suite.getTestGroups()[0].testCases).to.have.length(1);
});
it('duplicate test name', () => {
program.addOrReplaceFile('source/test.spec.bs', `
@suite
class ATest
@describe("groupA")
@it("is test1")
function Test_1()
end function
@describe("groupB")
@it("is test1")
function Test_2()
end function
@it("is test1")
function Test_3()
end function
end class
`);
program.validate();
expect(program.getDiagnostics()).to.not.be.empty;
expect(plugin.session.sessionInfo.testSuitesToRun).to.be.empty;
});
it('empty test group', () => {
program.addOrReplaceFile('source/test.spec.bs', `
@suite
class ATest
@describe("groupA")
end class
`);
program.validate();
expect(program.getDiagnostics()).to.not.be.empty;
expect(plugin.session.sessionInfo.testSuitesToRun).to.be.empty;
});
it('multiple test group annotations - same name', () => {
program.addOrReplaceFile('source/test.spec.bs', `
@suite
class ATest
@describe("groupA")
@describe("groupA")
@it("is test1")
function Test_3()
end function
end class
`);
program.validate();
expect(program.getDiagnostics()).to.not.be.empty;
expect(plugin.session.sessionInfo.testSuitesToRun).to.be.empty;
});
it('params test with negative numbers', () => {
program.addOrReplaceFile('source/test.spec.bs', `
@suite
class ATest
@describe("groupA")
@it("is test1")
@params(100,100)
@params(100,-100)
@params(-100,100)
@params(-100,-100)
function Test_3(a, b)
end function
end class
`);
program.validate();
expect(program.getDiagnostics()).to.be.empty;
expect(plugin.session.sessionInfo.testSuitesToRun).to.not.be.empty;
});
it('updates test name to match name of annotation', () => {
program.addOrReplaceFile('source/test.spec.bs', `
@suite
class ATest
@describe("groupA")
@it("is test1")
function test()
end function
@it("is test2")
function test()
end function
end class
`);
program.validate();
expect(program.getDiagnostics()).to.be.empty;
expect(plugin.session.sessionInfo.testSuitesToRun).to.not.be.empty;
});
it('updates test name to match name of annotation - with params', () => {
program.addOrReplaceFile('source/test.spec.bs', `
@suite
class ATest
@describe("groupA")
@it("is test1")
function test()
end function
@it("is test2")
@params(1)
@params(2)
function test(arg)
end function
end class
`);
program.validate();
expect(program.getDiagnostics()).to.be.empty;
expect(plugin.session.sessionInfo.testSuitesToRun).to.not.be.empty;
});
it('multiple test group annotations - different name', () => {
program.addOrReplaceFile('source/test.spec.bs', `
@suite
class ATest
@describe("groupA")
@describe("groupB")
@it("is test1")
function Test_3()
end function
end class
`);
program.validate();
expect(program.getDiagnostics()).to.not.be.empty;
expect(plugin.session.sessionInfo.testSuitesToRun).to.be.empty;
});
it('test full transpile', async () => {
plugin.afterProgramCreate(program);
// program.validate();
program.addOrReplaceFile('source/test.spec.bs', `
@suite
class ATest extends rooibos.BaseTestSuite
@describe("groupA")
@it("is test1")
function Test_3()
end function
end class
`);
program.validate();
await builder.transpile();
console.log(builder.getDiagnostics());
expect(builder.getDiagnostics()).to.have.length(1);
expect(builder.getDiagnostics()[0].severity).to.equal(DiagnosticSeverity.Warning);
expect(plugin.session.sessionInfo.testSuitesToRun).to.not.be.empty;
expect(plugin.session.sessionInfo.suitesCount).to.equal(1);
expect(plugin.session.sessionInfo.groupsCount).to.equal(1);
expect(plugin.session.sessionInfo.testsCount).to.equal(1);
expect(getContents('rooibosMain.brs')).to.eql(trimLeading(`function main()
Rooibos_init()
end function`).trim());
let a = getContents('test.spec.brs');
let b = trimLeading(`function __ATest_builder()
instance = __rooibos_BaseTestSuite_builder()
instance.super0_new = instance.new
instance.new = sub()
m.super0_new()
end sub
instance.groupA_is_test1 = function()
end function
instance.super0_getTestSuiteData = instance.getTestSuiteData
instance.getTestSuiteData = function()
return {
name: "ATest",
isSolo: false,
noCatch: false,
isIgnored: false,
pkgPath: "source/test.spec.bs",
filePath: "/home/george/hope/open-source/rooibos/bsc-plugin/tmp/rootDir/source/test.spec.bs",
lineNumber: 3,
valid: true,
hasFailures: false,
hasSoloTests: false,
hasIgnoredTests: false,
hasSoloGroups: false,
setupFunctionName: "",
tearDownFunctionName: "",
beforeEachFunctionName: "",
afterEachFunctionName: "",
isNodeTest: false,
nodeName: "",
generatedNodeName: "ATest",
testGroups: [
{
name: "groupA",
isSolo: false,
isIgnored: false,
filename: "source/test.spec.bs",
lineNumber: "3",
setupFunctionName: "",
tearDownFunctionName: "",
beforeEachFunctionName: "",
afterEachFunctionName: "",
testCases: [
{
isSolo: false,
noCatch: false,
funcName: "groupA_is_test1",
isIgnored: false,
isParamTest: false,
name: "is test1",
lineNumber: 7,
paramLineNumber: 0,
assertIndex: 0,
assertLineNumberMap: {},
rawParams: invalid,
paramTestIndex: 0,
expectedNumberOfParams: 0,
isParamsValid: true
}
]
}
]
}
end function
return instance
end function
function ATest()
instance = __ATest_builder()
instance.new()
return instance
end function`);
expect(a).to.eql(b);
});
it('test full transpile with complex params', async () => {
plugin.afterProgramCreate(program);
// program.validate();
program.addOrReplaceFile('source/test.spec.bs', `
@suite
class ATest extends rooibos.BaseTestSuite
@describe("groupA")
@it("is test1")
@params({"unknown_value": "color"})
function Test_3(arg)
end function
end class
`);
program.validate();
await builder.transpile();
console.log(builder.getDiagnostics());
expect(builder.getDiagnostics()).to.have.length(1);
expect(builder.getDiagnostics()[0].severity).to.equal(DiagnosticSeverity.Warning);
expect(plugin.session.sessionInfo.testSuitesToRun).to.not.be.empty;
expect(plugin.session.sessionInfo.suitesCount).to.equal(1);
expect(plugin.session.sessionInfo.groupsCount).to.equal(1);
expect(plugin.session.sessionInfo.testsCount).to.equal(1);
expect(getContents('rooibosMain.brs')).to.eql(trimLeading(`function main()
Rooibos_init()
end function`).trim());
});
});
describe('honours tags - simple tests', () => {
let testSource = `
@tags("one", "two", "exclude")
@suite("a")
class ATest extends rooibos.BaseTestSuite
@describe("groupA")
@it("is test1")
function t1()
end function
end class
@tags("one", "three")
@suite("b")
class BTest extends rooibos.BaseTestSuite
@describe("groupB")
@it("is test2")
function t2()
end function
end class
`;
beforeEach(() => {
plugin = new RooibosPlugin();
options = {
rootDir: _rootDir,
stagingFolderPath: _stagingFolderPath
};
fsExtra.ensureDirSync(_stagingFolderPath);
fsExtra.ensureDirSync(_rootDir);
fsExtra.ensureDirSync(tmpPath);
builder = new ProgramBuilder();
builder.options = util.normalizeAndResolveConfig(options);
builder.program = new Program(builder.options);
program = builder.program;
builder.plugins = new PluginInterface([plugin], builder.logger);
program.plugins = new PluginInterface([plugin], builder.logger);
program.createSourceScope(); //ensure source scope is created
plugin.beforeProgramCreate(builder);
plugin.fileFactory.sourcePath = path.resolve(path.join('../framework/src/source'));
plugin.afterProgramCreate(program);
// program.validate();
});
afterEach(() => {
fsExtra.ensureDirSync(tmpPath);
fsExtra.emptyDirSync(tmpPath);
builder.dispose();
program.dispose();
});
it('tag one', async () => {
plugin.session.sessionInfo.includeTags = ['one'];
program.addOrReplaceFile('source/test.spec.bs', testSource);
program.validate();
await builder.transpile();
console.log(builder.getDiagnostics());
expect(builder.getDiagnostics()).to.have.length(1);
expect(builder.getDiagnostics()[0].severity).to.equal(DiagnosticSeverity.Warning);
expect(plugin.session.sessionInfo.testSuitesToRun).to.not.be.empty;
expect(plugin.session.sessionInfo.testSuitesToRun[0].name).to.equal('a');
expect(plugin.session.sessionInfo.testSuitesToRun[1].name).to.equal('b');
});
it('tag two', async () => {
plugin.session.sessionInfo.includeTags = ['two'];
program.addOrReplaceFile('source/test.spec.bs', testSource);
program.validate();
await builder.transpile();
console.log(builder.getDiagnostics());
expect(builder.getDiagnostics()).to.have.length(1);
expect(builder.getDiagnostics()[0].severity).to.equal(DiagnosticSeverity.Warning);
expect(plugin.session.sessionInfo.testSuitesToRun).to.not.be.empty;
expect(plugin.session.sessionInfo.testSuitesToRun[0].name).to.equal('a');
});
it('tag three', async () => {
plugin.session.sessionInfo.includeTags = ['three'];
program.addOrReplaceFile('source/test.spec.bs', testSource);
program.validate();
await builder.transpile();
console.log(builder.getDiagnostics());
expect(builder.getDiagnostics()).to.have.length(1);
expect(builder.getDiagnostics()[0].severity).to.equal(DiagnosticSeverity.Warning);
expect(plugin.session.sessionInfo.testSuitesToRun).to.not.be.empty;
expect(plugin.session.sessionInfo.testSuitesToRun[0].name).to.equal('b');
});
it('tag exclude', async () => {
plugin.session.sessionInfo.excludeTags = ['exclude'];
program.addOrReplaceFile('source/test.spec.bs', testSource);
program.validate();
await builder.transpile();
console.log(builder.getDiagnostics());
expect(builder.getDiagnostics()).to.have.length(1);
expect(builder.getDiagnostics()[0].severity).to.equal(DiagnosticSeverity.Warning);
expect(plugin.session.sessionInfo.testSuitesToRun).to.not.be.empty;
expect(plugin.session.sessionInfo.testSuitesToRun[0].name).to.equal('b');
});
it('inlcude and exclude tags', async () => {
plugin.session.sessionInfo.includeTags = ['one', 'two'];
plugin.session.sessionInfo.excludeTags = ['exclude'];
program.addOrReplaceFile('source/test.spec.bs', testSource);
program.validate();
await builder.transpile();
console.log(builder.getDiagnostics());
expect(builder.getDiagnostics()).to.have.length(1);
expect(builder.getDiagnostics()[0].severity).to.equal(DiagnosticSeverity.Warning);
expect(plugin.session.sessionInfo.testSuitesToRun).to.be.empty;
});
it('Need all tags', async () => {
plugin.session.sessionInfo.includeTags = ['one', 'two'];
program.addOrReplaceFile('source/test.spec.bs', testSource);
program.validate();
await builder.transpile();
console.log(builder.getDiagnostics());
expect(builder.getDiagnostics()).to.have.length(1);
expect(builder.getDiagnostics()[0].severity).to.equal(DiagnosticSeverity.Warning);
expect(plugin.session.sessionInfo.testSuitesToRun).to.not.be.empty;
expect(plugin.session.sessionInfo.testSuitesToRun[0].name).to.equal('a');
});
});
});
describe.skip('run a local project', () => {
it('sanity checks on parsing - only run this outside of ci', () => {
let programBuilder = new ProgramBuilder();
let swv = {
'stagingFolderPath': 'build',
'rootDir': '/home/george/hope/open-source/maestro/swerve-app/src',
'files': [
'manifest',
'source/**/*.*',
'images/**/*.*',
'sounds/**/*.*',
'sounds/*.*',
'fonts/**/*.*',
'components/**/*.*'
],
'autoImportComponentScript': true,
'createPackage': false,
'diagnosticFilters': [
{
'src': '**/roku_modules/**/*.*'
},
{
'src': '**/Whitelist.xml',
'codes': [
1067
]
},
{
'src': 'components/maestro/generated/**/*.*'
},
1013,
{
'src': '**/RALETrackerTask.*'
}
],
'maestro': {
'nodeFileDelay': 0,
'excludeFilters': [
'**/roku_modules/**/*',
'**/*BaseTestSuite*.bs'
]
},
'sourceMap': true,
'extends': 'bsconfig.json',
'plugins': [
'/home/george/hope/open-source/maestro/maestro-roku-bsc-plugin/dist/plugin.js',
'/home/george/hope/open-source/rooibos/bsc-plugin/dist/plugin.js'
],
'exclude': {
'id': '/home/george/hope/open-source/maestro/roku-log-bsc-plugin/dist/plugin.js'
},
'rooibos': {
'isRecordingCodeCoverage': false,
'testsFilePattern': null,
'tags': [
'!integration',
'!deprecated',
'!fixme'
],
'showOnlyFailures': true,
'catchCrashes': true,
'lineWidth': 70
},
'rokuLog': {
'strip': false,
'insertPkgPath': true
}
};
programBuilder.run(
swv
// {
// project: '/home/george/hope/applicaster/zapp-roku-app/bsconfig-test.json'
// project: '/home/george/hope/open-source/maestro/swerve-app/bsconfig-test.json'
// }
).catch(e => {
console.error(e);
});
console.log('done');
});
});
function getContents(filename: string) {
return trimLeading(fsExtra.readFileSync(s`${_stagingFolderPath}/source/${filename}`).toString());
} | the_stack |
import { CloudErrorMapper, BaseResourceMapper } from "@azure/ms-rest-azure-js";
import * as msRest from "@azure/ms-rest-js";
export const CloudError = CloudErrorMapper;
export const BaseResource = BaseResourceMapper;
export const ErrorMesssage: msRest.CompositeMapper = {
serializedName: "ErrorMesssage",
type: {
name: "Composite",
className: "ErrorMesssage",
modelProperties: {
code: {
serializedName: "code",
type: {
name: "String"
}
},
message: {
serializedName: "message",
type: {
name: "String"
}
},
details: {
serializedName: "details",
type: {
name: "String"
}
}
}
}
};
export const AsyncOperationResult: msRest.CompositeMapper = {
serializedName: "AsyncOperationResult",
type: {
name: "Composite",
className: "AsyncOperationResult",
modelProperties: {
status: {
serializedName: "status",
type: {
name: "String"
}
},
error: {
serializedName: "error",
type: {
name: "Composite",
className: "ErrorMesssage"
}
}
}
}
};
export const CertificateProperties: msRest.CompositeMapper = {
serializedName: "CertificateProperties",
type: {
name: "Composite",
className: "CertificateProperties",
modelProperties: {
subject: {
readOnly: true,
serializedName: "subject",
type: {
name: "String"
}
},
expiry: {
readOnly: true,
serializedName: "expiry",
type: {
name: "DateTimeRfc1123"
}
},
thumbprint: {
readOnly: true,
serializedName: "thumbprint",
type: {
name: "String"
}
},
isVerified: {
readOnly: true,
serializedName: "isVerified",
type: {
name: "Boolean"
}
},
created: {
readOnly: true,
serializedName: "created",
type: {
name: "DateTimeRfc1123"
}
},
updated: {
readOnly: true,
serializedName: "updated",
type: {
name: "DateTimeRfc1123"
}
}
}
}
};
export const CertificateResponse: msRest.CompositeMapper = {
serializedName: "CertificateResponse",
type: {
name: "Composite",
className: "CertificateResponse",
modelProperties: {
properties: {
serializedName: "properties",
type: {
name: "Composite",
className: "CertificateProperties"
}
},
id: {
readOnly: true,
serializedName: "id",
type: {
name: "String"
}
},
name: {
readOnly: true,
serializedName: "name",
type: {
name: "String"
}
},
etag: {
readOnly: true,
serializedName: "etag",
type: {
name: "String"
}
},
type: {
readOnly: true,
serializedName: "type",
type: {
name: "String"
}
}
}
}
};
export const CertificateListDescription: msRest.CompositeMapper = {
serializedName: "CertificateListDescription",
type: {
name: "Composite",
className: "CertificateListDescription",
modelProperties: {
value: {
serializedName: "value",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "CertificateResponse"
}
}
}
}
}
}
};
export const CertificateBodyDescription: msRest.CompositeMapper = {
serializedName: "CertificateBodyDescription",
type: {
name: "Composite",
className: "CertificateBodyDescription",
modelProperties: {
certificate: {
serializedName: "certificate",
type: {
name: "String"
}
}
}
}
};
export const IotDpsSkuInfo: msRest.CompositeMapper = {
serializedName: "IotDpsSkuInfo",
type: {
name: "Composite",
className: "IotDpsSkuInfo",
modelProperties: {
name: {
serializedName: "name",
type: {
name: "String"
}
},
tier: {
readOnly: true,
serializedName: "tier",
type: {
name: "String"
}
},
capacity: {
serializedName: "capacity",
type: {
name: "Number"
}
}
}
}
};
export const IotHubDefinitionDescription: msRest.CompositeMapper = {
serializedName: "IotHubDefinitionDescription",
type: {
name: "Composite",
className: "IotHubDefinitionDescription",
modelProperties: {
applyAllocationPolicy: {
serializedName: "applyAllocationPolicy",
type: {
name: "Boolean"
}
},
allocationWeight: {
serializedName: "allocationWeight",
type: {
name: "Number"
}
},
name: {
readOnly: true,
serializedName: "name",
type: {
name: "String"
}
},
connectionString: {
required: true,
serializedName: "connectionString",
type: {
name: "String"
}
},
location: {
required: true,
serializedName: "location",
type: {
name: "String"
}
}
}
}
};
export const SharedAccessSignatureAuthorizationRuleAccessRightsDescription: msRest.CompositeMapper = {
serializedName: "SharedAccessSignatureAuthorizationRule_AccessRightsDescription_",
type: {
name: "Composite",
className: "SharedAccessSignatureAuthorizationRuleAccessRightsDescription",
modelProperties: {
keyName: {
required: true,
serializedName: "keyName",
type: {
name: "String"
}
},
primaryKey: {
serializedName: "primaryKey",
type: {
name: "String"
}
},
secondaryKey: {
serializedName: "secondaryKey",
type: {
name: "String"
}
},
rights: {
required: true,
serializedName: "rights",
type: {
name: "String"
}
}
}
}
};
export const IotDpsPropertiesDescription: msRest.CompositeMapper = {
serializedName: "IotDpsPropertiesDescription",
type: {
name: "Composite",
className: "IotDpsPropertiesDescription",
modelProperties: {
state: {
serializedName: "state",
type: {
name: "String"
}
},
provisioningState: {
serializedName: "provisioningState",
type: {
name: "String"
}
},
iotHubs: {
serializedName: "iotHubs",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "IotHubDefinitionDescription"
}
}
}
},
allocationPolicy: {
serializedName: "allocationPolicy",
type: {
name: "String"
}
},
serviceOperationsHostName: {
readOnly: true,
serializedName: "serviceOperationsHostName",
type: {
name: "String"
}
},
deviceProvisioningHostName: {
readOnly: true,
serializedName: "deviceProvisioningHostName",
type: {
name: "String"
}
},
idScope: {
readOnly: true,
serializedName: "idScope",
type: {
name: "String"
}
},
authorizationPolicies: {
serializedName: "authorizationPolicies",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "SharedAccessSignatureAuthorizationRuleAccessRightsDescription"
}
}
}
}
}
}
};
export const Resource: msRest.CompositeMapper = {
serializedName: "Resource",
type: {
name: "Composite",
className: "Resource",
modelProperties: {
id: {
readOnly: true,
serializedName: "id",
type: {
name: "String"
}
},
name: {
readOnly: true,
serializedName: "name",
constraints: {
Pattern: /^(?![0-9]+$)(?!-)[a-zA-Z0-9-]{2,49}[a-zA-Z0-9]$/
},
type: {
name: "String"
}
},
type: {
readOnly: true,
serializedName: "type",
type: {
name: "String"
}
},
location: {
required: true,
serializedName: "location",
type: {
name: "String"
}
},
tags: {
serializedName: "tags",
type: {
name: "Dictionary",
value: {
type: {
name: "String"
}
}
}
}
}
}
};
export const ProvisioningServiceDescription: msRest.CompositeMapper = {
serializedName: "ProvisioningServiceDescription",
type: {
name: "Composite",
className: "ProvisioningServiceDescription",
modelProperties: {
...Resource.type.modelProperties,
etag: {
serializedName: "etag",
type: {
name: "String"
}
},
properties: {
required: true,
serializedName: "properties",
type: {
name: "Composite",
className: "IotDpsPropertiesDescription"
}
},
sku: {
required: true,
serializedName: "sku",
type: {
name: "Composite",
className: "IotDpsSkuInfo"
}
}
}
}
};
export const OperationDisplay: msRest.CompositeMapper = {
serializedName: "Operation_display",
type: {
name: "Composite",
className: "OperationDisplay",
modelProperties: {
provider: {
readOnly: true,
serializedName: "provider",
type: {
name: "String"
}
},
resource: {
readOnly: true,
serializedName: "resource",
type: {
name: "String"
}
},
operation: {
readOnly: true,
serializedName: "operation",
type: {
name: "String"
}
}
}
}
};
export const Operation: msRest.CompositeMapper = {
serializedName: "Operation",
type: {
name: "Composite",
className: "Operation",
modelProperties: {
name: {
readOnly: true,
serializedName: "name",
type: {
name: "String"
}
},
display: {
serializedName: "display",
type: {
name: "Composite",
className: "OperationDisplay"
}
}
}
}
};
export const ErrorDetails: msRest.CompositeMapper = {
serializedName: "ErrorDetails",
type: {
name: "Composite",
className: "ErrorDetails",
modelProperties: {
code: {
readOnly: true,
serializedName: "code",
type: {
name: "String"
}
},
httpStatusCode: {
readOnly: true,
serializedName: "httpStatusCode",
type: {
name: "String"
}
},
message: {
readOnly: true,
serializedName: "message",
type: {
name: "String"
}
},
details: {
readOnly: true,
serializedName: "details",
type: {
name: "String"
}
}
}
}
};
export const IotDpsSkuDefinition: msRest.CompositeMapper = {
serializedName: "IotDpsSkuDefinition",
type: {
name: "Composite",
className: "IotDpsSkuDefinition",
modelProperties: {
name: {
serializedName: "name",
type: {
name: "String"
}
}
}
}
};
export const OperationInputs: msRest.CompositeMapper = {
serializedName: "OperationInputs",
type: {
name: "Composite",
className: "OperationInputs",
modelProperties: {
name: {
required: true,
serializedName: "name",
type: {
name: "String"
}
}
}
}
};
export const NameAvailabilityInfo: msRest.CompositeMapper = {
serializedName: "NameAvailabilityInfo",
type: {
name: "Composite",
className: "NameAvailabilityInfo",
modelProperties: {
nameAvailable: {
serializedName: "nameAvailable",
type: {
name: "Boolean"
}
},
reason: {
serializedName: "reason",
type: {
name: "String"
}
},
message: {
serializedName: "message",
type: {
name: "String"
}
}
}
}
};
export const TagsResource: msRest.CompositeMapper = {
serializedName: "TagsResource",
type: {
name: "Composite",
className: "TagsResource",
modelProperties: {
tags: {
serializedName: "tags",
type: {
name: "Dictionary",
value: {
type: {
name: "String"
}
}
}
}
}
}
};
export const VerificationCodeResponseProperties: msRest.CompositeMapper = {
serializedName: "VerificationCodeResponse_properties",
type: {
name: "Composite",
className: "VerificationCodeResponseProperties",
modelProperties: {
verificationCode: {
serializedName: "verificationCode",
type: {
name: "String"
}
},
subject: {
serializedName: "subject",
type: {
name: "String"
}
},
expiry: {
serializedName: "expiry",
type: {
name: "String"
}
},
thumbprint: {
serializedName: "thumbprint",
type: {
name: "String"
}
},
isVerified: {
serializedName: "isVerified",
type: {
name: "Boolean"
}
},
created: {
serializedName: "created",
type: {
name: "String"
}
},
updated: {
serializedName: "updated",
type: {
name: "String"
}
}
}
}
};
export const VerificationCodeResponse: msRest.CompositeMapper = {
serializedName: "VerificationCodeResponse",
type: {
name: "Composite",
className: "VerificationCodeResponse",
modelProperties: {
name: {
readOnly: true,
serializedName: "name",
type: {
name: "String"
}
},
etag: {
readOnly: true,
serializedName: "etag",
type: {
name: "String"
}
},
id: {
readOnly: true,
serializedName: "id",
type: {
name: "String"
}
},
type: {
readOnly: true,
serializedName: "type",
type: {
name: "String"
}
},
properties: {
serializedName: "properties",
type: {
name: "Composite",
className: "VerificationCodeResponseProperties"
}
}
}
}
};
export const VerificationCodeRequest: msRest.CompositeMapper = {
serializedName: "VerificationCodeRequest",
type: {
name: "Composite",
className: "VerificationCodeRequest",
modelProperties: {
certificate: {
serializedName: "certificate",
type: {
name: "String"
}
}
}
}
};
export const OperationListResult: msRest.CompositeMapper = {
serializedName: "OperationListResult",
type: {
name: "Composite",
className: "OperationListResult",
modelProperties: {
value: {
readOnly: true,
serializedName: "",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "Operation"
}
}
}
},
nextLink: {
readOnly: true,
serializedName: "nextLink",
type: {
name: "String"
}
}
}
}
};
export const ProvisioningServiceDescriptionListResult: msRest.CompositeMapper = {
serializedName: "ProvisioningServiceDescriptionListResult",
type: {
name: "Composite",
className: "ProvisioningServiceDescriptionListResult",
modelProperties: {
value: {
serializedName: "",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ProvisioningServiceDescription"
}
}
}
},
nextLink: {
readOnly: true,
serializedName: "nextLink",
type: {
name: "String"
}
}
}
}
};
export const IotDpsSkuDefinitionListResult: msRest.CompositeMapper = {
serializedName: "IotDpsSkuDefinitionListResult",
type: {
name: "Composite",
className: "IotDpsSkuDefinitionListResult",
modelProperties: {
value: {
serializedName: "",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "IotDpsSkuDefinition"
}
}
}
},
nextLink: {
readOnly: true,
serializedName: "nextLink",
type: {
name: "String"
}
}
}
}
};
export const SharedAccessSignatureAuthorizationRuleListResult: msRest.CompositeMapper = {
serializedName: "SharedAccessSignatureAuthorizationRuleListResult",
type: {
name: "Composite",
className: "SharedAccessSignatureAuthorizationRuleListResult",
modelProperties: {
value: {
serializedName: "",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "SharedAccessSignatureAuthorizationRuleAccessRightsDescription"
}
}
}
},
nextLink: {
readOnly: true,
serializedName: "nextLink",
type: {
name: "String"
}
}
}
}
}; | the_stack |
import { ServicePort } from '../libs/messaging/ServicePort';
import { Component } from '../libs/Component';
import { PlayerApi, PlayerState, PlaybackQuality } from './PlayerApi';
import { PlayerListenable, PlayerEvent } from './PlayerListenable';
import { EventType } from './EventType';
import { Event } from '../libs/events/Event';
import { PlayerData, PlayerConfig } from "./PlayerConfig";
declare interface PlayerApiElement extends HTMLElement {
getApiInterface: () => string[];
}
declare interface VolumeChangeDetail {
muted: boolean;
volume: number;
}
declare interface FullscreenChangeDetail {
fullscreen: number;
time: number;
videoId: string;
}
declare interface VideoDataChangeDetail {
playertype: number;
type: string;
}
declare interface PlayVideoDetail {
listId: string|null;
sessionData: {[key: string]: string|boolean|number};
videoId: string;
watchEndpoint: string|null;
}
export class Player extends Component {
private _id: string;
private _element?: HTMLElement;
private _config: PlayerConfig;
private _port?: ServicePort;
private _api?: PlayerApi;
private _youtubeEvents: {[key: string]: Function} = {};
private _preventDefaultEvents: {[key: string]: boolean} = {};
private _playerListenable?: PlayerListenable;
constructor(id: string, element: HTMLElement, playerConfig: PlayerConfig, port: ServicePort) {
super();
this._id = id;
this._element = element;
this._config = playerConfig;
this._port = port;
// Wrap the player methods to allow for modifying the input.
const api = this.getApi();
for (let key in api) {
if (api.hasOwnProperty(key)) {
(this._element as any)[key] = (...args: any[]) => this.callApi(key, ...args);
}
}
}
protected disposeInternal() {
super.disposeInternal();
const api = this.getApi();
for (let key in api) {
if (api.hasOwnProperty(key)) {
(this._element as any)[key] = (api as any)[key];
}
}
if (this._playerListenable) {
this._playerListenable.dispose();
}
delete this._playerListenable;
delete this._element;
delete this._api;
delete this._port;
}
getElement(): HTMLElement {
if (!this._element) {
throw new Error("Object has been disposed");
}
return this._element;
}
callApi(name: string, ...args: any[]): any {
if (!this._port) {
throw new Error("Object has been disposed");
}
let returnValue: { value: any }|undefined = undefined;
switch (name) {
case "addEventListener":
this._addEventListener(args[0], args[1]);
return;
case "removeEventListener":
this._removeEventListener(args[0], args[1]);
return;
case "destroy":
this._fireEvent(new PlayerEvent(null, "destroy", this), EventType.Destroy);
break;
case "loadVideoByPlayerVars":
case "cueVideoByPlayerVars":
case "updateVideoData":
args[0] = this._port.callSync("player#data-update", this._id, args[0]) as PlayerData || args[0];
default:
returnValue = this._port.callSync("player#api-call", this._id, name, ...args);
break;
}
if (!returnValue) {
const api = this.getApi();
let value = (api as any)[name](...args);
return value;
} else {
return returnValue.value;
}
}
private _addEventListener(type: string, fn: Function|string): void {
const api = this.getApi();
if (this.isDisposed()) {
api.addEventListener(type, fn);
} else {
this.getPlayerListenable().ytAddEventListener(type, fn);
}
}
private _removeEventListener(type: string, fn: Function|string): void {
const api = this.getApi();
if (this.isDisposed()) {
api.removeEventListener(type, fn);
} else {
this.getPlayerListenable().ytRemoveEventListener(type, fn);
}
}
public getPlayerListenable(): PlayerListenable {
if (!this._playerListenable) {
this._playerListenable = new PlayerListenable(this.getApi());
}
return this._playerListenable;
}
enterDocument() {
super.enterDocument();
let player = this.getPlayerListenable();
this.getHandler()
.listen(player, "onReady", this._handleOnReady, false)
.listen(player, "onStateChange", this._handleStateChange, false)
.listen(player, "onVolumeChange", this._handleVolumeChange, false)
.listen(player, "onFullscreenChange", this._handleFullscreenChange, false)
.listen(player, "onPlaybackQualityChange", this._handlePlaybackQualityChange, false)
.listen(player, "onPlaybackRateChange", this._handlePlaybackRateChange, false)
.listen(player, "onApiChange", this._handleApiChange, false)
.listen(player, "onError", this._handleError, false)
.listen(player, "onDetailedError", this._handleDetailedError, false)
.listen(player, "SIZE_CLICKED", this._handleSizeClicked, false)
.listen(player, "onAdStateChange", this._handleAdStateChange, false)
.listen(player, "onSharePanelOpened", this._handleSharePanelOpened, false)
.listen(player, "onPlaybackAudioChange", this._handlePlaybackAudioChange, false)
.listen(player, "onVideoDataChange", this._handleVideoDataChange, false)
.listen(player, "onPlaylistUpdate", this._handlePlaylistUpdate, false)
.listen(player, "onCueRangeEnter", this._handleCueRangeEnter, false)
.listen(player, "onCueRangeExit", this._handleCueRangeExit, false)
.listen(player, "onCueRangeMarkersUpdated", this._handleCueRangeMarkersUpdated, false)
.listen(player, "onCueRangesAdded", this._handleCueRangesAdded, false)
.listen(player, "onCueRangesRemoved", this._handleCueRangesRemoved, false)
.listen(player, "CONNECTION_ISSUE", this._handleConnectionIssue, false)
.listen(player, "SHARE_CLICKED", this._handleShareClicked, false)
.listen(player, "WATCH_LATER_VIDEO_ADDED", this._handleWatchLaterVideoAdded, false)
.listen(player, "WATCH_LATER_VIDEO_REMOVED", this._handleWatchLaterVideoRemoved, false)
.listen(player, "WATCH_LATER_ERROR", this._handleWatchLaterError, false)
.listen(player, "onLoadProgress", this._handleLoadProgress, false)
.listen(player, "onVideoProgress", this._handleVideoProgress, false)
.listen(player, "onReloadRequired", this._handleReloadRequired, false)
.listen(player, "onPlayVideo", this._handlePlayVideo, false)
.listen(player, "onAutonavCoundownStarted", this._handleAutonavCoundownStarted, false)
.listen(player, "onPlaylistNext", console.log.bind(console, "onPlaylistNext"), false)
.listen(player, "onPlaylistPrevious", console.log.bind(console, "onPlaylistPrevious"), false)
.listen(player, "onAdAnnounce", console.log.bind(console, "onAdAnnounce"), false)
.listen(player, "onLogClientVeCreated", console.log.bind(console, "onLogClientVeCreated"), false)
.listen(player, "onLogServerVeCreated", console.log.bind(console, "onLogServerVeCreated"), false)
.listen(player, "onLogVeClicked", console.log.bind(console, "onLogVeClicked"), false)
.listen(player, "onLogVesShown", console.log.bind(console, "onLogVesShown"), false)
.listen(player, "onPlaShelfInfoCardsReady", console.log.bind(console, "onPlaShelfInfoCardsReady"), false)
.listen(player, "onScreenChanged", console.log.bind(console, "onScreenChanged"), false)
.listen(player, "onFeedbackStartRequest", console.log.bind(console, "onFeedbackStartRequest"), false)
.listen(player, "onFeedbackArticleRequest", console.log.bind(console, "onFeedbackArticleRequest"), false)
.listen(player, "onYpcContentRequest", console.log.bind(console, "onYpcContentRequest"), false)
.listen(player, "onAutonavChangeRequest", console.log.bind(console, "onAutonavChangeRequest"), false)
.listen(player, "onAutonavPauseRequest", console.log.bind(console, "onAutonavPauseRequest"), false)
.listen(player, "SUBSCRIBE", console.log.bind(console, "SUBSCRIBE"), false)
.listen(player, "UNSUBSCRIBE", console.log.bind(console, "UNSUBSCRIBE"), false)
.listen(player, "onYtShowToast", console.log.bind(console, "onYtShowToast"), false);
}
exitDocument() {
super.exitDocument();
}
getId(): string {
return this._id;
}
getApi(): PlayerApi {
if (!this._api) {
let player = this._element as PlayerApiElement;
if (!player) throw new Error("Player (" + this.getId() + ") is not initialized.");
// Determine whether the API interface is on the element.
if (typeof player.getApiInterface !== "function") {
throw new Error("No API interface on player element.");
}
// List of all the available API methods.
let apiList = player.getApiInterface();
let api = {} as PlayerApi;
// Populate the API object with the player API.
for (let i = 0; i < apiList.length; i++) {
let key = apiList[i];
(api as any)[key] = (player as any)[key];
}
this._api = api;
}
return this._api;
}
setLoaded(loaded: boolean): void {
Object.defineProperty(this._config, 'loaded', {
"get": () => loaded,
"set": () => {},
"enumerable": true,
"configurable": true
});
}
private _fireEvent(e: Event, type: EventType, ...args: any[]) {
if (!this._port) {
throw new Error("Object has been disposed");
}
const preventDefault = this._port.callSync("player#event", this.getId(), type, ...args) as boolean;
if (preventDefault) {
e.preventDefault();
}
}
private _handleOnReady(e: PlayerEvent<any>) {
this._fireEvent(e, EventType.Ready);
}
private _handleStateChange(e: PlayerEvent<PlayerState>) {
let state = e.detail;
let type: EventType;
switch (state) {
case -1:
type = EventType.Unstarted;
break;
case 0:
type = EventType.Ended;
break;
case 1:
type = EventType.Played;
break;
case 2:
type = EventType.Paused;
break;
case 3:
type = EventType.Buffering;
break;
case 5:
type = EventType.Cued;
break;
default:
return;
}
this._fireEvent(e, type);
}
private _handleVolumeChange(e: PlayerEvent<VolumeChangeDetail>) {
let detail = e.detail;
this._fireEvent(e, EventType.VolumeChange, detail.volume, detail.muted);
}
private _handleFullscreenChange(e: PlayerEvent<FullscreenChangeDetail>) {
let detail = e.detail;
this._fireEvent(e, EventType.FullscreenChange, detail.fullscreen);
}
private _handlePlaybackQualityChange(e: PlayerEvent<PlaybackQuality>) {
let quality = e.detail;
this._fireEvent(e, EventType.QualityChange, quality);
}
private _handlePlaybackRateChange(e: PlayerEvent<number>) {
let rate = e.detail;
this._fireEvent(e, EventType.RateChange, rate);
}
private _handleApiChange(e: PlayerEvent<any>) {
this._fireEvent(e, EventType.ApiChange);
}
private _handleError(e: PlayerEvent<number>) {
let errorCode = e.detail;
this._fireEvent(e, EventType.Error, errorCode);
}
private _handleDetailedError(e: PlayerEvent<any>) {
console.log("DetailedError", e.detail);
}
private _handleSizeClicked(e: PlayerEvent<boolean>) {
this._fireEvent(e, EventType.SizeChange, e.detail);
}
private _handleAdStateChange(e: PlayerEvent<PlayerState>) {
let state = e.detail;
let type: EventType;
switch (state) {
case -1:
type = EventType.AdUnstarted;
break;
case 0:
type = EventType.AdEnded;
break;
case 1:
type = EventType.AdPlayed;
break;
case 2:
type = EventType.AdPaused;
break;
case 3:
type = EventType.AdBuffering;
break;
case 5:
type = EventType.AdCued;
break;
default:
return;
}
this._fireEvent(e, type);
}
private _handleSharePanelOpened(e: PlayerEvent<any>) {
this._fireEvent(e, EventType.SharePanelOpened);
}
private _handlePlaybackAudioChange(e: PlayerEvent<any>) {
console.log("PlaybackAudioChange", e.detail);
}
private _handleVideoDataChange(e: PlayerEvent<VideoDataChangeDetail>) {
const data = e.detail;
this._fireEvent(e, EventType.VideoDataChange, data.type, data.playertype);
}
private _handlePlaylistUpdate(e: PlayerEvent<any>) {
this._fireEvent(e, EventType.PlaylistUpdate);
}
private _handleCueRangeEnter(e: PlayerEvent<any>) {
this._fireEvent(e, EventType.CueRangeEnter, e.detail);
}
private _handleCueRangeExit(e: PlayerEvent<any>) {
this._fireEvent(e, EventType.CueRangeExit, e.detail);
}
private _handleCueRangeMarkersUpdated(e: PlayerEvent<any>) {
console.log("CueRangeMarkersUpdated", e.detail);
}
private _handleCueRangesAdded(e: PlayerEvent<any>) {
console.log("CueRangesAdded", e.detail);
}
private _handleCueRangesRemoved(e: PlayerEvent<any>) {
console.log("CueRangesRemoved", e.detail);
}
private _handleConnectionIssue(e: PlayerEvent<any>) {
this._fireEvent(e, EventType.ConnectionIssue);
}
private _handleShareClicked(e: PlayerEvent<any>) {
this._fireEvent(e, EventType.ShareClicked);
}
private _handleWatchLaterVideoAdded(e: PlayerEvent<any>) {
console.log("WatchLaterVideoAdded", e.detail);
}
private _handleWatchLaterVideoRemoved(e: PlayerEvent<any>) {
console.log("WatchLaterVideoRemoved", e.detail);
}
private _handleWatchLaterError(e: PlayerEvent<any>) {
console.log("WatchLaterError", e.detail);
}
private _handleLoadProgress(e: PlayerEvent<number>) {
this._fireEvent(e, EventType.LoadProgress, e.detail);
}
private _handleVideoProgress(e: PlayerEvent<number>) {
this._fireEvent(e, EventType.VideoProgress, e.detail);
}
private _handleReloadRequired(e: PlayerEvent<any>) {
this._fireEvent(e, EventType.ReloadRequired);
}
private _handlePlayVideo(e: PlayerEvent<PlayVideoDetail>) {
this._fireEvent(e, EventType.PlayVideo, e.detail);
}
private _handleAutonavCoundownStarted(e: PlayerEvent<number>) {
this._fireEvent(e, EventType.AutonavCoundownStarted, e.detail);
}
} | the_stack |
import React from 'react';
import { Schema } from '@formily/react';
import { ISchema } from '../';
import { uid } from '@formily/shared';
import { cloneDeep } from 'lodash';
import { barChartConfig, columnChartConfig } from './chart';
import { i18n } from '../../i18n';
export const generateGridBlock = (schema: ISchema) => {
const name = schema.name || uid();
return {
type: 'void',
name: uid(),
'x-component': 'Grid.Row',
properties: {
[uid()]: {
type: 'void',
'x-component': 'Grid.Col',
properties: {
[name]: schema,
},
},
},
};
};
export const isGrid = (schema: Schema) => {
return schema['x-component'] === 'Grid';
};
export const isGridBlock = (schema: Schema) => {
if (schema.parent['x-component'] !== 'Grid.Col') {
return false;
}
// Grid.Col 里有多少 Block
if (Object.keys(schema.parent.properties).length > 1) {
return false;
}
// 有多少 Grid.Row
if (Object.keys(schema.parent.parent.properties).length > 1) {
return false;
}
return true;
};
export const generateCardItemSchema = (component) => {
const defaults: { [key: string]: ISchema } = {
'Markdown.Void': {
type: 'void',
default: i18n.t('This is a demo text, **supports Markdown syntax**.'),
'x-designable-bar': 'Markdown.Void.DesignableBar',
'x-decorator': 'CardItem',
'x-read-pretty': true,
'x-component': 'Markdown.Void',
},
Table: {
type: 'array',
'x-designable-bar': 'Table.DesignableBar',
'x-decorator': 'CardItem',
'x-component': 'Table',
default: [],
'x-component-props': {
rowKey: 'id',
dragSort: true,
showIndex: true,
refreshRequestOnChange: true,
pagination: {
pageSize: 10,
},
},
properties: {
[uid()]: {
type: 'void',
'x-component': 'Table.ActionBar',
'x-designable-bar': 'Table.ActionBar.DesignableBar',
properties: {
[uid()]: {
type: 'void',
title: "{{t('Filter')}}",
'x-decorator': 'AddNew.Displayed',
'x-decorator-props': {
displayName: 'filter',
},
'x-align': 'left',
'x-component': 'Table.Filter',
'x-designable-bar': 'Table.Filter.DesignableBar',
'x-component-props': {
fieldNames: [],
},
},
[uid()]: {
type: 'void',
name: 'action1',
title: "{{t('Delete')}}",
'x-align': 'right',
'x-decorator': 'AddNew.Displayed',
'x-decorator-props': {
displayName: 'destroy',
},
'x-component': 'Action',
'x-designable-bar': 'Table.Action.DesignableBar',
'x-component-props': {
icon: 'DeleteOutlined',
confirm: {
title: "{{t('Delete record')}}",
content: "{{t('Are you sure you want to delete it?')}}",
},
useAction: '{{ Table.useTableDestroyAction }}',
},
},
[uid()]: {
type: 'void',
name: 'action1',
title: "{{t('Add new')}}",
'x-align': 'right',
'x-decorator': 'AddNew.Displayed',
'x-decorator-props': {
displayName: 'create',
},
'x-component': 'Action',
'x-component-props': {
icon: 'PlusOutlined',
type: 'primary',
},
'x-designable-bar': 'Table.Action.DesignableBar',
properties: {
modal: {
type: 'void',
title: "{{t('Add record')}}",
'x-decorator': 'Form',
'x-component': 'Action.Drawer',
'x-component-props': {
useOkAction: '{{ Table.useTableCreateAction }}',
},
properties: {
[uid()]: {
type: 'void',
'x-component': 'Grid',
'x-component-props': {
addNewComponent: 'AddNew.FormItem',
},
},
},
},
},
},
},
},
[uid()]: {
type: 'void',
title: '{{t("Actions")}}',
'x-component': 'Table.Column',
'x-component-props': {},
'x-designable-bar': 'Table.Operation.DesignableBar',
properties: {
[uid()]: {
type: 'void',
'x-component': 'Action.Group',
'x-component-props': {
type: 'link',
},
properties: {
[uid()]: {
type: 'void',
name: 'action1',
title: "{{t('View')}}",
'x-component': 'Action',
'x-component-props': {
type: 'link',
},
'x-designable-bar': 'Table.Action.DesignableBar',
'x-action-type': 'view',
properties: {
[uid()]: {
type: 'void',
title: "{{t('View record')}}",
'x-component': 'Action.Drawer',
'x-component-props': {
bodyStyle: {
background: '#f0f2f5',
// paddingTop: 0,
},
},
properties: {
[uid()]: {
type: 'void',
'x-component': 'Tabs',
'x-designable-bar': 'Tabs.DesignableBar',
properties: {
[uid()]: {
type: 'void',
title: "{{t('Details')}}",
'x-designable-bar': 'Tabs.TabPane.DesignableBar',
'x-component': 'Tabs.TabPane',
'x-component-props': {},
properties: {
[uid()]: {
type: 'void',
'x-component': 'Grid',
'x-component-props': {
addNewComponent: 'AddNew.PaneItem',
},
},
},
},
},
},
},
},
},
},
[uid()]: {
type: 'void',
title: "{{t('Edit')}}",
'x-component': 'Action',
'x-component-props': {
type: 'link',
},
'x-designable-bar': 'Table.Action.DesignableBar',
'x-action-type': 'update',
properties: {
[uid()]: {
type: 'void',
title: "{{t('Edit record')}}",
'x-decorator': 'Form',
'x-decorator-props': {
useResource: '{{ Table.useResource }}',
useValues: '{{ Table.useTableRowRecord }}',
},
'x-component': 'Action.Drawer',
'x-component-props': {
useOkAction: '{{ Table.useTableUpdateAction }}',
},
properties: {
[uid()]: {
type: 'void',
'x-component': 'Grid',
'x-component-props': {
addNewComponent: 'AddNew.FormItem',
},
},
},
},
},
},
// [uid()]: {
// type: 'void',
// title: '删除',
// 'x-component': 'Action',
// 'x-designable-bar': 'Table.Action.DesignableBar',
// 'x-action-type': 'destroy',
// 'x-component-props': {
// type: 'link',
// useAction: '{{ Table.useTableDestroyAction }}',
// },
// },
},
},
},
},
},
},
Form: {
type: 'void',
name: uid(),
'x-decorator': 'CardItem',
'x-component': 'Form',
'x-component-props': {
showDefaultButtons: true,
},
'x-designable-bar': 'Form.DesignableBar',
properties: {
[uid()]: {
type: 'void',
'x-component': 'Grid',
'x-component-props': {
addNewComponent: 'AddNew.FormItem',
},
},
},
},
Descriptions: {
type: 'void',
name: uid(),
'x-decorator': 'CardItem',
'x-component': 'Form',
'x-read-pretty': true,
'x-designable-bar': 'Form.DesignableBar',
properties: {
[uid()]: {
type: 'void',
'x-component': 'Grid',
'x-component-props': {
addNewComponent: 'AddNew.FormItem',
},
},
},
},
Kanban: {
type: 'array',
'x-component': 'Kanban',
'x-designable-bar': 'Kanban.DesignableBar',
'x-component-props': {},
'x-decorator': 'CardItem',
'x-decorator-props': {
style: {
background: 'none',
},
bodyStyle: {
padding: 0,
},
},
properties: {
create: {
type: 'void',
title: "{{t('Add card')}}",
// 'x-designable-bar': 'Kanban.AddCardDesignableBar',
'x-component': 'Kanban.Card.AddNew',
// 'x-decorator': 'AddNew.Displayed',
'x-component-props': {
type: 'text',
icon: 'PlusOutlined',
},
properties: {
modal: {
type: 'void',
title: "{{t('Add record')}}",
'x-decorator': 'Form',
'x-decorator-props': {
useResource: '{{ Kanban.useCreateResource }}',
},
'x-component': 'Action.Drawer',
'x-component-props': {
useOkAction: '{{ Kanban.useCreateAction }}',
},
properties: {
[uid()]: {
type: 'void',
'x-component': 'Grid',
'x-component-props': {
addNewComponent: 'AddNew.FormItem',
},
},
},
},
},
},
card1: {
type: 'void',
name: uid(),
'x-decorator': 'Form',
'x-component': 'Kanban.Card',
'x-designable-bar': 'Kanban.Card.DesignableBar',
'x-read-pretty': true,
'x-decorator-props': {
useResource: '{{ Kanban.useRowResource }}',
},
properties: {},
},
view1: {
type: 'void',
title: "{{t('Edit record')}}",
'x-decorator': 'Form',
'x-component': 'Kanban.Card.View',
'x-component-props': {
useOkAction: '{{ Kanban.useUpdateAction }}',
},
'x-decorator-props': {
useResource: '{{ Kanban.useSingleResource }}',
},
properties: {
[uid()]: {
type: 'void',
'x-component': 'Grid',
'x-component-props': {
addNewComponent: 'AddNew.FormItem',
},
},
},
},
},
},
Calendar: {
type: 'array',
name: 'calendar1',
'x-component': 'Calendar',
'x-designable-bar': 'Calendar.DesignableBar',
'x-decorator': 'CardItem',
default: [],
properties: {
toolbar: {
type: 'void',
'x-component': 'Calendar.Toolbar',
properties: {
today: {
type: 'void',
title: "{{t('Today')}}",
'x-designable-bar': 'Calendar.ActionDesignableBar',
'x-component': 'Calendar.Today',
'x-align': 'left',
'x-decorator': 'AddNew.Displayed',
'x-decorator-props': {
displayName: 'today',
},
},
nav: {
type: 'void',
title: "{{t('Navigate')}}",
'x-designable-bar': 'Calendar.ActionDesignableBar',
'x-component': 'Calendar.Nav',
'x-align': 'left',
'x-decorator': 'AddNew.Displayed',
'x-decorator-props': {
displayName: 'nav',
},
},
title: {
type: 'void',
title: "{{t('Title')}}",
'x-designable-bar': 'Calendar.ActionDesignableBar',
'x-component': 'Calendar.Title',
'x-align': 'left',
'x-decorator': 'AddNew.Displayed',
'x-decorator-props': {
displayName: 'title',
},
},
viewSelect: {
type: 'void',
title: "{{t('Select view')}}",
'x-designable-bar': 'Calendar.ActionDesignableBar',
'x-component': 'Calendar.ViewSelect',
'x-align': 'right',
'x-decorator': 'AddNew.Displayed',
'x-decorator-props': {
displayName: 'viewSelect',
},
},
filter: {
type: 'void',
title: "{{t('Filter')}}",
'x-align': 'right',
'x-designable-bar': 'Calendar.Filter.DesignableBar',
'x-component': 'Calendar.Filter',
'x-decorator': 'AddNew.Displayed',
'x-decorator-props': {
displayName: 'filter',
},
},
create: {
type: 'void',
title: "{{t('Add new')}}",
'x-align': 'right',
'x-designable-bar': 'Calendar.ActionDesignableBar',
'x-component': 'Action',
'x-decorator': 'AddNew.Displayed',
'x-decorator-props': {
displayName: 'create',
},
'x-component-props': {
type: 'primary',
icon: 'PlusOutlined',
},
properties: {
modal: {
type: 'void',
title: "{{t('Add record')}}",
'x-decorator': 'Form',
'x-component': 'Action.Drawer',
'x-component-props': {
useOkAction: '{{ Calendar.useCreateAction }}',
},
properties: {
[uid()]: {
type: 'void',
'x-component': 'Grid',
'x-component-props': {
addNewComponent: 'AddNew.FormItem',
},
},
},
},
},
},
},
},
event: {
type: 'void',
'x-component': 'Calendar.Event',
properties: {
[uid()]: {
type: 'void',
'x-component': 'Tabs',
'x-designable-bar': 'Tabs.DesignableBar',
properties: {
[uid()]: {
type: 'void',
title: "{{t('Details')}}",
'x-designable-bar': 'Tabs.TabPane.DesignableBar',
'x-component': 'Tabs.TabPane',
'x-component-props': {},
properties: {
[uid()]: {
type: 'void',
'x-component': 'Grid',
'x-component-props': {
addNewComponent: 'AddNew.PaneItem',
},
},
},
},
},
},
},
},
},
},
'Chart.Column': {
type: 'void',
'x-decorator': 'CardItem',
'x-component': 'Chart.Column',
'x-designable-bar': 'Chart.DesignableBar',
'x-component-props': {
config: cloneDeep(columnChartConfig[i18n.language] || columnChartConfig['en-US']),
},
},
'Chart.Bar': {
type: 'void',
'x-decorator': 'CardItem',
'x-component': 'Chart.Bar',
'x-designable-bar': 'Chart.DesignableBar',
'x-component-props': {
config: cloneDeep(barChartConfig[i18n.language] || barChartConfig['en-US']),
},
},
'Ref.ActionLogs': {
type: 'array',
name: 'table',
'x-decorator': 'CardItem',
'x-component': 'Table',
'x-designable-bar': 'Table.SimpleDesignableBar',
default: [],
'x-component-props': {
useResource: '{{ Table.useActionLogsResource }}',
collectionName: 'action_logs',
rowKey: 'id',
// dragSort: true,
showIndex: true,
defaultSort: ['-id'],
defaultAppends: ['user', 'collection'],
refreshRequestOnChange: true,
pagination: {
pageSize: 10,
},
},
properties: {
[uid()]: {
type: 'void',
'x-component': 'Table.ActionBar',
properties: {
[uid()]: {
type: 'void',
title: "{{t('Filter')}}",
'x-align': 'left',
'x-component': 'Table.Filter',
'x-component-props': {
fieldNames: [],
},
properties: {
column1: {
type: 'void',
title: "{{t('Action type')}}",
'x-component': 'Filter.Column',
'x-component-props': {
operations: [
{
label: "{{ t('is') }}",
value: 'eq',
selected: true,
schema: { 'x-component': 'Select' },
},
{
label: "{{ t('is not') }}",
value: 'ne',
schema: { 'x-component': 'Select' },
},
{
label: "{{ t('contains') }}",
value: 'in',
schema: {
'x-component': 'Select',
'x-component-props': { mode: 'tags' },
},
},
{
label: "{{ t('does not contain') }}",
value: 'notIn',
schema: {
'x-component': 'Select',
'x-component-props': { mode: 'tags' },
},
},
{
label: "{{ t('is empty') }}",
value: '$null',
noValue: true,
},
{
label: "{{ t('is not empty') }}",
value: '$notNull',
noValue: true,
},
],
},
properties: {
type: {
type: 'string',
'x-component': 'Select',
enum: [
{
label: "{{ t('Insert') }}",
value: 'create',
color: 'green',
},
{
label: "{{ t('Update') }}",
value: 'update',
color: 'blue',
},
{
label: "{{ t('Delete') }}",
value: 'destroy',
color: 'red',
},
],
},
},
},
},
},
},
},
column1: {
type: 'void',
title: "{{t('Created at')}}",
'x-component': 'Table.Column',
properties: {
created_at: {
type: 'string',
'x-component': 'DatePicker',
'x-read-pretty': true,
'x-component-props': {
format: 'YYYY-MM-DD HH:mm:ss',
},
},
},
},
column2: {
type: 'void',
title: "{{t('Created by')}}",
'x-component': 'Table.Column',
properties: {
'user.nickname': {
type: 'string',
'x-component': 'Input',
'x-read-pretty': true,
},
},
},
column3: {
type: 'void',
title: "{{t('Collection display name')}}",
'x-component': 'Table.Column',
properties: {
'collection.title': {
type: 'string',
'x-component': 'Input',
'x-read-pretty': true,
},
},
},
column4: {
type: 'void',
title: "{{t('Action type')}}",
'x-component': 'Table.Column',
properties: {
type: {
type: 'string',
'x-component': 'Select',
'x-read-pretty': true,
enum: [
{ label: "{{ t('Insert') }}", value: 'create', color: 'green' },
{ label: "{{ t('Update') }}", value: 'update', color: 'blue' },
{ label: "{{ t('Delete') }}", value: 'destroy', color: 'red' },
],
},
},
},
[uid()]: {
type: 'void',
title: "{{t('Actions')}}",
'x-component': 'Table.Column',
'x-component-props': {
width: 60,
align: 'center',
},
properties: {
[uid()]: {
type: 'void',
name: 'action1',
title: "{{t('View')}}",
'x-component': 'Action',
'x-component-props': {
type: 'link',
style: {
padding: '0',
height: 'auto',
},
},
'x-action-type': 'view',
properties: {
[uid()]: {
type: 'void',
title: "{{t('View record')}}",
'x-read-pretty': true,
'x-decorator': 'Form',
'x-decorator-props': {
useResource: '{{ Table.useActionLogDetailsResource }}',
},
'x-component': 'Action.Drawer',
'x-component-props': {
// bodyStyle: {
// background: '#f0f2f5',
// // paddingTop: 0,
// },
},
properties: {
created_at: {
type: 'string',
title: "{{t('Created at')}}",
'x-decorator': 'FormItem',
'x-component': 'DatePicker',
'x-read-pretty': true,
'x-component-props': {
format: 'YYYY-MM-DD HH:mm:ss',
},
},
'user.nickname': {
type: 'string',
title: "{{t('Created by')}}",
'x-decorator': 'FormItem',
'x-component': 'Input',
'x-read-pretty': true,
},
'collection.title': {
type: 'string',
title: "{{t('Collection display name')}}",
'x-decorator': 'FormItem',
'x-component': 'Input',
'x-read-pretty': true,
},
type: {
type: 'string',
title: "{{t('Action type')}}",
'x-decorator': 'FormItem',
'x-component': 'Select',
'x-read-pretty': true,
enum: [
{
label: "{{t('Insert')}}",
value: 'create',
color: 'green',
},
{
label: "{{t('Update')}}",
value: 'update',
color: 'blue',
},
{
label: "{{t('Delete')}}",
value: 'destroy',
color: 'red',
},
],
},
changes: {
type: 'array',
title: "{{t('Data changes')}}",
'x-decorator': 'FormItem',
'x-component': 'ArrayTable',
'x-component-props': {
pagination: false,
// scroll: { x: '100%' },
},
// 'x-reactions': ['{{ filterActionLogs }}'],
items: {
type: 'object',
properties: {
column0: {
type: 'void',
'x-component': 'ArrayTable.Column',
'x-component-props': {
width: 80,
align: 'center',
},
properties: {
index: {
type: 'void',
'x-component': 'ArrayTable.Index',
},
},
},
column1: {
type: 'void',
'x-component': 'ArrayTable.Column',
'x-component-props': { title: "{{t('Field display name')}}" },
properties: {
field: {
type: 'string',
'x-decorator': 'FormilyFormItem',
'x-component': 'ActionLogs.Field',
},
},
},
column3: {
type: 'void',
'x-component': 'ArrayTable.Column',
'x-component-props': { title: "{{ t('Before change') }}" },
properties: {
before: {
type: 'string',
'x-decorator': 'FormilyFormItem',
'x-component': 'ActionLogs.FieldValue',
},
},
},
column4: {
type: 'void',
'x-component': 'ArrayTable.Column',
'x-component-props': { title: "{{ t('After change') }}" },
properties: {
after: {
type: 'string',
'x-decorator': 'FormilyFormItem',
'x-component': 'ActionLogs.FieldValue',
},
},
},
},
},
},
},
},
},
},
},
},
},
},
};
return defaults[component];
};
export const generateFormItemSchema = (component) => {
const defaults = {
Markdown: {
type: 'string',
title: uid(),
'x-designable-bar': 'Markdown.DesignableBar',
'x-decorator': 'FormItem',
'x-component': 'Markdown',
'x-component-props': {},
},
};
return defaults[component];
}; | the_stack |
import test from 'ava';
import { nohm } from '../ts';
import * as args from './testArgs';
import { cleanUpPromise } from './helper';
import { keys, smembers, exists, sismember } from '../ts/typed-redis-helper';
const redis = args.redis;
const prefix = args.prefix + 'relations';
let relationsPrefix = '';
test.before(async () => {
nohm.setPrefix(prefix);
relationsPrefix = nohm.prefix.relations;
await args.setClient(nohm, redis);
await cleanUpPromise(redis, prefix);
});
test.afterEach(async () => {
await cleanUpPromise(redis, prefix);
});
const UserLinkMockup = nohm.model('UserLinkMockup', {
properties: {
name: {
defaultValue: 'testName',
type: 'string',
validations: ['notEmpty'],
},
},
});
const CommentLinkMockup = nohm.model('CommentLinkMockup', {
properties: {
text: {
defaultValue: 'this is a comment! REALLY!',
type: 'string',
validations: ['notEmpty'],
},
},
});
const RoleLinkMockup = nohm.model('RoleLinkMockup', {
properties: {
name: {
defaultValue: 'user',
type: 'string',
},
},
});
test.serial('instances', (t) => {
const user = new UserLinkMockup();
const role = new RoleLinkMockup();
role.link(user);
t.not(
// @ts-ignore
role.relationChanges,
// @ts-ignore
user.relationChanges,
'Instances share the relationChanges, initiate them as an empty array in the constructor.',
);
const role2 = new RoleLinkMockup();
t.deepEqual(
// @ts-ignore
role2.relationChanges,
[],
'Creating a new instance does not reset the relationChanges of that instance.',
);
});
test.serial('link', async (t) => {
const user = new UserLinkMockup();
const role = new RoleLinkMockup();
const role2 = new RoleLinkMockup();
let linkCallbackCalled = false;
let linkCallbackCalled2 = false;
user.link(role, (action, on, name, obj) => {
linkCallbackCalled = true;
t.is(
action,
'link',
'The argument "action" given to the link callback are not correct',
);
t.is(
on,
'UserLinkMockup',
'The argument "on" given to the link callback are not correct',
);
t.is(
name,
'default',
'The argument "name" given to the link callback are not correct',
);
t.is(
obj,
role,
'The argument "obj" given to the link callback are not correct',
);
});
role2.property('name', 'test');
user.link(role2, () => {
linkCallbackCalled2 = true;
});
await user.save();
t.true(
linkCallbackCalled,
'The provided callback for linking was not called.',
);
t.true(
linkCallbackCalled2,
'The provided callback for the second(!) linking was not called.',
);
const values = await keys(redis, relationsPrefix + '*');
t.is(
values.length,
3,
'Linking an object did not create the correct number of keys.',
);
await Promise.all(
values.map<Promise<void>>(async (value) => {
const isForeignLink = value.includes(':defaultForeign:');
// user links to role1 and role2, each role links to only user
const ids = isForeignLink ? [user.id] : [role.id, role2.id];
const members = await smembers(redis, value.toString());
t.deepEqual(members.sort(), ids.sort());
}),
);
});
test.serial('unlink', async (t) => {
const user = new UserLinkMockup();
const role = new RoleLinkMockup();
const role2 = new RoleLinkMockup();
let unlinkCallbackCalled = false;
let unlinkCallbackCalled2 = false;
user.id = '1';
role.id = '1';
role2.id = '2';
user.unlink(role, (action, on, name, obj) => {
unlinkCallbackCalled = true;
t.is(
action,
'unlink',
'The argument "action" given to the unlink callback are not correct',
);
t.is(
on,
'UserLinkMockup',
'The argument "on" given to the unlink callback are not correct',
);
t.is(
name,
'default',
'The argument "name" given to the unlink callback are not correct',
);
t.is(
obj,
role,
'The argument "obj" given to the unlink callback are not correct',
);
});
user.unlink(role2, () => {
unlinkCallbackCalled2 = true;
});
await user.save();
t.true(
unlinkCallbackCalled,
'The provided callback for unlinking was not called.',
);
t.true(
unlinkCallbackCalled2,
'The provided callback for the second(!) unlinking was not called.',
);
const relationKeys = await keys(redis, relationsPrefix + '*');
const check =
(Array.isArray(relationKeys) && relationKeys.length === 0) ||
relationKeys === null;
t.true(check, 'Unlinking an object did not delete keys.');
});
test.serial('deepLink', async (t) => {
const user = new UserLinkMockup();
const role = new RoleLinkMockup();
const comment = new CommentLinkMockup();
let userLinkCallbackCalled = false;
let commentLinkCallbackCalled = false;
role.link(user, () => {
userLinkCallbackCalled = true;
});
user.link(comment, () => {
commentLinkCallbackCalled = true;
});
await role.save();
t.true(userLinkCallbackCalled, 'The user link callback was not called.');
t.true(
commentLinkCallbackCalled,
'The comment link callback was not called.',
);
t.true(
user.id !== null,
'The deep linked user does not have an id and thus is probably not saved correctly.',
);
t.true(
comment.id !== null,
'The deep linked comment does not have an id and thus is probably not saved correctly.',
);
const value = await smembers(
redis,
relationsPrefix +
comment.modelName +
':defaultForeign:' +
user.modelName +
':' +
comment.id,
);
t.is(
value[0],
user.id,
'The user does not have the necessary relations saved. There are probably more problems, if this occurs.',
);
});
test.serial('removeUnlinks', async (t) => {
// uses unlinkAll in remove
const user = new UserLinkMockup();
const role = new RoleLinkMockup();
const role2 = new RoleLinkMockup();
const comment = new CommentLinkMockup();
const linkName = 'creator';
user.property('name', 'removeUnlinks');
role.link(user, linkName);
user.link(role, 'isA');
user.link(comment);
role2.link(user);
await role2.save();
const tmpId = user.id;
if (typeof tmpId !== 'string') {
throw new Error('Saving failed to save relation.');
}
await user.remove();
const foreignRoleLinkExists = await exists(
redis,
relationsPrefix +
user.modelName +
':' +
linkName +
'Foreign:' +
role.modelName +
':' +
tmpId,
);
t.is(
foreignRoleLinkExists,
0,
'The foreign link to the custom-link-name role was not deleted',
);
const roleLinkExists = await exists(
redis,
relationsPrefix +
role.modelName +
':' +
linkName +
':' +
user.modelName +
':' +
role.id,
);
t.is(
roleLinkExists,
0,
'The link to the custom-link-name role was not deleted',
);
const commentLinkExists = await exists(
redis,
relationsPrefix +
user.modelName +
':default:' +
comment.modelName +
':' +
tmpId,
);
t.is(commentLinkExists, 0, 'The link to the child comment was not deleted');
const foreignCommentIds = await sismember(
redis,
relationsPrefix +
comment.modelName +
':defaultForeign:' +
user.modelName +
':' +
comment.id,
tmpId,
);
t.is(foreignCommentIds, 0, 'The link to the comment parent was not deleted');
const roleParentIds = await sismember(
redis,
relationsPrefix +
role2.modelName +
':default:' +
user.modelName +
':' +
role2.id,
tmpId,
);
t.is(
roleParentIds,
0,
'The removal did not delete the link from a parent to the object itself.',
);
});
test.serial('belongsTo', async (t) => {
const user = new UserLinkMockup();
const role = new RoleLinkMockup();
user.link(role);
await user.save();
const belongs = await user.belongsTo(role);
t.is(belongs, true, 'The link was not detected correctly by belongsTo()');
});
test.serial('getAll', async (t) => {
const user = new UserLinkMockup();
const role = new RoleLinkMockup();
const role2 = new RoleLinkMockup();
user.link(role);
user.link(role2);
await user.save();
const should = [role.id, role2.id].sort();
const relationIds = await user.getAll(role.modelName);
t.true(Array.isArray(relationIds), 'getAll() did not return an array.');
t.deepEqual(
relationIds.sort(),
should,
'getAll() did not return the correct array',
);
});
test.serial('getAll with different id generators', async (t) => {
const user = new UserLinkMockup();
const comment = new CommentLinkMockup();
user.link(comment);
await user.save();
const should = [comment.id];
const relationIds = await user.getAll(comment.modelName);
t.deepEqual(relationIds, should, 'getAll() did not return the correct array');
});
test.serial('numLinks', async (t) => {
const user = new UserLinkMockup();
const role = new RoleLinkMockup();
const role2 = new RoleLinkMockup();
user.link(role);
user.link(role2);
await user.save();
const numLinks = await user.numLinks(role.modelName);
t.is(numLinks, 2, 'The number of links was not returned correctly');
});
test.serial('deep link errors', async (t) => {
const user = new UserLinkMockup();
const role = new RoleLinkMockup();
const comment = new CommentLinkMockup();
role.link(user);
user.link(comment);
comment.property('text', ''); // makes the comment fail
try {
await role.save();
} catch (err) {
t.true(
user.id !== null,
'The deep linked user does not have an id and thus is probably not saved correctly.',
);
t.is(
comment.id,
null,
'The deep linked erroneous comment does not have an id and thus is probably saved.',
);
t.true(
err instanceof nohm.LinkError,
'The deep linked comment did not produce a top-level LinkError.',
);
t.is(
err.errors.length,
1,
'The deep linked role did not fail in a child or reported it wrong.',
);
t.true(
err.errors[0].error instanceof nohm.ValidationError,
'The deep linked comment did not produce a ValidationError.',
);
t.deepEqual(
err.errors[0].child.errors,
{ text: ['notEmpty'] },
'The deep linked role did not fail.',
);
t.is(
err.errors[0].child.modelName,
'CommentLinkMockup',
'The deep linked role failed in the wrong model or reported it wrong.',
);
t.is(
err.errors[0].parent.modelName,
'UserLinkMockup',
'The deep linked role failed in the wrong model or reported it wrong.',
);
}
});
test.serial('linkToSelf', async (t) => {
const user = new UserLinkMockup();
user.link(user);
await user.save();
t.true(true, 'Linking an object to itself failed.');
});
test.serial('deppLinkErrorCallback', async (t) => {
const user = new UserLinkMockup();
const role = new RoleLinkMockup();
const comment = new CommentLinkMockup();
role.link(user, {
error: (err, obj) => {
console.log(err, obj.errors, obj.allProperties());
t.fail(
'Error callback for role.link(user) called even though user is valid.',
);
},
});
user.link(comment, {
error: (err, obj) => {
t.true(
err instanceof nohm.ValidationError,
'err in error callback was not a ValidationError',
);
t.is(comment, obj, 'obj in Error callback was not the right object.');
},
});
comment.property('text', ''); // makes the comment fail
try {
await role.save();
} catch (err) {
t.true(
user.id !== null,
'The deep linked user does not have an id and thus is probably not saved correctly.',
);
t.is(
comment.id,
null,
'The deep linked erroneous comment does not have an id and thus is probably saved.',
);
t.true(
err instanceof nohm.LinkError,
'The deep linked role did not fail in a child or reported it wrong.',
);
t.is(
err.errors[0].child.modelName,
'CommentLinkMockup',
'The deep linked role failed in the wrong model or reported it wrong.',
);
}
});
test.serial('continueOnError', async (t) => {
const user = new UserLinkMockup();
const role = new RoleLinkMockup();
const comment = new CommentLinkMockup();
const comment2 = new CommentLinkMockup();
const comment3 = new CommentLinkMockup();
role.link(user, {
error: (err, obj) => {
console.log(err, obj.errors, obj.allProperties());
t.fail(
'Error callback for role.link(user) called even though user is valid.',
);
},
});
user.link(comment, {
error: (err, obj) => {
t.true(
err instanceof nohm.ValidationError,
'err in error callback was not a ValidationError',
);
t.is(comment, obj, 'obj in Error callback was not the right object.');
},
});
user.link(comment2, {
error: (err, obj) => {
console.log(err, obj.errors, obj.allProperties());
t.fail(
'Error callback for comment2.link(user) called even though user is valid.',
);
},
});
user.link(comment3, {
error: (err, obj) => {
console.log(err, obj.errors, obj.allProperties());
t.fail(
'Error callback for comment3.link(user) called even though user is valid.',
);
},
});
comment.property('text', ''); // makes the first comment fail
try {
await role.save();
} catch (e) {
t.true(
e instanceof nohm.LinkError,
'Error thrown by save() was not a link error.',
);
t.is(e.errors.length, 1, 'LinkError contained too many error items');
t.is(e.errors[0].parent, user, 'LinkError parent was not user.');
t.is(e.errors[0].child, comment, 'LinkError child was not comment.');
t.true(
e.errors[0].error instanceof nohm.ValidationError,
'LinkError contained error was not ValidationError.',
);
if (typeof user.id !== 'string') {
throw new Error('Saving failed to save relation.');
}
const commentForeignUserIds = await sismember(
redis,
relationsPrefix +
comment3.modelName +
':defaultForeign:' +
user.modelName +
':' +
comment3.id,
user.id,
);
t.is(commentForeignUserIds, 1, 'The comment3 relation was not saved');
}
});
/* Maybe this isn't such a good idea. I like that model definitions are completely
lacking relation definitions.
cascadingDeletes: function (t) {
const user = new UserLinkMockup(),
role = new RoleLinkMockup(),
comment = new CommentLinkMockup(),
testComment = new CommentLinkMockup();
;
user.link(role);
role.link(comment);
user.save(function (err) {
if (err) {
console.dir(err);
}
const testid = comment.id;
user.remove(function (err) {
if (err) {
console.dir(err);
}
testComment.load(testid, function (err) {
t.is(err, 'not found', 'Removing an object that has cascading deletes did not remove the relations');
});
});
});
};*/ | the_stack |
import { ContextLevel } from '@/core/constants';
import { Injectable } from '@angular/core';
import { CoreCourseActivitySyncBaseProvider } from '@features/course/classes/activity-sync';
import { CoreCourseLogHelper } from '@features/course/services/log-helper';
import { CoreFileUploader } from '@features/fileuploader/services/fileuploader';
import { CoreRatingSync } from '@features/rating/services/rating-sync';
import { CoreApp } from '@services/app';
import { CoreGroups } from '@services/groups';
import { CoreSites } from '@services/sites';
import { CoreSync } from '@services/sync';
import { CoreUtils } from '@services/utils/utils';
import { makeSingleton, Translate } from '@singletons';
import { CoreArray } from '@singletons/array';
import { CoreEvents } from '@singletons/events';
import {
AddonModForum,
AddonModForumAddDiscussionPostWSOptionsObject,
AddonModForumAddDiscussionWSOptionsObject,
AddonModForumProvider,
} from './forum';
import { AddonModForumHelper } from './forum-helper';
import { AddonModForumOffline, AddonModForumOfflineDiscussion, AddonModForumOfflineReply } from './forum-offline';
declare module '@singletons/events' {
/**
* Augment CoreEventsData interface with events specific to this service.
*
* @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation
*/
export interface CoreEventsData {
[AddonModForumSyncProvider.AUTO_SYNCED]: AddonModForumAutoSyncData;
[AddonModForumSyncProvider.MANUAL_SYNCED]: AddonModForumManualSyncData;
}
}
/**
* Service to sync forums.
*/
@Injectable({ providedIn: 'root' })
export class AddonModForumSyncProvider extends CoreCourseActivitySyncBaseProvider<AddonModForumSyncResult> {
static readonly AUTO_SYNCED = 'addon_mod_forum_autom_synced';
static readonly MANUAL_SYNCED = 'addon_mod_forum_manual_synced';
protected componentTranslatableString = 'forum';
constructor() {
super('AddonModForumSyncProvider');
}
/**
* Try to synchronize all the forums in a certain site or in all sites.
*
* @param siteId Site ID to sync. If not defined, sync all sites.
* @param force Wether to force sync not depending on last execution.
* @return Promise resolved if sync is successful, rejected if sync fails.
*/
async syncAllForums(siteId?: string, force?: boolean): Promise<void> {
await this.syncOnSites('all forums', this.syncAllForumsFunc.bind(this, !!force), siteId);
}
/**
* Sync all forums on a site.
*
* @param force Wether to force sync not depending on last execution.
* @param siteId Site ID to sync.
* @return Promise resolved if sync is successful, rejected if sync fails.
*/
protected async syncAllForumsFunc(force: boolean, siteId: string): Promise<void> {
const sitePromises: Promise<unknown>[] = [];
// Sync all new discussions.
const syncDiscussions = async (discussions: AddonModForumOfflineDiscussion[]) => {
// Do not sync same forum twice.
const syncedForumIds: number[] = [];
const promises = discussions.map(async discussion => {
if (CoreArray.contains(syncedForumIds, discussion.forumid)) {
return;
}
syncedForumIds.push(discussion.forumid);
const result = force
? await this.syncForumDiscussions(discussion.forumid, discussion.userid, siteId)
: await this.syncForumDiscussionsIfNeeded(discussion.forumid, discussion.userid, siteId);
if (result && result.updated) {
// Sync successful, send event.
CoreEvents.trigger(AddonModForumSyncProvider.AUTO_SYNCED, {
forumId: discussion.forumid,
userId: discussion.userid,
warnings: result.warnings,
}, siteId);
}
});
await Promise.all(Object.values(promises));
};
sitePromises.push(
AddonModForumOffline.instance
.getAllNewDiscussions(siteId)
.then(discussions => syncDiscussions(discussions)),
);
// Sync all discussion replies.
const syncReplies = async (replies: AddonModForumOfflineReply[]) => {
// Do not sync same discussion twice.
const syncedDiscussionIds: number[] = [];
const promises = replies.map(async reply => {
if (CoreArray.contains(syncedDiscussionIds, reply.discussionid)) {
return;
}
const result = force
? await this.syncDiscussionReplies(reply.discussionid, reply.userid, siteId)
: await this.syncDiscussionRepliesIfNeeded(reply.discussionid, reply.userid, siteId);
if (result && result.updated) {
// Sync successful, send event.
CoreEvents.trigger(AddonModForumSyncProvider.AUTO_SYNCED, {
forumId: reply.forumid,
discussionId: reply.discussionid,
userId: reply.userid,
warnings: result.warnings,
}, siteId);
}
});
await Promise.all(promises);
};
sitePromises.push(
AddonModForumOffline.instance
.getAllReplies(siteId)
.then(replies => syncReplies(replies)),
);
// Sync ratings.
sitePromises.push(this.syncRatings(undefined, undefined, force, siteId));
await Promise.all(sitePromises);
}
/**
* Sync a forum only if a certain time has passed since the last time.
*
* @param forumId Forum ID.
* @param userId User the discussion belong to.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the forum is synced or if it doesn't need to be synced.
*/
async syncForumDiscussionsIfNeeded(
forumId: number,
userId: number,
siteId?: string,
): Promise<AddonModForumSyncResult | void> {
siteId = siteId || CoreSites.getCurrentSiteId();
const syncId = this.getForumSyncId(forumId, userId);
const needed = await this.isSyncNeeded(syncId, siteId);
if (needed) {
return this.syncForumDiscussions(forumId, userId, siteId);
}
}
/**
* Synchronize all offline discussions of a forum.
*
* @param forumId Forum ID to be synced.
* @param userId User the discussions belong to.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved if sync is successful, rejected otherwise.
*/
async syncForumDiscussions(
forumId: number,
userId?: number,
siteId?: string,
): Promise<AddonModForumSyncResult> {
userId = userId || CoreSites.getCurrentSiteUserId();
siteId = siteId || CoreSites.getCurrentSiteId();
const syncId = this.getForumSyncId(forumId, userId);
if (this.isSyncing(syncId, siteId)) {
// There's already a sync ongoing for this discussion, return the promise.
return this.getOngoingSync(syncId, siteId)!;
}
// Verify that forum isn't blocked.
if (CoreSync.isBlocked(AddonModForumProvider.COMPONENT, syncId, siteId)) {
this.logger.debug('Cannot sync forum ' + forumId + ' because it is blocked.');
throw new Error(Translate.instant('core.errorsyncblocked', { $a: this.componentTranslate }));
}
this.logger.debug('Try to sync forum ' + forumId + ' for user ' + userId);
const result: AddonModForumSyncResult = {
warnings: [],
updated: false,
};
// Sync offline logs.
const syncDiscussions = async (): Promise<{ warnings: string[]; updated: boolean }> => {
await CoreUtils.ignoreErrors(
CoreCourseLogHelper.syncActivity(AddonModForumProvider.COMPONENT, forumId, siteId),
);
// Get offline responses to be sent.
const discussions = await CoreUtils.ignoreErrors(
AddonModForumOffline.getNewDiscussions(forumId, siteId, userId),
[] as AddonModForumOfflineDiscussion[],
);
if (discussions.length !== 0 && !CoreApp.isOnline()) {
throw new Error('cannot sync in offline');
}
const promises = discussions.map(async discussion => {
const errors: Error[] = [];
const groupIds = discussion.groupid === AddonModForumProvider.ALL_GROUPS
? await AddonModForum.instance
.getForumById(discussion.courseid, discussion.forumid, { siteId })
.then(forum => CoreGroups.getActivityAllowedGroups(forum.cmid))
.then(result => result.groups.map((group) => group.id))
: [discussion.groupid];
await Promise.all(groupIds.map(async groupId => {
try {
// First of all upload the attachments (if any).
const itemId = await this.uploadAttachments(forumId, discussion, true, siteId, userId);
// Now try to add the discussion.
const options = CoreUtils.clone(discussion.options || {});
options.attachmentsid = itemId!;
await AddonModForum.addNewDiscussionOnline(
forumId,
discussion.subject,
discussion.message,
options as unknown as AddonModForumAddDiscussionWSOptionsObject,
groupId,
siteId,
);
} catch (error) {
errors.push(error);
}
}));
if (errors.length === groupIds.length) {
// All requests have failed, reject if errors were not returned by WS.
for (const error of errors) {
if (!CoreUtils.isWebServiceError(error)) {
throw error;
}
}
}
// All requests succeeded, some failed or all failed with a WS error.
result.updated = true;
await this.deleteNewDiscussion(forumId, discussion.timecreated, siteId, userId);
if (errors.length === groupIds.length) {
// All requests failed with WS error.
this.addOfflineDataDeletedWarning(result.warnings, discussion.name, errors[0]);
}
});
await Promise.all(promises);
if (result.updated) {
// Data has been sent to server. Now invalidate the WS calls.
const promises = [
AddonModForum.invalidateDiscussionsList(forumId, siteId),
AddonModForum.invalidateCanAddDiscussion(forumId, siteId),
];
await CoreUtils.ignoreErrors(Promise.all(promises));
}
// Sync finished, set sync time.
await CoreUtils.ignoreErrors(this.setSyncTime(syncId, siteId));
return result;
};
return this.addOngoingSync(syncId, syncDiscussions(), siteId);
}
/**
* Synchronize forum offline ratings.
*
* @param cmId Course module to be synced. If not defined, sync all forums.
* @param discussionId Discussion id to be synced. If not defined, sync all discussions.
* @param force Wether to force sync not depending on last execution.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved if sync is successful, rejected otherwise.
*/
async syncRatings(cmId?: number, discussionId?: number, force?: boolean, siteId?: string): Promise<AddonModForumSyncResult> {
siteId = siteId || CoreSites.getCurrentSiteId();
const results =
await CoreRatingSync.syncRatings('mod_forum', 'post', ContextLevel.MODULE, cmId, discussionId, force, siteId);
let updated = false;
const warnings: string[] = [];
const promises: Promise<void>[] = [];
results.forEach((result) => {
if (result.updated.length) {
updated = true;
// Invalidate discussions of updated ratings.
promises.push(AddonModForum.invalidateDiscussionPosts(result.itemSet.itemSetId, undefined, siteId));
}
if (result.warnings.length) {
// Fetch forum to construct the warning message.
promises.push(AddonModForum.getForum(result.itemSet.courseId, result.itemSet.instanceId, { siteId })
.then((forum) => {
result.warnings.forEach((warning) => {
this.addOfflineDataDeletedWarning(warnings, forum.name, warning);
});
return;
}));
}
});
await CoreUtils.allPromises(promises);
return { updated, warnings };
}
/**
* Synchronize all offline discussion replies of a forum.
*
* @param forumId Forum ID to be synced.
* @param userId User the discussions belong to.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved if sync is successful, rejected otherwise.
*/
async syncForumReplies(forumId: number, userId?: number, siteId?: string): Promise<AddonModForumSyncResult> {
// Get offline forum replies to be sent.
const replies = await CoreUtils.ignoreErrors(
AddonModForumOffline.getForumReplies(forumId, siteId, userId),
[] as AddonModForumOfflineReply[],
);
if (!replies.length) {
// Nothing to sync.
return { warnings: [], updated: false };
} else if (!CoreApp.isOnline()) {
// Cannot sync in offline.
return Promise.reject(null);
}
const promises: Record<string, Promise<AddonModForumSyncResult>> = {};
// Do not sync same discussion twice.
replies.forEach((reply) => {
if (typeof promises[reply.discussionid] != 'undefined') {
return;
}
promises[reply.discussionid] = this.syncDiscussionReplies(reply.discussionid, userId, siteId);
});
const results = await Promise.all(Object.values(promises));
return results.reduce((a, b) => ({
warnings: a.warnings.concat(b.warnings),
updated: a.updated || b.updated,
}), { warnings: [], updated: false } as AddonModForumSyncResult);
}
/**
* Sync a forum discussion replies only if a certain time has passed since the last time.
*
* @param discussionId Discussion ID to be synced.
* @param userId User the posts belong to.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the forum discussion is synced or if it doesn't need to be synced.
*/
async syncDiscussionRepliesIfNeeded(
discussionId: number,
userId?: number,
siteId?: string,
): Promise<AddonModForumSyncResult | void> {
siteId = siteId || CoreSites.getCurrentSiteId();
const syncId = this.getDiscussionSyncId(discussionId, userId);
const needed = await this.isSyncNeeded(syncId, siteId);
if (needed) {
return this.syncDiscussionReplies(discussionId, userId, siteId);
}
}
/**
* Synchronize all offline replies from a discussion.
*
* @param discussionId Discussion ID to be synced.
* @param userId User the posts belong to.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved if sync is successful, rejected otherwise.
*/
async syncDiscussionReplies(discussionId: number, userId?: number, siteId?: string): Promise<AddonModForumSyncResult> {
userId = userId || CoreSites.getCurrentSiteUserId();
siteId = siteId || CoreSites.getCurrentSiteId();
const syncId = this.getDiscussionSyncId(discussionId, userId);
if (this.isSyncing(syncId, siteId)) {
// There's already a sync ongoing for this discussion, return the promise.
return this.getOngoingSync(syncId, siteId)!;
}
// Verify that forum isn't blocked.
if (CoreSync.isBlocked(AddonModForumProvider.COMPONENT, syncId, siteId)) {
this.logger.debug('Cannot sync forum discussion ' + discussionId + ' because it is blocked.');
throw new Error(Translate.instant('core.errorsyncblocked', { $a: this.componentTranslate }));
}
this.logger.debug('Try to sync forum discussion ' + discussionId + ' for user ' + userId);
let forumId;
const result: AddonModForumSyncResult = {
warnings: [],
updated: false,
};
// Get offline responses to be sent.
const syncReplies = async () => {
const replies = await CoreUtils.ignoreErrors(
AddonModForumOffline.getDiscussionReplies(discussionId, siteId, userId),
[] as AddonModForumOfflineReply[],
);
if (replies.length !== 0 && !CoreApp.isOnline()) {
throw new Error('Cannot sync in offline');
}
const promises = replies.map(async reply => {
forumId = reply.forumid;
reply.options = reply.options || {};
try {
// First of all upload the attachments (if any).
await this.uploadAttachments(forumId, reply, false, siteId, userId).then((itemId) => {
// Now try to send the reply.
reply.options.attachmentsid = itemId;
return AddonModForum.replyPostOnline(
reply.postid,
reply.subject,
reply.message,
reply.options as unknown as AddonModForumAddDiscussionPostWSOptionsObject,
siteId,
);
});
result.updated = true;
await this.deleteReply(forumId, reply.postid, siteId, userId);
} catch (error) {
if (!CoreUtils.isWebServiceError(error)) {
throw error;
}
// The WebService has thrown an error, this means that responses cannot be submitted. Delete them.
result.updated = true;
await this.deleteReply(forumId, reply.postid, siteId, userId);
// Responses deleted, add a warning.
this.addOfflineDataDeletedWarning(result.warnings, reply.name, error);
}
});
await Promise.all(promises);
// Data has been sent to server. Now invalidate the WS calls.
const invalidationPromises: Promise<void>[] = [];
if (forumId) {
invalidationPromises.push(AddonModForum.invalidateDiscussionsList(forumId, siteId));
}
invalidationPromises.push(AddonModForum.invalidateDiscussionPosts(discussionId, forumId, siteId));
await CoreUtils.ignoreErrors(CoreUtils.allPromises(invalidationPromises));
// Sync finished, set sync time.
await CoreUtils.ignoreErrors(this.setSyncTime(syncId, siteId));
// All done, return the warnings.
return result;
};
return this.addOngoingSync(syncId, syncReplies(), siteId);
}
/**
* Delete a new discussion.
*
* @param forumId Forum ID the discussion belongs to.
* @param timecreated The timecreated of the discussion.
* @param siteId Site ID. If not defined, current site.
* @param userId User the discussion belongs to. If not defined, current user in site.
* @return Promise resolved when deleted.
*/
protected async deleteNewDiscussion(forumId: number, timecreated: number, siteId?: string, userId?: number): Promise<void> {
await Promise.all([
AddonModForumOffline.deleteNewDiscussion(forumId, timecreated, siteId, userId),
CoreUtils.ignoreErrors(
AddonModForumHelper.deleteNewDiscussionStoredFiles(forumId, timecreated, siteId),
),
]);
}
/**
* Delete a new discussion.
*
* @param forumId Forum ID the discussion belongs to.
* @param postId ID of the post being replied.
* @param siteId Site ID. If not defined, current site.
* @param userId User the discussion belongs to. If not defined, current user in site.
* @return Promise resolved when deleted.
*/
protected async deleteReply(forumId: number, postId: number, siteId?: string, userId?: number): Promise<void> {
await Promise.all([
AddonModForumOffline.deleteReply(postId, siteId, userId),
CoreUtils.ignoreErrors(AddonModForumHelper.deleteReplyStoredFiles(forumId, postId, siteId, userId)),
]);
}
/**
* Upload attachments of an offline post/discussion.
*
* @param forumId Forum ID the post belongs to.
* @param post Offline post or discussion.
* @param isDiscussion True if it's a new discussion, false if it's a reply.
* @param siteId Site ID. If not defined, current site.
* @param userId User the reply belongs to. If not defined, current user in site.
* @return Promise resolved with draftid if uploaded, resolved with undefined if nothing to upload.
*/
protected async uploadAttachments(
forumId: number,
post: AddonModForumOfflineDiscussion | AddonModForumOfflineReply,
isDiscussion: boolean,
siteId?: string,
userId?: number,
): Promise<number | undefined> {
const attachments = post && post.options && post.options.attachmentsid;
if (!attachments) {
return;
}
// Has some attachments to sync.
let files = typeof attachments === 'object' && attachments.online ? attachments.online : [];
if (typeof attachments === 'object' && attachments.offline) {
// Has offline files.
try {
const postAttachments = isDiscussion
? await AddonModForumHelper.getNewDiscussionStoredFiles(
forumId,
(post as AddonModForumOfflineDiscussion).timecreated,
siteId,
)
: await AddonModForumHelper.getReplyStoredFiles(
forumId,
(post as AddonModForumOfflineReply).postid,
siteId,
userId,
);
files = files.concat(postAttachments as unknown as []);
} catch (error) {
// Folder not found, no files to add.
}
}
return CoreFileUploader.uploadOrReuploadFiles(files, AddonModForumProvider.COMPONENT, forumId, siteId);
}
/**
* Get the ID of a forum sync.
*
* @param forumId Forum ID.
* @param userId User the responses belong to.. If not defined, current user.
* @return Sync ID.
*/
getForumSyncId(forumId: number, userId?: number): string {
userId = userId || CoreSites.getCurrentSiteUserId();
return 'forum#' + forumId + '#' + userId;
}
/**
* Get the ID of a discussion sync.
*
* @param discussionId Discussion ID.
* @param userId User the responses belong to.. If not defined, current user.
* @return Sync ID.
*/
getDiscussionSyncId(discussionId: number, userId?: number): string {
userId = userId || CoreSites.getCurrentSiteUserId();
return 'discussion#' + discussionId + '#' + userId;
}
}
export const AddonModForumSync = makeSingleton(AddonModForumSyncProvider);
/**
* Result of forum sync.
*/
export type AddonModForumSyncResult = {
updated: boolean;
warnings: string[];
};
/**
* Data passed to AUTO_SYNCED event.
*/
export type AddonModForumAutoSyncData = {
forumId: number;
userId: number;
warnings: string[];
discussionId?: number;
};
/**
* Data passed to MANUAL_SYNCED event.
*/
export type AddonModForumManualSyncData = {
forumId: number;
userId: number;
source: string;
discussionId?: number;
}; | the_stack |
import { Directive, ElementRef, SimpleChanges, OnChanges, isDevMode } from '@angular/core';
import { lyl } from '../parse';
import { StyleRenderer, Style, WithStyles, InputStyle } from '../minimal/renderer-style';
import { ThemeVariables } from './theme-config';
const STYLE_PRIORITY = -0.5;
/**
* @dynamic
*/
@Directive({
selector: `[lyStyle],
[lyColor],
[lyBg],
[lyP], [lyPf], [lyPe], [lyPt], [lyPb], [lyPx], [lyPy],
[lyM], [lyMf], [lyMe], [lyMt], [lyMb], [lyMx], [lyMy],
[lySize],
[lyWidth], [lyMaxWidth], [lyMinWidth],
[lyHeight], [lyMaxHeight], [lyMinHeight],
[lyDisplay],
[lyFlex],
[lyFlexBasis],
[lyFlexDirection],
[lyFlexGrow],
[lyFlexSelf],
[lyFlexShrink],
[lyFlexWrap],
[lyJustifyContent],
[lyJustifyItems],
[lyJustifySelf],
[lyAlignContent],
[lyAlignItems],
[lyOrder]`,
providers: [
StyleRenderer
],
inputs: [
'lyStyle',
'color: lyColor',
'bg: lyBg',
'p: lyP', 'pf: lyPf', 'pe: lyPe', 'pt: lyPt', 'pb: lyPb', 'px: lyPx', 'py: lyPy',
'm: lyM', 'mf: lyMf', 'me: lyMe', 'mt: lyMt', 'mb: lyMb', 'mx: lyMx', 'my: lyMy',
'size: lySize',
'width: lyWidth', 'maxWidth: lyMaxWidth', 'minWidth: lyMinWidth',
'height: lyHeight', 'maxHeight: lyMaxHeight', 'minHeight: lyMinHeight',
'display: lyDisplay',
'flex: lyFlex',
'flexBasis: lyFlexBasis',
'flexDirection: lyFlexDirection',
'flexGrow: lyFlexGrow',
'flexSelf: lyFlexSelf',
'flexShrink: lyFlexShrink',
'flexWrap: lyFlexWrap',
'justifyContent: lyJustifyContent',
'justifyItems: lyJustifyItems',
'justifySelf: lyJustifySelf',
'alignContent: lyAlignContent',
'alignItems: lyAlignItems',
'order: lyOrder'
]
})
export class LyStyle implements WithStyles {
set size(value: string | number | null) {
this.width = value;
this.height = value;
}
constructor(
readonly sRenderer: StyleRenderer
) { }
/** @docs-private */
static readonly и = 'LyStyle';
static readonly $priority = STYLE_PRIORITY;
static readonly with: InputStyle<string | number | null>;
@Style<string | null>(
(value) => (theme: ThemeVariables) => (
lyl `{
color: ${theme.colorOf(value)}
}`
)
) color: string | number | null;
@Style<string | null>(
(value) => (theme: ThemeVariables) => (
lyl `{
background: ${theme.colorOf(value)}
}`
)
) bg: string | number | null;
@Style<string | number | null>(
(value, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
padding: ${to8Px(value)}
}
}`
)
) p: string | number | null;
@Style<string | number | null>(
(val, media) => ({ breakpoints, after }) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
padding-${after}: ${to8Px(val)}
}
}`
)
) pf: string | number | null;
@Style<string | number | null>(
(val, media) => ({ breakpoints, before }) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
padding-${before}: ${to8Px(val)}
}
}`
)
) pe: string | number | null;
@Style<string | number | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
padding-top: ${to8Px(val)}
}
}`
)
) pt: string | number | null;
@Style<string | number | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
padding-bottom: ${to8Px(val)}
}
}`
)
) pb: string | number | null;
@Style<string | number | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
padding: 0 ${to8Px(val)}
}
}`
)
) px: string | number | null;
@Style<string | number | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
padding: ${to8Px(val)} 0
}
}`
)
) py: string | number | null;
@Style<string | number | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
margin: ${to8Px(val)}
}
}`
)
) m: string | number | null;
@Style<string | number | null>(
(val, media) => ({ breakpoints, after }) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
margin-${after}: ${to8Px(val)}
}
}`
)
) mf: string | number | null;
@Style<string | number | null>(
(val, media) => ({ breakpoints, before }) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
margin-${before}: ${to8Px(val)}
}
}`
)
) me: string | number | null;
@Style<string | number | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
margin-top: ${to8Px(val)}
}
}`
)
) mt: string | number | null;
@Style<string | number | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
margin-bottom: ${to8Px(val)}
}
}`
)
) mb: string | number | null;
@Style<string | number | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
margin: 0 ${to8Px(val)}
}
}`
)
) mx: string | number | null;
@Style<string | number | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
margin: ${to8Px(val)} 0
}
}`
)
) my: string | number | null;
@Style<string | number | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
width: ${transform(val)}
}
}`
)
) width: string | number | null;
@Style<string | number | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
max-width: ${transform(val)}
}
}`
)
) maxWidth: string | number | null;
@Style<string | number | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
min-width: ${transform(val)}
}
}`
)
) minWidth: string | number | null;
@Style<string | number | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
height: ${transform(val)}
}
}`
)
) height: string | number | null;
@Style<string | number | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
max-height: ${transform(val)}
}
}`
)
) maxHeight: string | number | null;
@Style<string | number | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
min-height: ${transform(val)}
}
}`
)
) minHeight: string | number | null;
@Style<string | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
display: ${val}
}
}`
)
) display: string | null;
// Flexbox
@Style<string | number | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
flex: ${val}
}
}`
)
) flex: string | number | null;
@Style<string | number | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
flex-basis: ${val}
}
}`
)
) flexBasis: string | number | null;
@Style<string | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
flex-direction: ${val}
}
}`
)
) flexDirection: string | null;
@Style<string | number | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
flex-grow: ${val}
}
}`
)
) flexGrow: string | number | null;
@Style<string | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
flex-self: ${val}
}
}`
)
) flexSelf: string | null;
@Style<string | number | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
flex-shrink: ${val}
}
}`
)
) flexShrink: string | number | null;
@Style<string | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
flex-wrap: ${val}
}
}`
)
) flexWrap: string | null;
@Style<string | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
justify-content: ${val}
}
}`
)
) justifyContent: string | null;
@Style<string | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
justify-items: ${val}
}
}`
)
) justifyItems: string | null;
@Style<string | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
justify-self: ${val}
}
}`
)
) justifySelf: string | null;
@Style<string | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
align-content: ${val}
}
}`
)
) alignContent: string | null;
@Style<string | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
align-items: ${val}
}
}`
)
) alignItems: string | null;
@Style<string | number | null>(
(val, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && breakpoints[ media ]) || 'all'} {
order: ${val}
}
}`
)
) order: string | number | null;
@Style<string | number | null>(
(value, media) => ({ breakpoints }: ThemeVariables) => (
lyl`{
@media ${(media && (breakpoints[ media ] || media)) || 'all'} {
${value}
}
}`
)
)
lyStyle: string | null;
}
/**
* @dynamic
* @deprecated
* Spacing
* [p], [pf], [pe], [pt], [pb], [px], [py],
* [m], [mf], [me], [mt], [mb], [mx], [my],
* Sizing
* [size],
* [width], [maxWidth], [minWidth],
* [height], [maxHeight], [minHeight],
* Others
* [lyStyle]
*/
@Directive({
selector: `
[p], [pf], [pe], [pt], [pb], [px], [py],
[m], [mf], [me], [mt], [mb], [mx], [my],
[size]:not([ly-button]),
[width]:not(svg):not(canvas):not(embed):not(iframe):not(img):not(input):not(object):not(video),
[maxWidth], [minWidth],
[height]:not(svg):not(canvas):not(embed):not(iframe):not(img):not(input):not(object):not(video),
[maxHeight], [minHeight],
[display],
[flex],
[flexBasis],
[flexDirection],
[flexGrow],
[flexSelf],
[flexShrink],
[flexWrap],
[justifyContent],
[justifyItems],
[justifySelf],
[alignContent],
[alignItems],
[order]`,
providers: [
StyleRenderer
],
inputs: [
'p', 'pf', 'pe', 'pt', 'pb', 'px', 'py',
'm', 'mf', 'me', 'mt', 'mb', 'mx', 'my',
'size',
'width', 'maxWidth', 'minWidth',
'height', 'maxHeight', 'minHeight',
'display',
'flex',
'flexBasis',
'flexDirection',
'flexGrow',
'flexSelf',
'flexShrink',
'flexWrap',
'justifyContent',
'justifyItems',
'justifySelf',
'alignContent',
'alignItems',
'order',
]
})
export class LyStyleDeprecated extends LyStyle implements OnChanges {
constructor(
sRenderer: StyleRenderer,
private _el: ElementRef
) {
super(sRenderer);
}
ngOnChanges(changes: SimpleChanges) {
if (isDevMode()) {
for (const key in changes) {
if (changes.hasOwnProperty(key)) {
const message = `[${key}] is deprecated, use [ly${key.charAt(0).toUpperCase() + key.slice(1)}] instead.`;
console.warn({
message,
element: this._el.nativeElement
});
}
}
}
}
}
/**
* Convert to px if the value is a number, otherwise leave it as is
* @docs-private
*/
function to8Px(val: number | string) {
return typeof val === 'number'
? `${val * 8}px`
: val.includes(' ')
? val.split(' ').map(_ => strTo8Px(_)).join(' ')
: strTo8Px(val);
}
function strTo8Px(val: string) {
const num = +val;
return isNaN(num) ? val : `${num * 8}px`;
}
function strToPx(val: string) {
const num = +val;
return isNaN(num) ? val : `${num}px`;
}
function transform(value: number | string) {
return value <= 1
? `${value as number * 100}%`
: typeof value === 'number'
? `${value}px`
: value.includes(' ')
? value.split(' ').map(_ => strToPx(_)).join(' ')
: strToPx(value);
} | the_stack |
import {
isServer,
onStoreChange,
payLaterOption as defaultPayLaterOption,
removeOnStoreChange,
standardShipping as defaultStandardShipping,
TOrder,
TOrderInput,
TOrderPaymentSession,
TPaymentOption,
TShippingOption,
TUser,
} from '@cromwell/core';
import { getCStore, getRestApiClient, useUserInfo } from '@cromwell/core-frontend';
import queryString from 'query-string';
import React, { useEffect, useRef, useState } from 'react';
import { notifier as baseNotifier } from '../../helpers/notifier';
import { moduleState } from '../../helpers/state';
import { CheckoutProps } from './Checkout';
import { DefaultCheckoutFields, getDefaultCheckoutFields } from './DefaultElements';
/** @internal */
export type PaymentStatus = 'cancelled' | 'success';
/** @internal */
export const usuCheckoutActions = (config: {
checkoutProps: CheckoutProps;
rootRef: React.MutableRefObject<HTMLDivElement | null>;
}) => {
const cstore = getCStore();
const { notifier = baseNotifier, notifierOptions = {},
fields = getDefaultCheckoutFields(config.checkoutProps),
text, getPaymentOptions, changeErrorText } = config.checkoutProps;
const [isLoading, setIsLoading] = useState(false);
const [isAwaitingPayment, setIsAwaitingPayment] = useState(false);
const userInfo = useUserInfo();
const [canShowValidation, setCanShowValidation] = useState(false);
const [placedOrder, setPlacedOrder] = useState<TOrder | null>(null);
const [paymentSession, setPaymentSession] = useState<TOrderPaymentSession | null | undefined>(null);
const [additionalPaymentOptions, setAdditionalPaymentOptions] = useState<TPaymentOption[] | null>(null);
const standardShipping: TShippingOption = {
key: defaultStandardShipping.key,
name: text?.standardShipping ?? defaultStandardShipping.name,
}
const payLaterOption: TPaymentOption = {
key: defaultPayLaterOption.key,
name: text?.payLater ?? defaultPayLaterOption.name,
}
const [order, setOrder] = useState<TOrderInput>({
customerEmail: userInfo?.email,
customerName: userInfo?.fullName,
customerPhone: userInfo?.phone,
customerAddress: userInfo?.address,
paymentMethod: undefined,
shippingMethod: standardShipping.key,
});
const coupons = useRef<Record<string, {
value: string;
applied?: boolean | null;
}>>({});
useEffect(() => {
if (!isServer()) {
// For pop-up payment window after transaction end and redirect with query param.
// ***
// When we call `client.createPaymentSession` we pass `successUrl` and `cancelUrl`.
// Customer will be redirected on these URLs when transaction is finished.
// In this case we point `successUrl` to the same (this) page with a query param;
// So if URL has params, then we can communicate with parent page (where transaction started)
// and tell transaction status:
const parsedUrl = queryString.parseUrl(window.location.href);
const paymentStatus = parsedUrl.query?.paymentStatus as PaymentStatus;
if (paymentStatus === 'success') {
(window.opener as any)?.paySuccess();
window.close();
}
if (paymentStatus === 'cancelled') {
(window.opener as any)?.payCancel();
window.close();
}
}
const onUserChange = (value: TUser | undefined) => {
if (value) setOrder(prev => ({
...prev,
customerEmail: value.email,
customerName: value.fullName,
customerPhone: value.phone,
customerAddress: value.address,
}));
}
checkout.getOrderTotal();
const cartUpdateCbId = cstore.onCartUpdate(checkout.getOrderTotal);
const userInfoCbId = onStoreChange('userInfo', onUserChange);
const currencyCbId = onStoreChange('currency', checkout.getOrderTotal);
return () => {
removeOnStoreChange('userInfo', userInfoCbId);
removeOnStoreChange('currency', currencyCbId);
cstore.removeOnCartUpdate(cartUpdateCbId);
moduleState.setPaymentSession(null);
}
}, []);
const checkout = {
order,
setOrder,
isLoading,
isAwaitingPayment,
placedOrder,
paymentSession,
coupons: coupons.current,
canShowValidation,
additionalPaymentOptions,
payLaterOption,
standardShipping,
setCoupons: (newCoupons) => {
coupons.current = newCoupons;
},
getOrderTotal: async () => {
setIsLoading(true);
try {
const successUrl = queryString.parseUrl(window.location.href);
successUrl.query.paymentStatus = 'success';
const cancelUrl = queryString.parseUrl(window.location.href);
cancelUrl.query.paymentStatus = 'cancelled';
const session = await getRestApiClient().createPaymentSession({
cart: JSON.stringify(cstore.getCart()),
currency: cstore.getActiveCurrencyTag(),
fromUrl: window.location.origin,
successUrl: queryString.stringifyUrl(successUrl),
cancelUrl: queryString.stringifyUrl(cancelUrl),
couponCodes: Object.values(coupons.current).map(c => c.value).filter(Boolean),
shippingMethod: order.shippingMethod,
paymentSessionId: paymentSession?.paymentSessionId,
})?.catch(e => console.error(e)) || null;
for (const couponId of Object.keys(coupons.current)) {
if (session?.appliedCoupons?.includes(coupons.current[couponId].value)) {
coupons.current[couponId].applied = true;
} else {
coupons.current[couponId].applied = false;
}
}
setPaymentSession(session);
moduleState.setPaymentSession(session);
config.checkoutProps.onGetOrderTotal?.(session);
if (getPaymentOptions) {
try {
const additional = await getPaymentOptions(session);
if (additional) setAdditionalPaymentOptions(additional.filter(Boolean));
} catch (error) {
console.error(error);
}
}
} catch (error) {
console.error(error);
}
setIsLoading(false);
},
placeOrder: async () => {
if (!canShowValidation) setCanShowValidation(true);
if (!checkout.isOrderValid()) {
notifier?.warning?.(text?.fillOrderInformation ?? 'Please fill order information',
{ ...notifierOptions, });
config.rootRef?.current?.scrollIntoView?.({ behavior: 'smooth' });
return;
}
setIsLoading(true);
const placedOrder = await getRestApiClient()?.placeOrder(Object.assign({}, order, {
userId: userInfo?.id,
cart: JSON.stringify(cstore.getCart()),
fromUrl: window.location.origin,
currency: cstore.getActiveCurrencyTag(),
couponCodes: Object.values(coupons.current).map(c => c.value).filter(Boolean),
})).catch(e => {
console.error(e);
notifier?.error?.((text?.failedCreateOrder ?? 'Failed to place order.') + ' ' +
(changeErrorText ?? ((m) => m))(e.message),
{ ...notifierOptions, });
}) || null;
setIsLoading(false);
config.checkoutProps.onPlaceOrder?.(placedOrder);
if (placedOrder) {
setPlacedOrder(placedOrder);
moduleState.setPaymentSession(null);
cstore.clearCart();
}
},
changeOrder: (key: keyof TOrder, value: any) => {
setOrder(prevState => {
return {
...prevState,
[key]: value
}
})
},
getFieldValue: (fieldKey): string | null => {
const field = fields.find(f => f.key === fieldKey);
if (!field) return null;
const isDefault = Object.values<string>(DefaultCheckoutFields).includes(fieldKey);
let value;
if (!isDefault) {
let address;
try {
address = JSON.parse(order.customerAddress ?? '{}')
} catch (e) { }
if (address) {
value = address[field.key];
}
} else if (field.meta) {
value = order.customMeta?.[field.key];
} else {
value = order[field.key];
}
return value ?? null;
},
setFieldValue: (fieldKey, newValue: string) => {
const field = fields.find(f => f.key === fieldKey);
if (!field) return null;
const isDefault = Object.values<string>(DefaultCheckoutFields).includes(fieldKey);
if (isDefault) {
checkout.changeOrder(field.key as any, newValue);
} else if (field.meta) {
checkout.changeOrder('customMeta', {
...order.customMeta,
[field.key]: newValue,
});
} else {
let address;
try {
address = JSON.parse(order.customerAddress ?? '{}');
} catch (e) { }
if (typeof address !== 'object') address = {};
address[field.key] = newValue;
checkout.changeOrder('customerAddress', JSON.stringify(address));
}
},
isFieldValid: (fieldKey): {
valid: boolean;
message?: string;
} => {
const field = fields.find(f => f.key === fieldKey);
if (!field) return {
valid: false,
message: 'Wrong field config'
}
const value = checkout.getFieldValue(fieldKey);
if (field.required && !value) return {
valid: false,
message: text?.fieldIsRequired ?? 'This field is required',
};
if (field.validate) return field.validate(value);
return {
valid: true
}
},
isOrderValid: () => {
for (const field of fields) {
if (!checkout.isFieldValid(field.key).valid) return false;
}
return true;
},
pay: async () => {
if (!canShowValidation) setCanShowValidation(true);
if (!checkout.isOrderValid()) {
notifier?.warning?.(text?.fillOrderInformation ?? 'Please fill order information',
{ ...notifierOptions, });
config.rootRef?.current?.scrollIntoView?.({ behavior: 'smooth' });
return;
}
if (!paymentSession?.paymentOptions?.length) {
notifier?.warning?.(text?.noPaymentsAvailable ?? 'No payment options available',
{ ...notifierOptions, });
return;
}
if (!order?.paymentMethod) {
notifier?.warning?.(text?.choosePaymentMethod ?? 'Please choose a payment method',
{ ...notifierOptions, });
return;
}
const paymentMethod = paymentSession.paymentOptions
.find(option => option.name === order.paymentMethod);
if (!paymentMethod?.link) {
console.error('Cannot proceed payment. paymentMethod.link is not set: ' + paymentMethod);
notifier?.warning?.(text?.somethingWrongWithPayment ??
'Something is wrong with payment method', { ...notifierOptions, });
return;
}
setIsAwaitingPayment(true);
const popup = window.open(paymentMethod.link, 'payment',
`scrollbars=no,resizable=no,status=no,location=no,toolbar=no,menubar=no,width=0,height=0,left=-1000,top=-1000`);
const success = await new Promise<boolean>(done => {
(window as any).paySuccess = () => done(true);
(window as any).payCancel = () => done(false);
const timer = setInterval(function () {
if (popup?.closed) {
clearInterval(timer);
done(false);
}
}, 1000);
});
setIsAwaitingPayment(false);
if (success) {
await checkout.placeOrder();
}
}
}
return checkout;
} | the_stack |
import {
Component,
OnInit,
ViewChild,
AfterContentInit,
HostListener
} from '@angular/core'
import { UtilitiesService } from './services/utilities.service'
import { UIService } from './services/ui.service'
import { FadeInOutAnimation, FromTopAnimation } from '@eqmac/components'
import { MatDialog, MatDialogRef } from '@angular/material/dialog'
import { TransitionService } from './services/transitions.service'
import { AnalyticsService } from './services/analytics.service'
import { ApplicationService } from './services/app.service'
import { SettingsService, IconMode } from './sections/settings/settings.service'
import { ToastService } from './services/toast.service'
import { OptionsDialogComponent } from './components/options-dialog/options-dialog.component'
import { Option, Options } from './components/options/options.component'
import { HeaderComponent } from './sections/header/header.component'
import { VolumeBoosterBalanceComponent } from './sections/volume/booster-balance/volume-booster-balance.component'
import { EqualizersComponent } from './sections/effects/equalizers/equalizers.component'
import { OutputsComponent } from './sections/outputs/outputs.component'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: [ './app.component.scss' ],
animations: [ FadeInOutAnimation, FromTopAnimation ]
})
export class AppComponent implements OnInit, AfterContentInit {
@ViewChild('container', { static: true }) container
@ViewChild('header', { static: true }) header: HeaderComponent
@ViewChild('volumeBoosterBalance', { static: false }) volumeBoosterBalance: VolumeBoosterBalanceComponent
@ViewChild('equalizers', { static: false }) equalizers: EqualizersComponent
@ViewChild('outputs', { static: false }) outputs: OutputsComponent
loaded = false
animationDuration = 500
animationFps = 30
showDropdownSections = {
settings: false,
help: false
}
private containerWidth = 400
private containerHeight = 400
get containerStyle () {
const style: any = {}
style.width = `${this.containerWidth / this.ui.scale}px`
style.height = `${this.containerHeight / this.ui.scale}px`
style.transform = `scale(${this.ui.scale})`
return style
}
constructor (
public utils: UtilitiesService,
public ui: UIService,
public dialog: MatDialog,
public transitions: TransitionService,
public analytics: AnalyticsService,
public app: ApplicationService,
public settings: SettingsService,
public toast: ToastService
) {
this.app.ref = this
}
get minHeight () {
const divider = 3
const {
volumeFeatureEnabled, balanceFeatureEnabled,
equalizersFeatureEnabled,
outputFeatureEnabled
} = this.ui.settings
let minHeight = this.header.height + divider +
((volumeFeatureEnabled || balanceFeatureEnabled) ? (this.volumeBoosterBalance.height + divider) : 0) +
(equalizersFeatureEnabled ? (this.equalizers.height + divider) : 0) +
(outputFeatureEnabled ? this.outputs.height : 0)
const dropdownSection = document.getElementById('dropdown-section')
if (dropdownSection) {
const dropdownHeight = dropdownSection.offsetHeight + this.header.height + divider
if (dropdownHeight > minHeight) {
minHeight = dropdownHeight
}
}
return minHeight
}
get minWidth () {
return 400
}
get maxHeight () {
const divider = 3
const {
volumeFeatureEnabled, balanceFeatureEnabled,
equalizersFeatureEnabled,
outputFeatureEnabled
} = this.ui.settings
let maxHeight = this.header.height + divider +
((volumeFeatureEnabled || balanceFeatureEnabled) ? (this.volumeBoosterBalance.height + divider) : 0) +
(equalizersFeatureEnabled ? (this.equalizers.maxHeight + divider) : 0) +
(outputFeatureEnabled ? this.outputs.height : 0)
const dropdownSection = document.getElementById('dropdown-section')
if (dropdownSection) {
const dropdownHeight = dropdownSection.offsetHeight + this.header.height + divider
if (dropdownHeight > maxHeight) {
maxHeight = dropdownHeight
}
}
return maxHeight
}
async ngOnInit () {
await this.sync()
await this.fixUIMode()
this.startDimensionsSync()
await this.setupPrivacy()
}
async setupPrivacy () {
const [ uiSettings ] = await Promise.all([
this.ui.getSettings()
])
if (typeof uiSettings.privacyFormSeen !== 'boolean') {
let doCollectTelemetry = uiSettings.doCollectTelemetry ?? false
let doCollectCrashReports = await this.settings.getDoCollectCrashReports()
let saving = false
const doCollectTelemetryOption: Option = {
type: 'checkbox',
label: 'Send Anonymous Analytics data',
tooltip: `
eqMac would collect anonymous Telemetry analytics data like:
• macOS Version
• App and UI Version
• Country (IP Addresses are anonymized)
This helps us understand distribution of our users.
`,
tooltipAsComponent: true,
value: doCollectTelemetry,
isEnabled: () => !saving,
toggled: doCollect => {
doCollectTelemetry = doCollect
}
}
const doCollectCrashReportsOption: Option = {
type: 'checkbox',
label: 'Send Anonymous Crash reports',
tooltip: `
eqMac would send anonymized crash reports
back to the developer in case eqMac crashes.
This helps us understand improve eqMac
and make it a more stable product.
`,
tooltipAsComponent: true,
value: doCollectCrashReports,
isEnabled: () => !saving,
toggled: doCollect => {
doCollectCrashReports = doCollect
}
}
const privacyDialog: MatDialogRef<OptionsDialogComponent> = this.dialog.open(OptionsDialogComponent, {
hasBackdrop: true,
disableClose: true,
data: {
options: [
[ { type: 'label', label: 'Privacy' } ],
[ {
type: 'label', label: `eqMac respects it's user's privacy
and is giving you a choice what data you wish to share with the developer.
This data would help us improve and grow the product.`
} ],
[ doCollectTelemetryOption ],
[ doCollectCrashReportsOption ],
[
{
type: 'button',
label: 'Save',
isEnabled: () => !saving,
action: () => privacyDialog.close()
},
{
type: 'button',
label: 'Accept all',
isEnabled: () => !saving,
action: async () => {
doCollectCrashReports = true
doCollectTelemetry = true
doCollectCrashReportsOption.value = true
doCollectTelemetryOption.value = true
saving = true
await this.utils.delay(200)
privacyDialog.close()
}
}
]
] as Options
}
})
await privacyDialog.afterClosed().toPromise()
await Promise.all([
this.ui.setSettings({
privacyFormSeen: true,
doCollectTelemetry
}),
this.settings.setDoCollectCrashReports({
doCollectCrashReports
})
])
}
if (uiSettings.doCollectTelemetry) {
await this.analytics.init()
}
}
async ngAfterContentInit () {
await this.utils.delay(this.animationDuration)
this.loaded = true
await this.utils.delay(1000)
this.ui.loaded()
}
async sync () {
await Promise.all([
this.getTransitionSettings()
])
}
async startDimensionsSync () {
setInterval(() => {
this.syncMinHeight()
this.syncMaxHeight()
}, 1000)
}
private previousMinHeight: number
async syncMinHeight () {
if (!this.previousMinHeight) {
this.previousMinHeight = this.minHeight
await this.ui.setMinHeight({ minHeight: this.minHeight })
return
}
const diff = this.minHeight - this.previousMinHeight
this.previousMinHeight = this.minHeight
if (diff !== 0) {
this.ui.onMinHeightChanged.emit()
await this.ui.setMinHeight({ minHeight: this.minHeight })
}
if (diff < 0) {
this.ui.changeHeight({ diff })
}
}
private previousMaxHeight: number
async syncMaxHeight () {
if (!this.previousMaxHeight) {
this.previousMaxHeight = this.maxHeight
await this.ui.setMaxHeight({ maxHeight: this.maxHeight })
return
}
const diff = this.maxHeight - this.previousMaxHeight
this.previousMaxHeight = this.maxHeight
await this.ui.setMaxHeight({ maxHeight: this.maxHeight })
if (diff > 0) {
// this.ui.changeHeight({ diff })
}
}
private windowResizeHandlerTimer: number
@HostListener('window:resize')
handleWindowResize () {
if (this.windowResizeHandlerTimer) {
clearTimeout(this.windowResizeHandlerTimer)
}
this.windowResizeHandlerTimer = setTimeout(async () => {
const [ height, width ] = await Promise.all([
this.ui.getHeight(),
this.ui.getWidth()
])
this.containerHeight = height
this.containerWidth = width
setTimeout(() => {
this.ui.dimensionsChanged.emit()
}, 100)
}, 100) as any
}
async getTransitionSettings () {
const settings = await this.transitions.getSettings()
this.animationDuration = settings.duration
this.animationFps = settings.fps
}
toggleDropdownSection (section: string) {
for (const key in this.showDropdownSections) {
this.showDropdownSections[key] = key === section ? !this.showDropdownSections[key] : false
}
}
openDropdownSection (section: string) {
for (const key in this.showDropdownSections) {
this.showDropdownSections[key] = key === section
}
}
async fixUIMode () {
const [ mode, iconMode ] = await Promise.all([
this.ui.getMode(),
this.settings.getIconMode()
])
if (mode === 'popover' && iconMode === IconMode.dock) {
await this.ui.setMode('window')
}
}
closeDropdownSection (section: string, event?: MouseEvent) {
// if (event && event.target && ['backdrop', 'mat-dialog'].some(e => event.target.className.includes(e))) return
if (this.dialog.openDialogs.length > 0) return
if (section in this.showDropdownSections) {
this.showDropdownSections[section] = false
}
}
} | the_stack |
import type { BuildPlatformContext, BuildPlatformEvents } from '@jovotech/cli-command-build';
import {
ANSWER_CANCEL,
ANSWER_OVERWRITE,
deleteFolderRecursive,
getResolvedLocales,
JovoCliError,
Log,
mergeArrayCustomizer,
OK_HAND,
PluginHook,
printHighlight,
promptOverwriteReverseBuild,
REVERSE_ARROWS,
STATION,
Task,
wait,
} from '@jovotech/cli-core';
import { JovoModelData, JovoModelDataV3, NativeFileInformation } from '@jovotech/model';
import { JovoModelLex, LexModelFile } from '@jovotech/model-lex';
import { existsSync, mkdirSync, writeFileSync } from 'fs';
import _get from 'lodash.get';
import _mergeWith from 'lodash.mergewith';
import _pick from 'lodash.pick';
import { join as joinPaths } from 'path';
import { LexCliConfig } from '../interfaces';
import { getLexLocale, SupportedLocales, SupportedLocalesType } from '../utilities';
export class BuildHook extends PluginHook<BuildPlatformEvents> {
$context!: BuildPlatformContext;
install(): void {
this.middlewareCollection = {
'before.build:platform': [
this.checkForPlatform.bind(this),
this.checkForCleanBuild.bind(this),
this.validateLocales.bind(this),
this.validateModels.bind(this),
],
'build:platform': [this.buildLexModel.bind(this)],
'build:platform.reverse': [this.buildReverse.bind(this)],
};
}
/**
* Checks if the currently selected platform matches this CLI plugin.
* @param context - Context containing information after flags and args have been parsed by the CLI.
*/
checkForPlatform(): void {
// Check if this plugin should be used or not.
if (!this.$context.platforms.includes(this.$plugin.id)) {
this.uninstall();
}
}
/**
* Checks, if --clean has been set and deletes the platform folder accordingly.
*/
checkForCleanBuild(): void {
// If --clean has been set, delete the respective platform folders before building.
if (this.$context.flags.clean) {
deleteFolderRecursive(this.$plugin.platformPath);
}
}
/**
* Checks if any provided locale is not supported, thus invalid.
*/
validateLocales(): void {
const locales: SupportedLocalesType[] = this.$context.locales.reduce(
(locales: string[], locale: string) => {
locales.push(...getResolvedLocales(locale, SupportedLocales, this.$plugin.config.locales));
return locales;
},
[],
) as SupportedLocalesType[];
if (locales.length > 1) {
throw new JovoCliError({
message: `Amazon Lex does not support multiple language models (${locales.join(',')}).`,
module: this.$plugin.constructor.name,
hint: 'Please provide a locale by using the flag "--locale" or in your project configuration.',
});
}
const locale: SupportedLocalesType = locales.pop()!;
if (!SupportedLocales.includes(locale)) {
throw new JovoCliError({
message: `Locale ${printHighlight(locale)} is not supported by Lex.`,
module: this.$plugin.constructor.name,
learnMore:
'For more information on multiple language support: https://docs.aws.amazon.com/lex/latest/dg/how-it-works-language.html',
});
}
}
/**
* Validates Jovo models with platform-specific validators.
*/
async validateModels(): Promise<void> {
// Validate Jovo model.
const validationTask: Task = new Task(`${OK_HAND} Validating Lex model files`);
for (const locale of this.$context.locales) {
const localeTask = new Task(locale, async () => {
const model: JovoModelData | JovoModelDataV3 = await this.$cli.project!.getModel(locale);
await this.$cli.project!.validateModel(locale, model, JovoModelLex.getValidator(model));
await wait(500);
});
validationTask.add(localeTask);
}
await validationTask.run();
}
async buildLexModel(): Promise<void> {
const platformPath: string = this.$plugin.platformPath;
if (!existsSync(platformPath)) {
mkdirSync(platformPath);
}
const buildTask: Task = new Task(`${STATION} Building Lex`);
for (const modelLocale of this.$context.locales) {
const resolvedLocales: string[] = getResolvedLocales(
modelLocale,
SupportedLocales,
this.$plugin.config.locales,
);
const resolvedLocalesOutput: string = resolvedLocales.join(', ');
// If the model locale is resolved to different locales, provide task details, i.e. "en (en-US, en-CA)"".
const taskDetails: string =
resolvedLocalesOutput === modelLocale ? '' : `(${resolvedLocalesOutput})`;
const localeTask: Task = new Task(`${modelLocale} ${taskDetails}`, async () => {
for (const resolvedLocale of resolvedLocales) {
const model: JovoModelData = (await this.getJovoModel(modelLocale)) as JovoModelData;
const jovoModel: JovoModelLex = new JovoModelLex(model, resolvedLocale);
// eslint-disable-next-line
const lexModelFiles: NativeFileInformation[] =
jovoModel.exportNative() as NativeFileInformation[];
if (!lexModelFiles || !lexModelFiles.length) {
throw new JovoCliError({
message: `Could not build Lex files for locale "${resolvedLocale}"!`,
module: this.$plugin.constructor.name,
});
}
for (const file of lexModelFiles) {
// Set configuration-specific properties.
const resourceProperties: string[] = [
'name',
'version',
'childDirected',
'abortStatement',
'clarificationPrompt',
'voiceId',
'description',
'idleSessionTTLInSeconds',
'detectSentiment',
];
const configResource: Partial<LexCliConfig> = _pick(
this.$plugin.config,
resourceProperties,
);
// Additionally merge already existing model files.
const lexModel: LexModelFile | undefined = this.$plugin.getLexModel(resolvedLocale);
file.content.resource = _mergeWith(
lexModel?.resource,
file.content.resource,
configResource,
);
writeFileSync(
joinPaths(platformPath, ...file.path),
JSON.stringify(file.content, null, 2),
);
}
}
});
buildTask.add(localeTask);
}
await buildTask.run();
}
/**
* Builds Jovo model files from platform-specific files.
*/
async buildReverse(): Promise<void> {
// Since platform can be prompted for, check if this plugin should actually be executed again.
if (!this.$context.platforms.includes(this.$plugin.id)) {
return;
}
// Get locale to reverse build from.
// If a locale is specified, check if it's available to reverse build from.
const platformLocale: string = getLexLocale(
this.$plugin.platformPath,
this.$context.locales,
this.$plugin.config.locales,
);
if (this.$context.flags.locale && this.$context.flags.locale[0] !== platformLocale) {
throw new JovoCliError({
message: `Could not find platform models for locale: ${printHighlight(
this.$context.flags.locale[0],
)}`,
module: this.$plugin.constructor.name,
hint: `Available locales include: ${platformLocale}`,
});
}
// Try to resolve the locale according to the locale map provided in this.$plugin.config.locales.
let modelLocale: string = platformLocale;
if (this.$plugin.config.locales) {
for (const locale in this.$plugin.config.locales) {
const resolvedLocales: string[] = getResolvedLocales(
locale,
SupportedLocales,
this.$plugin.config.locales,
);
if (resolvedLocales.includes(platformLocale)) {
modelLocale = locale;
break;
}
}
}
const reverseBuildTask: Task = new Task(`${REVERSE_ARROWS} Reversing model files`);
// If Jovo model files for the current locales exist, ask whether to back them up or not.
if (this.$cli.project!.hasModelFiles([modelLocale]) && !this.$context.flags.clean) {
const answer = await promptOverwriteReverseBuild();
if (answer.overwrite === ANSWER_CANCEL) {
return;
}
if (answer.overwrite === ANSWER_OVERWRITE) {
// Backup old files.
const backupTask: Task = new Task('Creating backups', async () => {
const localeTask: Task = new Task(modelLocale, () => {
this.$cli.project!.backupModel(modelLocale);
Log.spacer();
});
await localeTask.run();
});
reverseBuildTask.add(backupTask);
}
}
const taskDetails: string = platformLocale === modelLocale ? '' : `(${modelLocale})`;
const localeTask: Task = new Task(`${platformLocale} ${taskDetails}`, async () => {
const lexModelFiles: NativeFileInformation[] = [
{
path: [],
content: this.getLexModel(platformLocale),
},
];
const jovoModel = new JovoModelLex();
jovoModel.importNative(lexModelFiles, modelLocale);
const nativeData: JovoModelData | JovoModelDataV3 | undefined = jovoModel.exportJovoModel();
if (!nativeData) {
throw new JovoCliError({
message: 'Something went wrong while exporting your Jovo model.',
module: this.$plugin.constructor.name,
});
}
this.$cli.project!.saveModel(nativeData, modelLocale);
await wait(500);
});
reverseBuildTask.add(localeTask);
await reverseBuildTask.run();
}
/**
* Loads a Jovo model specified by a locale and merges it with plugin-specific models.
* @param locale - The locale that specifies which model to load.
*/
async getJovoModel(locale: string): Promise<JovoModelData | JovoModelDataV3> {
const model: JovoModelData | JovoModelDataV3 = await this.$cli.project!.getModel(locale);
// Merge model with configured language model in project.js.
_mergeWith(
model,
this.$cli.project!.config.getParameter(`languageModel.${locale}`) || {},
mergeArrayCustomizer,
);
// Merge model with configured, platform-specific language model in project.js.
_mergeWith(
model,
_get(this.$plugin.config, `options.languageModel.${locale}`, {}),
mergeArrayCustomizer,
);
return model;
}
/**
* Loads a Lex model, specified by a locale.
* @param locale - Locale of the Lex model.
*/
getLexModel(locale: string): JovoModelData | JovoModelDataV3 {
return require(joinPaths(this.$plugin.platformPath, locale));
}
} | the_stack |
export default () => [
{
name: "node-exporter.rules",
rules: [
{
expr: 'count without (cpu) (\n count without (mode) (\n node_cpu_seconds_total{job="node-exporter"}\n )\n)\n',
record: "instance:node_num_cpu:sum"
},
{
expr: '1 - avg without (cpu, mode) (\n rate(node_cpu_seconds_total{job="node-exporter", mode="idle"}[1m])\n)\n',
record: "instance:node_cpu_utilisation:rate1m"
},
{
expr: '(\n node_load1{job="node-exporter"}\n/\n instance:node_num_cpu:sum{job="node-exporter"}\n)\n',
record: "instance:node_load1_per_cpu:ratio"
},
{
expr: '1 - (\n node_memory_MemAvailable_bytes{job="node-exporter"}\n/\n node_memory_MemTotal_bytes{job="node-exporter"}\n)\n',
record: "instance:node_memory_utilisation:ratio"
},
{
expr: '(\n rate(node_vmstat_pgpgin{job="node-exporter"}[1m])\n+\n rate(node_vmstat_pgpgout{job="node-exporter"}[1m])\n)\n',
record: "instance:node_memory_swap_io_pages:rate1m"
},
{
expr: 'rate(node_disk_io_time_seconds_total{job="node-exporter", device=~"nvme.+|rbd.+|sd.+|vd.+|xvd.+|dm-.+"}[1m])\n',
record: "instance_device:node_disk_io_time_seconds:rate1m"
},
{
expr: 'rate(node_disk_io_time_weighted_seconds_total{job="node-exporter", device=~"nvme.+|rbd.+|sd.+|vd.+|xvd.+|dm-.+"}[1m])\n',
record: "instance_device:node_disk_io_time_weighted_seconds:rate1m"
},
{
expr: 'sum without (device) (\n rate(node_network_receive_bytes_total{job="node-exporter", device!="lo"}[1m])\n)\n',
record: "instance:node_network_receive_bytes_excluding_lo:rate1m"
},
{
expr: 'sum without (device) (\n rate(node_network_transmit_bytes_total{job="node-exporter", device!="lo"}[1m])\n)\n',
record: "instance:node_network_transmit_bytes_excluding_lo:rate1m"
},
{
expr: 'sum without (device) (\n rate(node_network_receive_drop_total{job="node-exporter", device!="lo"}[1m])\n)\n',
record: "instance:node_network_receive_drop_excluding_lo:rate1m"
},
{
expr: 'sum without (device) (\n rate(node_network_transmit_drop_total{job="node-exporter", device!="lo"}[1m])\n)\n',
record: "instance:node_network_transmit_drop_excluding_lo:rate1m"
}
]
},
{
name: "k8s.rules",
rules: [
{
expr: 'sum(rate(container_cpu_usage_seconds_total{job="kubelet", image!="", container!="POD"}[5m])) by (namespace)\n',
record: "namespace:container_cpu_usage_seconds_total:sum_rate"
},
{
expr: 'sum by (namespace, pod, container) (\n rate(container_cpu_usage_seconds_total{job="kubelet", image!="", container!="POD"}[5m])\n)\n',
record:
"namespace_pod_container:container_cpu_usage_seconds_total:sum_rate"
},
{
expr: 'sum(container_memory_usage_bytes{job="kubelet", image!="", container!="POD"}) by (namespace)\n',
record: "namespace:container_memory_usage_bytes:sum"
},
{
expr: 'sum by (namespace, label_name) (\n sum(kube_pod_container_resource_requests_memory_bytes{job="kube-state-metrics"} * on (endpoint, instance, job, namespace, pod, service) group_left(phase) (kube_pod_status_phase{phase=~"^(Pending|Running)$"} == 1)) by (namespace, pod)\n * on (namespace, pod)\n group_left(label_name) kube_pod_labels{job="kube-state-metrics"}\n)\n',
record:
"namespace:kube_pod_container_resource_requests_memory_bytes:sum"
},
{
expr: 'sum by (namespace, label_name) (\n sum(kube_pod_container_resource_requests_cpu_cores{job="kube-state-metrics"} * on (endpoint, instance, job, namespace, pod, service) group_left(phase) (kube_pod_status_phase{phase=~"^(Pending|Running)$"} == 1)) by (namespace, pod)\n * on (namespace, pod)\n group_left(label_name) kube_pod_labels{job="kube-state-metrics"}\n)\n',
record: "namespace:kube_pod_container_resource_requests_cpu_cores:sum"
},
{
expr: 'sum(\n label_replace(\n label_replace(\n kube_pod_owner{job="kube-state-metrics", owner_kind="ReplicaSet"},\n "replicaset", "$1", "owner_name", "(.*)"\n ) * on(replicaset, namespace) group_left(owner_name) kube_replicaset_owner{job="kube-state-metrics"},\n "workload", "$1", "owner_name", "(.*)"\n )\n) by (namespace, workload, pod)\n',
labels: {
workload_type: "deployment"
},
record: "mixin_pod_workload"
},
{
expr: 'sum(\n label_replace(\n kube_pod_owner{job="kube-state-metrics", owner_kind="DaemonSet"},\n "workload", "$1", "owner_name", "(.*)"\n )\n) by (namespace, workload, pod)\n',
labels: {
workload_type: "daemonset"
},
record: "mixin_pod_workload"
},
{
expr: 'sum(\n label_replace(\n kube_pod_owner{job="kube-state-metrics", owner_kind="StatefulSet"},\n "workload", "$1", "owner_name", "(.*)"\n )\n) by (namespace, workload, pod)\n',
labels: {
workload_type: "statefulset"
},
record: "mixin_pod_workload"
}
]
},
{
name: "kube-scheduler.rules",
rules: [
{
expr: 'histogram_quantile(0.99, sum(rate(scheduler_e2e_scheduling_duration_seconds_bucket{job="kube-scheduler"}[5m])) without(instance, pod))\n',
labels: {
quantile: "0.99"
},
record:
"cluster_quantile:scheduler_e2e_scheduling_duration_seconds:histogram_quantile"
},
{
expr: 'histogram_quantile(0.99, sum(rate(scheduler_scheduling_algorithm_duration_seconds_bucket{job="kube-scheduler"}[5m])) without(instance, pod))\n',
labels: {
quantile: "0.99"
},
record:
"cluster_quantile:scheduler_scheduling_algorithm_duration_seconds:histogram_quantile"
},
{
expr: 'histogram_quantile(0.99, sum(rate(scheduler_binding_duration_seconds_bucket{job="kube-scheduler"}[5m])) without(instance, pod))\n',
labels: {
quantile: "0.99"
},
record:
"cluster_quantile:scheduler_binding_duration_seconds:histogram_quantile"
},
{
expr: 'histogram_quantile(0.9, sum(rate(scheduler_e2e_scheduling_duration_seconds_bucket{job="kube-scheduler"}[5m])) without(instance, pod))\n',
labels: {
quantile: "0.9"
},
record:
"cluster_quantile:scheduler_e2e_scheduling_duration_seconds:histogram_quantile"
},
{
expr: 'histogram_quantile(0.9, sum(rate(scheduler_scheduling_algorithm_duration_seconds_bucket{job="kube-scheduler"}[5m])) without(instance, pod))\n',
labels: {
quantile: "0.9"
},
record:
"cluster_quantile:scheduler_scheduling_algorithm_duration_seconds:histogram_quantile"
},
{
expr: 'histogram_quantile(0.9, sum(rate(scheduler_binding_duration_seconds_bucket{job="kube-scheduler"}[5m])) without(instance, pod))\n',
labels: {
quantile: "0.9"
},
record:
"cluster_quantile:scheduler_binding_duration_seconds:histogram_quantile"
},
{
expr: 'histogram_quantile(0.5, sum(rate(scheduler_e2e_scheduling_duration_seconds_bucket{job="kube-scheduler"}[5m])) without(instance, pod))\n',
labels: {
quantile: "0.5"
},
record:
"cluster_quantile:scheduler_e2e_scheduling_duration_seconds:histogram_quantile"
},
{
expr: 'histogram_quantile(0.5, sum(rate(scheduler_scheduling_algorithm_duration_seconds_bucket{job="kube-scheduler"}[5m])) without(instance, pod))\n',
labels: {
quantile: "0.5"
},
record:
"cluster_quantile:scheduler_scheduling_algorithm_duration_seconds:histogram_quantile"
},
{
expr: 'histogram_quantile(0.5, sum(rate(scheduler_binding_duration_seconds_bucket{job="kube-scheduler"}[5m])) without(instance, pod))\n',
labels: {
quantile: "0.5"
},
record:
"cluster_quantile:scheduler_binding_duration_seconds:histogram_quantile"
}
]
},
{
name: "kube-apiserver.rules",
rules: [
{
expr: 'histogram_quantile(0.99, sum(rate(apiserver_request_duration_seconds_bucket{job="apiserver"}[5m])) without(instance, pod))\n',
labels: {
quantile: "0.99"
},
record:
"cluster_quantile:apiserver_request_duration_seconds:histogram_quantile"
},
{
expr: 'histogram_quantile(0.9, sum(rate(apiserver_request_duration_seconds_bucket{job="apiserver"}[5m])) without(instance, pod))\n',
labels: {
quantile: "0.9"
},
record:
"cluster_quantile:apiserver_request_duration_seconds:histogram_quantile"
},
{
expr: 'histogram_quantile(0.5, sum(rate(apiserver_request_duration_seconds_bucket{job="apiserver"}[5m])) without(instance, pod))\n',
labels: {
quantile: "0.5"
},
record:
"cluster_quantile:apiserver_request_duration_seconds:histogram_quantile"
}
]
},
{
name: "node.rules",
rules: [
{
expr: "sum(min(kube_pod_info) by (node))",
record: ":kube_pod_info_node_count:"
},
{
expr: 'max(label_replace(kube_pod_info{job="kube-state-metrics"}, "pod", "$1", "pod", "(.*)")) by (node, namespace, pod)\n',
record: "node_namespace_pod:kube_pod_info:"
},
{
expr: 'count by (node) (sum by (node, cpu) (\n node_cpu_seconds_total{job="node-exporter"}\n* on (namespace, pod) group_left(node)\n node_namespace_pod:kube_pod_info:\n))\n',
record: "node:node_num_cpu:sum"
},
{
expr: 'sum(node_memory_MemFree_bytes{job="node-exporter"} + node_memory_Cached_bytes{job="node-exporter"} + node_memory_Buffers_bytes{job="node-exporter"})\n',
record: ":node_memory_MemFreeCachedBuffers_bytes:sum"
}
]
},
{
name: "kube-prometheus-node-recording.rules",
rules: [
{
expr: 'sum(rate(node_cpu_seconds_total{mode!="idle",mode!="iowait"}[3m])) BY\n(instance)',
record: "instance:node_cpu:rate:sum"
},
{
expr: 'sum((node_filesystem_size_bytes{mountpoint="/"} - node_filesystem_free_bytes{mountpoint="/"}))\nBY (instance)',
record: "instance:node_filesystem_usage:sum"
},
{
expr: "sum(rate(node_network_receive_bytes_total[3m])) BY (instance)",
record: "instance:node_network_receive_bytes:rate:sum"
},
{
expr: "sum(rate(node_network_transmit_bytes_total[3m])) BY (instance)",
record: "instance:node_network_transmit_bytes:rate:sum"
},
{
expr: 'sum(rate(node_cpu_seconds_total{mode!="idle",mode!="iowait"}[5m])) WITHOUT\n(cpu, mode) / ON(instance) GROUP_LEFT() count(sum(node_cpu_seconds_total)\nBY (instance, cpu)) BY (instance)',
record: "instance:node_cpu:ratio"
},
{
expr: 'sum(rate(node_cpu_seconds_total{mode!="idle",mode!="iowait"}[5m]))',
record: "cluster:node_cpu:sum_rate5m"
},
{
expr: "cluster:node_cpu_seconds_total:rate5m / count(sum(node_cpu_seconds_total)\nBY (instance, cpu))",
record: "cluster:node_cpu:ratio"
}
]
},
{
name: "cortex_api",
rules: [
{
expr: "histogram_quantile(0.99, sum(rate(cortex_request_duration_seconds_bucket[1m])) by (le, cluster, job))",
record: "cluster_job:cortex_request_duration_seconds:99quantile"
},
{
expr: "histogram_quantile(0.50, sum(rate(cortex_request_duration_seconds_bucket[1m])) by (le, cluster, job))",
record: "cluster_job:cortex_request_duration_seconds:50quantile"
},
{
expr: "sum(rate(cortex_request_duration_seconds_sum[1m])) by (cluster, job) / sum(rate(cortex_request_duration_seconds_count[1m])) by (cluster, job)",
record: "cluster_job:cortex_request_duration_seconds:avg"
},
{
expr: "sum(rate(cortex_request_duration_seconds_bucket[1m])) by (le, cluster, job)",
record: "cluster_job:cortex_request_duration_seconds_bucket:sum_rate"
},
{
expr: "sum(rate(cortex_request_duration_seconds_sum[1m])) by (cluster, job)",
record: "cluster_job:cortex_request_duration_seconds_sum:sum_rate"
},
{
expr: "sum(rate(cortex_request_duration_seconds_count[1m])) by (cluster, job)",
record: "cluster_job:cortex_request_duration_seconds_count:sum_rate"
},
{
expr: "histogram_quantile(0.99, sum(rate(cortex_request_duration_seconds_bucket[1m])) by (le, cluster, job, route))",
record: "cluster_job_route:cortex_request_duration_seconds:99quantile"
},
{
expr: "histogram_quantile(0.50, sum(rate(cortex_request_duration_seconds_bucket[1m])) by (le, cluster, job, route))",
record: "cluster_job_route:cortex_request_duration_seconds:50quantile"
},
{
expr: "sum(rate(cortex_request_duration_seconds_sum[1m])) by (cluster, job, route) / sum(rate(cortex_request_duration_seconds_count[1m])) by (cluster, job, route)",
record: "cluster_job_route:cortex_request_duration_seconds:avg"
},
{
expr: "sum(rate(cortex_request_duration_seconds_bucket[1m])) by (le, cluster, job, route)",
record:
"cluster_job_route:cortex_request_duration_seconds_bucket:sum_rate"
},
{
expr: "sum(rate(cortex_request_duration_seconds_sum[1m])) by (cluster, job, route)",
record: "cluster_job_route:cortex_request_duration_seconds_sum:sum_rate"
},
{
expr: "sum(rate(cortex_request_duration_seconds_count[1m])) by (cluster, job, route)",
record:
"cluster_job_route:cortex_request_duration_seconds_count:sum_rate"
},
{
expr: "histogram_quantile(0.99, sum(rate(cortex_request_duration_seconds_bucket[1m])) by (le, cluster, namespace, job, route))",
record:
"cluster_namespace_job_route:cortex_request_duration_seconds:99quantile"
},
{
expr: "histogram_quantile(0.50, sum(rate(cortex_request_duration_seconds_bucket[1m])) by (le, cluster, namespace, job, route))",
record:
"cluster_namespace_job_route:cortex_request_duration_seconds:50quantile"
},
{
expr: "sum(rate(cortex_request_duration_seconds_sum[1m])) by (cluster, namespace, job, route) / sum(rate(cortex_request_duration_seconds_count[1m])) by (cluster, namespace, job, route)",
record:
"cluster_namespace_job_route:cortex_request_duration_seconds:avg"
},
{
expr: "sum(rate(cortex_request_duration_seconds_bucket[1m])) by (le, cluster, namespace, job, route)",
record:
"cluster_namespace_job_route:cortex_request_duration_seconds_bucket:sum_rate"
},
{
expr: "sum(rate(cortex_request_duration_seconds_sum[1m])) by (cluster, namespace, job, route)",
record:
"cluster_namespace_job_route:cortex_request_duration_seconds_sum:sum_rate"
},
{
expr: "sum(rate(cortex_request_duration_seconds_count[1m])) by (cluster, namespace, job, route)",
record:
"cluster_namespace_job_route:cortex_request_duration_seconds_count:sum_rate"
}
]
},
{
name: "cortex_querier_api",
rules: [
{
expr: "histogram_quantile(0.99, sum(rate(cortex_querier_request_duration_seconds_bucket[1m])) by (le, cluster, job))",
record: "cluster_job:cortex_querier_request_duration_seconds:99quantile"
},
{
expr: "histogram_quantile(0.50, sum(rate(cortex_querier_request_duration_seconds_bucket[1m])) by (le, cluster, job))",
record: "cluster_job:cortex_querier_request_duration_seconds:50quantile"
},
{
expr: "sum(rate(cortex_querier_request_duration_seconds_sum[1m])) by (cluster, job) / sum(rate(cortex_querier_request_duration_seconds_count[1m])) by (cluster, job)",
record: "cluster_job:cortex_querier_request_duration_seconds:avg"
},
{
expr: "sum(rate(cortex_querier_request_duration_seconds_bucket[1m])) by (le, cluster, job)",
record:
"cluster_job:cortex_querier_request_duration_seconds_bucket:sum_rate"
},
{
expr: "sum(rate(cortex_querier_request_duration_seconds_sum[1m])) by (cluster, job)",
record:
"cluster_job:cortex_querier_request_duration_seconds_sum:sum_rate"
},
{
expr: "sum(rate(cortex_querier_request_duration_seconds_count[1m])) by (cluster, job)",
record:
"cluster_job:cortex_querier_request_duration_seconds_count:sum_rate"
},
{
expr: "histogram_quantile(0.99, sum(rate(cortex_querier_request_duration_seconds_bucket[1m])) by (le, cluster, job, route))",
record:
"cluster_job_route:cortex_querier_request_duration_seconds:99quantile"
},
{
expr: "histogram_quantile(0.50, sum(rate(cortex_querier_request_duration_seconds_bucket[1m])) by (le, cluster, job, route))",
record:
"cluster_job_route:cortex_querier_request_duration_seconds:50quantile"
},
{
expr: "sum(rate(cortex_querier_request_duration_seconds_sum[1m])) by (cluster, job, route) / sum(rate(cortex_querier_request_duration_seconds_count[1m])) by (cluster, job, route)",
record: "cluster_job_route:cortex_querier_request_duration_seconds:avg"
},
{
expr: "sum(rate(cortex_querier_request_duration_seconds_bucket[1m])) by (le, cluster, job, route)",
record:
"cluster_job_route:cortex_querier_request_duration_seconds_bucket:sum_rate"
},
{
expr: "sum(rate(cortex_querier_request_duration_seconds_sum[1m])) by (cluster, job, route)",
record:
"cluster_job_route:cortex_querier_request_duration_seconds_sum:sum_rate"
},
{
expr: "sum(rate(cortex_querier_request_duration_seconds_count[1m])) by (cluster, job, route)",
record:
"cluster_job_route:cortex_querier_request_duration_seconds_count:sum_rate"
},
{
expr: "histogram_quantile(0.99, sum(rate(cortex_querier_request_duration_seconds_bucket[1m])) by (le, cluster, namespace, job, route))",
record:
"cluster_namespace_job_route:cortex_querier_request_duration_seconds:99quantile"
},
{
expr: "histogram_quantile(0.50, sum(rate(cortex_querier_request_duration_seconds_bucket[1m])) by (le, cluster, namespace, job, route))",
record:
"cluster_namespace_job_route:cortex_querier_request_duration_seconds:50quantile"
},
{
expr: "sum(rate(cortex_querier_request_duration_seconds_sum[1m])) by (cluster, namespace, job, route) / sum(rate(cortex_querier_request_duration_seconds_count[1m])) by (cluster, namespace, job, route)",
record:
"cluster_namespace_job_route:cortex_querier_request_duration_seconds:avg"
},
{
expr: "sum(rate(cortex_querier_request_duration_seconds_bucket[1m])) by (le, cluster, namespace, job, route)",
record:
"cluster_namespace_job_route:cortex_querier_request_duration_seconds_bucket:sum_rate"
},
{
expr: "sum(rate(cortex_querier_request_duration_seconds_sum[1m])) by (cluster, namespace, job, route)",
record:
"cluster_namespace_job_route:cortex_querier_request_duration_seconds_sum:sum_rate"
},
{
expr: "sum(rate(cortex_querier_request_duration_seconds_count[1m])) by (cluster, namespace, job, route)",
record:
"cluster_namespace_job_route:cortex_querier_request_duration_seconds_count:sum_rate"
}
]
},
{
name: "cortex_cache",
rules: [
{
expr: "histogram_quantile(0.99, sum(rate(cortex_memcache_request_duration_seconds_bucket[1m])) by (le, cluster, job, method))",
record:
"cluster_job_method:cortex_memcache_request_duration_seconds:99quantile"
},
{
expr: "histogram_quantile(0.50, sum(rate(cortex_memcache_request_duration_seconds_bucket[1m])) by (le, cluster, job, method))",
record:
"cluster_job_method:cortex_memcache_request_duration_seconds:50quantile"
},
{
expr: "sum(rate(cortex_memcache_request_duration_seconds_sum[1m])) by (cluster, job, method) / sum(rate(cortex_memcache_request_duration_seconds_count[1m])) by (cluster, job, method)",
record:
"cluster_job_method:cortex_memcache_request_duration_seconds:avg"
},
{
expr: "sum(rate(cortex_memcache_request_duration_seconds_bucket[1m])) by (le, cluster, job, method)",
record:
"cluster_job_method:cortex_memcache_request_duration_seconds_bucket:sum_rate"
},
{
expr: "sum(rate(cortex_memcache_request_duration_seconds_sum[1m])) by (cluster, job, method)",
record:
"cluster_job_method:cortex_memcache_request_duration_seconds_sum:sum_rate"
},
{
expr: "sum(rate(cortex_memcache_request_duration_seconds_count[1m])) by (cluster, job, method)",
record:
"cluster_job_method:cortex_memcache_request_duration_seconds_count:sum_rate"
},
{
expr: "histogram_quantile(0.99, sum(rate(cortex_cache_request_duration_seconds_bucket[1m])) by (le, cluster, job))",
record: "cluster_job:cortex_cache_request_duration_seconds:99quantile"
},
{
expr: "histogram_quantile(0.50, sum(rate(cortex_cache_request_duration_seconds_bucket[1m])) by (le, cluster, job))",
record: "cluster_job:cortex_cache_request_duration_seconds:50quantile"
},
{
expr: "sum(rate(cortex_cache_request_duration_seconds_sum[1m])) by (cluster, job) / sum(rate(cortex_cache_request_duration_seconds_count[1m])) by (cluster, job)",
record: "cluster_job:cortex_cache_request_duration_seconds:avg"
},
{
expr: "sum(rate(cortex_cache_request_duration_seconds_bucket[1m])) by (le, cluster, job)",
record:
"cluster_job:cortex_cache_request_duration_seconds_bucket:sum_rate"
},
{
expr: "sum(rate(cortex_cache_request_duration_seconds_sum[1m])) by (cluster, job)",
record: "cluster_job:cortex_cache_request_duration_seconds_sum:sum_rate"
},
{
expr: "sum(rate(cortex_cache_request_duration_seconds_count[1m])) by (cluster, job)",
record:
"cluster_job:cortex_cache_request_duration_seconds_count:sum_rate"
},
{
expr: "histogram_quantile(0.99, sum(rate(cortex_cache_request_duration_seconds_bucket[1m])) by (le, cluster, job, method))",
record:
"cluster_job_method:cortex_cache_request_duration_seconds:99quantile"
},
{
expr: "histogram_quantile(0.50, sum(rate(cortex_cache_request_duration_seconds_bucket[1m])) by (le, cluster, job, method))",
record:
"cluster_job_method:cortex_cache_request_duration_seconds:50quantile"
},
{
expr: "sum(rate(cortex_cache_request_duration_seconds_sum[1m])) by (cluster, job, method) / sum(rate(cortex_cache_request_duration_seconds_count[1m])) by (cluster, job, method)",
record: "cluster_job_method:cortex_cache_request_duration_seconds:avg"
},
{
expr: "sum(rate(cortex_cache_request_duration_seconds_bucket[1m])) by (le, cluster, job, method)",
record:
"cluster_job_method:cortex_cache_request_duration_seconds_bucket:sum_rate"
},
{
expr: "sum(rate(cortex_cache_request_duration_seconds_sum[1m])) by (cluster, job, method)",
record:
"cluster_job_method:cortex_cache_request_duration_seconds_sum:sum_rate"
},
{
expr: "sum(rate(cortex_cache_request_duration_seconds_count[1m])) by (cluster, job, method)",
record:
"cluster_job_method:cortex_cache_request_duration_seconds_count:sum_rate"
}
]
},
{
name: "cortex_queries",
rules: [
{
expr: "histogram_quantile(0.99, sum(rate(cortex_query_frontend_retries_bucket[1m])) by (le, cluster, job))",
record: "cluster_job:cortex_query_frontend_retries:99quantile"
},
{
expr: "histogram_quantile(0.50, sum(rate(cortex_query_frontend_retries_bucket[1m])) by (le, cluster, job))",
record: "cluster_job:cortex_query_frontend_retries:50quantile"
},
{
expr: "sum(rate(cortex_query_frontend_retries_sum[1m])) by (cluster, job) / sum(rate(cortex_query_frontend_retries_count[1m])) by (cluster, job)",
record: "cluster_job:cortex_query_frontend_retries:avg"
},
{
expr: "sum(rate(cortex_query_frontend_retries_bucket[1m])) by (le, cluster, job)",
record: "cluster_job:cortex_query_frontend_retries_bucket:sum_rate"
},
{
expr: "sum(rate(cortex_query_frontend_retries_sum[1m])) by (cluster, job)",
record: "cluster_job:cortex_query_frontend_retries_sum:sum_rate"
},
{
expr: "sum(rate(cortex_query_frontend_retries_count[1m])) by (cluster, job)",
record: "cluster_job:cortex_query_frontend_retries_count:sum_rate"
},
{
expr: "histogram_quantile(0.99, sum(rate(cortex_query_frontend_queue_duration_seconds_bucket[1m])) by (le, cluster, job))",
record:
"cluster_job:cortex_query_frontend_queue_duration_seconds:99quantile"
},
{
expr: "histogram_quantile(0.50, sum(rate(cortex_query_frontend_queue_duration_seconds_bucket[1m])) by (le, cluster, job))",
record:
"cluster_job:cortex_query_frontend_queue_duration_seconds:50quantile"
},
{
expr: "sum(rate(cortex_query_frontend_queue_duration_seconds_sum[1m])) by (cluster, job) / sum(rate(cortex_query_frontend_queue_duration_seconds_count[1m])) by (cluster, job)",
record: "cluster_job:cortex_query_frontend_queue_duration_seconds:avg"
},
{
expr: "sum(rate(cortex_query_frontend_queue_duration_seconds_bucket[1m])) by (le, cluster, job)",
record:
"cluster_job:cortex_query_frontend_queue_duration_seconds_bucket:sum_rate"
},
{
expr: "sum(rate(cortex_query_frontend_queue_duration_seconds_sum[1m])) by (cluster, job)",
record:
"cluster_job:cortex_query_frontend_queue_duration_seconds_sum:sum_rate"
},
{
expr: "sum(rate(cortex_query_frontend_queue_duration_seconds_count[1m])) by (cluster, job)",
record:
"cluster_job:cortex_query_frontend_queue_duration_seconds_count:sum_rate"
},
{
expr: "histogram_quantile(0.99, sum(rate(cortex_ingester_queried_series_bucket[1m])) by (le, cluster, job))",
record: "cluster_job:cortex_ingester_queried_series:99quantile"
},
{
expr: "histogram_quantile(0.50, sum(rate(cortex_ingester_queried_series_bucket[1m])) by (le, cluster, job))",
record: "cluster_job:cortex_ingester_queried_series:50quantile"
},
{
expr: "sum(rate(cortex_ingester_queried_series_sum[1m])) by (cluster, job) / sum(rate(cortex_ingester_queried_series_count[1m])) by (cluster, job)",
record: "cluster_job:cortex_ingester_queried_series:avg"
},
{
expr: "sum(rate(cortex_ingester_queried_series_bucket[1m])) by (le, cluster, job)",
record: "cluster_job:cortex_ingester_queried_series_bucket:sum_rate"
},
{
expr: "sum(rate(cortex_ingester_queried_series_sum[1m])) by (cluster, job)",
record: "cluster_job:cortex_ingester_queried_series_sum:sum_rate"
},
{
expr: "sum(rate(cortex_ingester_queried_series_count[1m])) by (cluster, job)",
record: "cluster_job:cortex_ingester_queried_series_count:sum_rate"
},
{
expr: "histogram_quantile(0.99, sum(rate(cortex_ingester_queried_chunks_bucket[1m])) by (le, cluster, job))",
record: "cluster_job:cortex_ingester_queried_chunks:99quantile"
},
{
expr: "histogram_quantile(0.50, sum(rate(cortex_ingester_queried_chunks_bucket[1m])) by (le, cluster, job))",
record: "cluster_job:cortex_ingester_queried_chunks:50quantile"
},
{
expr: "sum(rate(cortex_ingester_queried_chunks_sum[1m])) by (cluster, job) / sum(rate(cortex_ingester_queried_chunks_count[1m])) by (cluster, job)",
record: "cluster_job:cortex_ingester_queried_chunks:avg"
},
{
expr: "sum(rate(cortex_ingester_queried_chunks_bucket[1m])) by (le, cluster, job)",
record: "cluster_job:cortex_ingester_queried_chunks_bucket:sum_rate"
},
{
expr: "sum(rate(cortex_ingester_queried_chunks_sum[1m])) by (cluster, job)",
record: "cluster_job:cortex_ingester_queried_chunks_sum:sum_rate"
},
{
expr: "sum(rate(cortex_ingester_queried_chunks_count[1m])) by (cluster, job)",
record: "cluster_job:cortex_ingester_queried_chunks_count:sum_rate"
},
{
expr: "histogram_quantile(0.99, sum(rate(cortex_ingester_queried_samples_bucket[1m])) by (le, cluster, job))",
record: "cluster_job:cortex_ingester_queried_samples:99quantile"
},
{
expr: "histogram_quantile(0.50, sum(rate(cortex_ingester_queried_samples_bucket[1m])) by (le, cluster, job))",
record: "cluster_job:cortex_ingester_queried_samples:50quantile"
},
{
expr: "sum(rate(cortex_ingester_queried_samples_sum[1m])) by (cluster, job) / sum(rate(cortex_ingester_queried_samples_count[1m])) by (cluster, job)",
record: "cluster_job:cortex_ingester_queried_samples:avg"
},
{
expr: "sum(rate(cortex_ingester_queried_samples_bucket[1m])) by (le, cluster, job)",
record: "cluster_job:cortex_ingester_queried_samples_bucket:sum_rate"
},
{
expr: "sum(rate(cortex_ingester_queried_samples_sum[1m])) by (cluster, job)",
record: "cluster_job:cortex_ingester_queried_samples_sum:sum_rate"
},
{
expr: "sum(rate(cortex_ingester_queried_samples_count[1m])) by (cluster, job)",
record: "cluster_job:cortex_ingester_queried_samples_count:sum_rate"
}
]
},
{
name: "cortex_received_samples",
rules: [
{
expr: "sum by (cluster, namespace, job) (rate(cortex_distributor_received_samples_total[5m]))\n",
record:
"cluster_namespace_job:cortex_distributor_received_samples:rate5m"
}
]
},
{
name: "cortex_scaling_rules",
rules: [
{
expr: 'sum by (cluster, namespace, deployment) (\n label_replace(\n kube_deployment_spec_replicas,\n \n \n "deployment", "$1", "deployment", "(.*?)(?:-zone-[a-z])?"\n )\n)\nor\nsum by (cluster, namespace, deployment) (\n label_replace(kube_statefulset_replicas, "deployment", "$1", "statefulset", "(.*?)(?:-zone-[a-z])?")\n)\n',
record: "cluster_namespace_deployment:actual_replicas:count"
},
{
expr: "ceil(\n quantile_over_time(0.99,\n sum by (cluster, namespace) (\n cluster_namespace_job:cortex_distributor_received_samples:rate5m\n )[24h:]\n )\n / 240000\n)\n",
labels: {
deployment: "distributor",
reason: "sample_rate"
},
record: "cluster_namespace_deployment_reason:required_replicas:count"
},
{
expr: 'ceil(\n sum by (cluster, namespace) (cortex_overrides{limit_name="ingestion_rate"})\n * 0.59999999999999998 / 240000\n)\n',
labels: {
deployment: "distributor",
reason: "sample_rate_limits"
},
record: "cluster_namespace_deployment_reason:required_replicas:count"
},
{
expr: "ceil(\n quantile_over_time(0.99,\n sum by (cluster, namespace) (\n cluster_namespace_job:cortex_distributor_received_samples:rate5m\n )[24h:]\n )\n * 3 / 80000\n)\n",
labels: {
deployment: "ingester",
reason: "sample_rate"
},
record: "cluster_namespace_deployment_reason:required_replicas:count"
},
{
expr: "ceil(\n quantile_over_time(0.99,\n sum by(cluster, namespace) (\n cortex_ingester_memory_series\n )[24h:]\n )\n / 1500000\n)\n",
labels: {
deployment: "ingester",
reason: "active_series"
},
record: "cluster_namespace_deployment_reason:required_replicas:count"
},
{
expr: 'ceil(\n sum by (cluster, namespace) (cortex_overrides{limit_name="max_global_series_per_user"})\n * 3 * 0.59999999999999998 / 1500000\n)\n',
labels: {
deployment: "ingester",
reason: "active_series_limits"
},
record: "cluster_namespace_deployment_reason:required_replicas:count"
},
{
expr: 'ceil(\n sum by (cluster, namespace) (cortex_overrides{limit_name="ingestion_rate"})\n * 0.59999999999999998 / 80000\n)\n',
labels: {
deployment: "ingester",
reason: "sample_rate_limits"
},
record: "cluster_namespace_deployment_reason:required_replicas:count"
},
{
expr: 'ceil(\n (sum by (cluster, namespace) (\n cortex_ingester_tsdb_storage_blocks_bytes{job=~".+/ingester.*"}\n ) / 4)\n /\n avg by (cluster, namespace) (\n memcached_limit_bytes{job=~".+/memcached"}\n )\n)\n',
labels: {
deployment: "memcached",
reason: "active_series"
},
record: "cluster_namespace_deployment_reason:required_replicas:count"
},
{
expr: 'sum by (cluster, namespace, deployment) (\n label_replace(\n label_replace(\n node_namespace_pod_container:container_cpu_usage_seconds_total:sum_rate,\n "deployment", "$1", "pod", "(.*)-(?:([0-9]+)|([a-z0-9]+)-([a-z0-9]+))"\n ),\n \n \n "deployment", "$1", "deployment", "(.*?)(?:-zone-[a-z])?"\n )\n)\n',
record:
"cluster_namespace_deployment:container_cpu_usage_seconds_total:sum_rate"
},
{
expr: '(sum by (cluster, namespace, deployment) (\n label_replace(\n label_replace(\n kube_pod_container_resource_requests_cpu_cores,\n "deployment", "$1", "pod", "(.*)-(?:([0-9]+)|([a-z0-9]+)-([a-z0-9]+))"\n ),\n \n \n "deployment", "$1", "deployment", "(.*?)(?:-zone-[a-z])?"\n )\n )\n)\nor\n\n\n(\n sum by (cluster, namespace, deployment) (\n label_replace(\n label_replace(\n kube_pod_container_resource_requests{resource="cpu"},\n "deployment", "$1", "pod", "(.*)-(?:([0-9]+)|([a-z0-9]+)-([a-z0-9]+))"\n ),\n \n \n "deployment", "$1", "deployment", "(.*?)(?:-zone-[a-z])?"\n )\n )\n)\n',
record:
"cluster_namespace_deployment:kube_pod_container_resource_requests_cpu_cores:sum"
},
{
expr: "ceil(\n cluster_namespace_deployment:actual_replicas:count\n *\n quantile_over_time(0.99, cluster_namespace_deployment:container_cpu_usage_seconds_total:sum_rate[24h])\n /\n cluster_namespace_deployment:kube_pod_container_resource_requests_cpu_cores:sum\n)\n",
labels: {
reason: "cpu_usage"
},
record: "cluster_namespace_deployment_reason:required_replicas:count"
},
{
expr: 'sum by (cluster, namespace, deployment) (\n label_replace(\n label_replace(\n container_memory_usage_bytes,\n "deployment", "$1", "pod", "(.*)-(?:([0-9]+)|([a-z0-9]+)-([a-z0-9]+))"\n ),\n \n \n "deployment", "$1", "deployment", "(.*?)(?:-zone-[a-z])?"\n )\n)\n',
record: "cluster_namespace_deployment:container_memory_usage_bytes:sum"
},
{
expr: '(\n sum by (cluster, namespace, deployment) (\n label_replace(\n label_replace(\n kube_pod_container_resource_requests_memory_bytes,\n "deployment", "$1", "pod", "(.*)-(?:([0-9]+)|([a-z0-9]+)-([a-z0-9]+))"\n ),\n \n \n "deployment", "$1", "deployment", "(.*?)(?:-zone-[a-z])?"\n )\n )\n)\nor\n\n\n(\n sum by (cluster, namespace, deployment) (\n label_replace(\n label_replace(\n kube_pod_container_resource_requests{resource="memory"},\n "deployment", "$1", "pod", "(.*)-(?:([0-9]+)|([a-z0-9]+)-([a-z0-9]+))"\n ),\n \n \n "deployment", "$1", "deployment", "(.*?)(?:-zone-[a-z])?"\n )\n )\n)\n',
record:
"cluster_namespace_deployment:kube_pod_container_resource_requests_memory_bytes:sum"
},
{
expr: "ceil(\n cluster_namespace_deployment:actual_replicas:count\n *\n quantile_over_time(0.99, cluster_namespace_deployment:container_memory_usage_bytes:sum[24h])\n /\n cluster_namespace_deployment:kube_pod_container_resource_requests_memory_bytes:sum\n)\n",
labels: {
reason: "memory_usage"
},
record: "cluster_namespace_deployment_reason:required_replicas:count"
}
]
},
{
name: "loki_rules",
rules: [
{
expr: "histogram_quantile(0.99, sum(rate(loki_request_duration_seconds_bucket[1m])) by (le, job))",
record: "job:loki_request_duration_seconds:99quantile"
},
{
expr: "histogram_quantile(0.50, sum(rate(loki_request_duration_seconds_bucket[1m])) by (le, job))",
record: "job:loki_request_duration_seconds:50quantile"
},
{
expr: "sum(rate(loki_request_duration_seconds_sum[1m])) by (job) / sum(rate(loki_request_duration_seconds_count[1m])) by (job)",
record: "job:loki_request_duration_seconds:avg"
},
{
expr: "sum(rate(loki_request_duration_seconds_bucket[1m])) by (le, job)",
record: "job:loki_request_duration_seconds_bucket:sum_rate"
},
{
expr: "sum(rate(loki_request_duration_seconds_sum[1m])) by (job)",
record: "job:loki_request_duration_seconds_sum:sum_rate"
},
{
expr: "sum(rate(loki_request_duration_seconds_count[1m])) by (job)",
record: "job:loki_request_duration_seconds_count:sum_rate"
},
{
expr: "histogram_quantile(0.99, sum(rate(loki_request_duration_seconds_bucket[1m])) by (le, job, route))",
record: "job_route:loki_request_duration_seconds:99quantile"
},
{
expr: "histogram_quantile(0.50, sum(rate(loki_request_duration_seconds_bucket[1m])) by (le, job, route))",
record: "job_route:loki_request_duration_seconds:50quantile"
},
{
expr: "sum(rate(loki_request_duration_seconds_sum[1m])) by (job, route) / sum(rate(loki_request_duration_seconds_count[1m])) by (job, route)",
record: "job_route:loki_request_duration_seconds:avg"
},
{
expr: "sum(rate(loki_request_duration_seconds_bucket[1m])) by (le, job, route)",
record: "job_route:loki_request_duration_seconds_bucket:sum_rate"
},
{
expr: "sum(rate(loki_request_duration_seconds_sum[1m])) by (job, route)",
record: "job_route:loki_request_duration_seconds_sum:sum_rate"
},
{
expr: "sum(rate(loki_request_duration_seconds_count[1m])) by (job, route)",
record: "job_route:loki_request_duration_seconds_count:sum_rate"
},
{
expr: "histogram_quantile(0.99, sum(rate(loki_request_duration_seconds_bucket[1m])) by (le, namespace, job, route))",
record: "namespace_job_route:loki_request_duration_seconds:99quantile"
},
{
expr: "histogram_quantile(0.50, sum(rate(loki_request_duration_seconds_bucket[1m])) by (le, namespace, job, route))",
record: "namespace_job_route:loki_request_duration_seconds:50quantile"
},
{
expr: "sum(rate(loki_request_duration_seconds_sum[1m])) by (namespace, job, route) / sum(rate(loki_request_duration_seconds_count[1m])) by (namespace, job, route)",
record: "namespace_job_route:loki_request_duration_seconds:avg"
},
{
expr: "sum(rate(loki_request_duration_seconds_bucket[1m])) by (le, namespace, job, route)",
record:
"namespace_job_route:loki_request_duration_seconds_bucket:sum_rate"
},
{
expr: "sum(rate(loki_request_duration_seconds_sum[1m])) by (namespace, job, route)",
record: "namespace_job_route:loki_request_duration_seconds_sum:sum_rate"
},
{
expr: "sum(rate(loki_request_duration_seconds_count[1m])) by (namespace, job, route)",
record:
"namespace_job_route:loki_request_duration_seconds_count:sum_rate"
}
]
}
]; | the_stack |
import chai from 'chai'
import chaiAsPromised from 'chai-as-promised'
import { AwsKmsMrkAwareSymmetricKeyringClass } from '../src/kms_mrk_keyring'
import {
NodeAlgorithmSuite,
AlgorithmSuiteIdentifier,
NodeEncryptionMaterial,
KeyringTraceFlag,
Keyring,
Newable,
} from '@aws-crypto/material-management'
chai.use(chaiAsPromised)
const { expect } = chai
describe('AwsKmsMrkAwareSymmetricKeyring: _onEncrypt', () => {
it('Updates materials with data from KMS GenerateDataKey if input materials do not contain plaintext data key', async () => {
const keyId =
'arn:aws:kms:us-east-1:2222222222222:key/mrk-4321abcd12ab34cd56ef1234567890ab'
const context = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
let generateCalled = false
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//= type=test
//# If the input encryption materials (structures.md#encryption-
//# materials) do not contain a plaintext data key OnEncrypt MUST attempt
//# to generate a new plaintext data key by calling AWS KMS
//# GenerateDataKey (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_GenerateDataKey.html).
function generateDataKey({
KeyId,
EncryptionContext,
GrantTokens,
NumberOfBytes,
}: any) {
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//= type=test
//# The keyring MUST call
//# AWS KMS GenerateDataKeys with a request constructed as follows:
expect(EncryptionContext).to.deep.equal(context)
expect(GrantTokens).to.equal(grantTokens)
expect(KeyId).to.equal(KeyId)
expect(NumberOfBytes).to.equal(suite.keyLengthBytes)
generateCalled = true
return {
Plaintext: new Uint8Array(suite.keyLengthBytes),
KeyId,
CiphertextBlob: new Uint8Array(5),
}
}
const client: any = { generateDataKey }
class TestAwsKmsMrkAwareSymmetricKeyring extends AwsKmsMrkAwareSymmetricKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricKeyring({
client,
keyId,
grantTokens,
})
const seedMaterial = new NodeEncryptionMaterial(suite, context)
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//= type=test
//# OnEncrypt MUST take encryption materials (structures.md#encryption-
//# materials) as input.
const material = await testKeyring.onEncrypt(seedMaterial)
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//= type=test
//# If verified,
//# OnEncrypt MUST do the following with the response from AWS KMS
//# GenerateDataKey (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_GenerateDataKey.html):
expect(material.hasUnencryptedDataKey).to.equal(true)
expect(material.encryptedDataKeys).to.have.lengthOf(1)
const [edkGenerate] = material.encryptedDataKeys
expect(edkGenerate.providerId).to.equal('aws-kms')
expect(edkGenerate.providerInfo).to.equal(keyId)
expect(material.keyringTrace).to.have.lengthOf(2)
const [traceGenerate, traceEncrypt1] = material.keyringTrace
expect(traceGenerate.keyNamespace).to.equal('aws-kms')
expect(traceGenerate.keyName).to.equal(keyId)
expect(
traceGenerate.flags & KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY
).to.equal(KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY)
expect(
traceGenerate.flags & KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY
).to.equal(KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY)
expect(
traceGenerate.flags & KeyringTraceFlag.WRAPPING_KEY_SIGNED_ENC_CTX
).to.equal(KeyringTraceFlag.WRAPPING_KEY_SIGNED_ENC_CTX)
expect(traceEncrypt1.keyNamespace).to.equal('aws-kms')
expect(traceEncrypt1.keyName).to.equal(keyId)
expect(
traceEncrypt1.flags & KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY
).to.equal(KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY)
expect(
traceEncrypt1.flags & KeyringTraceFlag.WRAPPING_KEY_SIGNED_ENC_CTX
).to.equal(KeyringTraceFlag.WRAPPING_KEY_SIGNED_ENC_CTX)
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//= type=test
//# * OnEncrypt MUST output the modified encryption materials
//# (structures.md#encryption-materials)
expect(seedMaterial === material).to.equal(true)
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//= type=test
//# If the keyring calls AWS KMS GenerateDataKeys, it MUST use the
//# configured AWS KMS client to make the call.
expect(generateCalled).to.equal(true)
})
it('The generated unencryptedDataKey length must match the algorithm specification.', async () => {
const keyId =
'arn:aws:kms:us-east-1:2222222222222:key/mrk-4321abcd12ab34cd56ef1234567890ab'
const encryptionContext = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
function generateDataKey({ KeyId, EncryptionContext, GrantTokens }: any) {
expect(EncryptionContext).to.deep.equal(encryptionContext)
expect(GrantTokens).to.equal(grantTokens)
return {
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//= type=test
//# If the Generate Data Key call succeeds, OnEncrypt MUST verify that
//# the response "Plaintext" length matches the specification of the
//# algorithm suite (algorithm-suites.md)'s Key Derivation Input Length
//# field.
Plaintext: new Uint8Array(suite.keyLengthBytes - 5),
KeyId,
CiphertextBlob: new Uint8Array(5),
}
}
const client: any = { generateDataKey }
class TestAwsKmsMrkAwareSymmetricKeyring extends AwsKmsMrkAwareSymmetricKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricKeyring({
client,
keyId,
grantTokens,
})
return expect(
testKeyring.onEncrypt(
new NodeEncryptionMaterial(suite, encryptionContext)
)
).to.rejectedWith(
Error,
'Key length does not agree with the algorithm specification.'
)
})
it('The KeyID returned by KMS GenerateDataKey must be a valid ARN', async () => {
const keyId =
'arn:aws:kms:us-east-1:2222222222222:key/mrk-4321abcd12ab34cd56ef1234567890ab'
const encryptionContext = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
function generateDataKey({ EncryptionContext, GrantTokens }: any) {
expect(EncryptionContext).to.deep.equal(encryptionContext)
expect(GrantTokens).to.equal(grantTokens)
return {
Plaintext: new Uint8Array(suite.keyLengthBytes),
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//= type=test
//# The Generate Data Key response's "KeyId" MUST be A valid AWS
//# KMS key ARN (aws-kms-key-arn.md#identifying-an-aws-kms-multi-region-
//# key).
KeyId: 'Not an arn',
CiphertextBlob: new Uint8Array(5),
}
}
const client: any = { generateDataKey }
class TestAwsKmsMrkAwareSymmetricKeyring extends AwsKmsMrkAwareSymmetricKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricKeyring({
client,
keyId,
grantTokens,
})
return await expect(
testKeyring.onEncrypt(
new NodeEncryptionMaterial(suite, encryptionContext)
)
).to.rejectedWith(Error, 'Malformed arn')
})
it('fails if KMS GenerateDataKey fails', async () => {
const keyId =
'arn:aws:kms:us-east-1:2222222222222:key/mrk-4321abcd12ab34cd56ef1234567890ab'
const encryptionContext = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
function generateDataKey() {
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//= type=test
//# If the call to AWS KMS GenerateDataKey
//# (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_GenerateDataKey.html) does not succeed, OnEncrypt MUST NOT modify
//# the encryption materials (structures.md#encryption-materials) and
//# MUST fail.
throw new Error('failed to generate data key')
}
const client: any = { generateDataKey }
class TestAwsKmsMrkAwareSymmetricKeyring extends AwsKmsMrkAwareSymmetricKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricKeyring({
client,
keyId,
grantTokens,
})
const material = new NodeEncryptionMaterial(suite, encryptionContext)
await expect(testKeyring.onEncrypt(material)).to.rejectedWith(
Error,
'failed to generate data key'
)
expect(material.hasValidKey()).to.equal(false)
expect(material.encryptedDataKeys.length).to.equal(0)
})
it('Updates materials with data from KMS Encrypt if input materials contain plaintext data key.', async () => {
const configuredKeyId =
'arn:aws:kms:us-east-1:2222222222222:key/mrk-4321abcd12ab34cd56ef1234567890ab'
const encryptionContext = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
const udk = new Uint8Array(suite.keyLengthBytes).fill(2)
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//= type=test
//# The keyring MUST call AWS KMS Encrypt
//# (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_Encrypt.html) using the configured AWS KMS client.
//
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//= type=test
//# The keyring
//# MUST AWS KMS Encrypt call with a request constructed as follows:
function encrypt({
KeyId,
EncryptionContext,
GrantTokens,
Plaintext,
}: any) {
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//= type=test
//# Given a plaintext data key in the encryption materials
//# (structures.md#encryption-materials), OnEncrypt MUST attempt to
//# encrypt the plaintext data key using the configured AWS KMS key
//# identifier.
expect(KeyId).to.equal(configuredKeyId)
expect(Plaintext).to.deep.equal(udk)
expect(EncryptionContext).to.deep.equal(encryptionContext)
expect(GrantTokens).to.equal(grantTokens)
return {
KeyId,
CiphertextBlob: new Uint8Array(5),
grantTokens,
}
}
const client: any = { encrypt }
class TestAwsKmsMrkAwareSymmetricKeyring extends AwsKmsMrkAwareSymmetricKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricKeyring({
client,
keyId: configuredKeyId,
grantTokens,
})
const seedMaterial = new NodeEncryptionMaterial(
suite,
encryptionContext
).setUnencryptedDataKey(new Uint8Array(udk), {
keyName: 'keyName',
keyNamespace: 'keyNamespace',
flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY,
})
const material = await testKeyring.onEncrypt(seedMaterial)
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//= type=test
//# If verified, OnEncrypt MUST do the following with the response from
//# AWS KMS Encrypt (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_Encrypt.html):
expect(material.encryptedDataKeys).to.have.lengthOf(1)
const [kmsEDK] = material.encryptedDataKeys
expect(kmsEDK.providerId).to.equal('aws-kms')
expect(kmsEDK.providerInfo).to.equal(configuredKeyId)
expect(material.keyringTrace).to.have.lengthOf(2)
const [, kmsTrace] = material.keyringTrace
expect(kmsTrace.keyNamespace).to.equal('aws-kms')
expect(kmsTrace.keyName).to.equal(configuredKeyId)
expect(
kmsTrace.flags & KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY
).to.equal(KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY)
expect(
kmsTrace.flags & KeyringTraceFlag.WRAPPING_KEY_SIGNED_ENC_CTX
).to.equal(KeyringTraceFlag.WRAPPING_KEY_SIGNED_ENC_CTX)
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//= type=test
//# If all Encrypt calls succeed, OnEncrypt MUST output the modified
//# encryption materials (structures.md#encryption-materials).
expect(material === seedMaterial).to.equal(true)
})
it('The KeyID returned by KMS Encrypt must be a valid ARN', async () => {
const keyId =
'arn:aws:kms:us-east-1:2222222222222:key/mrk-4321abcd12ab34cd56ef1234567890ab'
const encryptionContext = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
function encrypt({ EncryptionContext, GrantTokens }: any) {
expect(EncryptionContext).to.deep.equal(encryptionContext)
expect(GrantTokens).to.equal(grantTokens)
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//= type=test
//# If the Encrypt call succeeds The response's "KeyId" MUST be A valid
//# AWS KMS key ARN (aws-kms-key-arn.md#identifying-an-aws-kms-multi-
//# region-key).
return {
KeyId: 'Not an arn',
CiphertextBlob: new Uint8Array(5),
grantTokens,
}
}
const client: any = { encrypt }
class TestAwsKmsMrkAwareSymmetricKeyring extends AwsKmsMrkAwareSymmetricKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricKeyring({
client,
keyId,
grantTokens,
})
const seedMaterial = new NodeEncryptionMaterial(
suite,
encryptionContext
).setUnencryptedDataKey(new Uint8Array(suite.keyLengthBytes), {
keyName: 'keyName',
keyNamespace: 'keyNamespace',
flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY,
})
return expect(testKeyring.onEncrypt(seedMaterial)).to.rejectedWith(
Error,
'Malformed arn'
)
})
it('fails if KMS Encrypt fails', async () => {
const keyId =
'arn:aws:kms:us-east-1:2222222222222:key/mrk-4321abcd12ab34cd56ef1234567890ab'
const encryptionContext = { some: 'context' }
const grantTokens = ['grant']
const suite = new NodeAlgorithmSuite(
AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16
)
function encrypt() {
throw new Error('failed to encrypt')
}
const client: any = { encrypt }
class TestAwsKmsMrkAwareSymmetricKeyring extends AwsKmsMrkAwareSymmetricKeyringClass(
Keyring as Newable<Keyring<NodeAlgorithmSuite>>
) {}
const testKeyring = new TestAwsKmsMrkAwareSymmetricKeyring({
client,
keyId,
grantTokens,
})
const seedMaterial = new NodeEncryptionMaterial(
suite,
encryptionContext
).setUnencryptedDataKey(new Uint8Array(suite.keyLengthBytes), {
keyName: 'keyName',
keyNamespace: 'keyNamespace',
flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY,
})
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-keyring.txt#2.7
//= type=test
//# If the call to AWS KMS Encrypt
//# (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_Encrypt.html) does not succeed, OnEncrypt MUST fail.
await expect(testKeyring.onEncrypt(seedMaterial)).to.rejectedWith(
Error,
'failed to encrypt'
)
expect(seedMaterial.encryptedDataKeys.length).to.equal(0)
})
}) | the_stack |
import * as React from 'react';
import { mount, ReactWrapper, shallow, ShallowWrapper } from 'enzyme';
import Callout from '../Callout';
import { KeyCodes } from '../../util/keyCodes';
import { Hovercard, HovercardProps, HovercardState, TriggerType } from '.';
jest.useFakeTimers();
describe('<Hovercard />', () => {
let component: ShallowWrapper<HovercardProps, HovercardState>;
let fullComponent: ReactWrapper<HovercardProps, HovercardState>;
describe('with default options', () => {
beforeEach(() => {
component = shallow(
<Hovercard content={<div>Hovercard content</div>}>
<span>Trigger</span>
</Hovercard>,
);
});
it('matches its snapshot', () => {
expect(component).toMatchSnapshot();
});
});
describe('with additional className', () => {
beforeEach(() => {
component = shallow(
<Hovercard content={<div>Hovercard content</div>} className="TEST_CLASSNAME">
<span>Trigger</span>
</Hovercard>,
);
});
it('matches its snapshot', () => {
expect(component).toMatchSnapshot();
});
});
describe('with screenreaderTitle', () => {
beforeEach(() => {
component = shallow(
<Hovercard
content={<div>Hovercard content</div>}
screenreaderTitle="HIDDEN TITLE"
triggerType={TriggerType.CLICK}
>
<span>Trigger</span>
</Hovercard>,
);
component.find('.y-hovercard--trigger').simulate('click');
});
it('matches its snapshot', () => {
expect(component).toMatchSnapshot();
});
});
describe('hovercard gets displayed', () => {
it('via click', () => {
component = shallow(
<Hovercard content={<div>Hovercard content</div>} triggerType={TriggerType.CLICK}>
<span>Trigger</span>
</Hovercard>,
);
component.find('.y-hovercard--trigger').simulate('click');
expect(component.find('.y-hovercard--modal-container').length).toBe(1);
});
it('via hover after delay', () => {
component = shallow(
<Hovercard content={<div>Hovercard content</div>}>
<span>Trigger</span>
</Hovercard>,
);
component.find('.y-hovercard--trigger').simulate('mouseEnter');
jest.advanceTimersByTime(750);
expect(component.update().find('.y-hovercard--modal-container').length).toBe(1);
});
});
describe('hovercard properly does not display', () => {
it('when clicking a hover trigger', () => {
component = shallow(
<Hovercard content={<div>Hovercard content</div>}>
<span>Trigger</span>
</Hovercard>,
);
component.find('.y-hovercard--trigger').simulate('click');
jest.advanceTimersByTime(750);
expect(component.find('.y-hovercard--modal-container').length).toBe(0);
});
it('when hovering over a click trigger', () => {
component = shallow(
<Hovercard content={<div>Hovercard content</div>} triggerType={TriggerType.CLICK}>
<span>Trigger</span>
</Hovercard>,
);
component.find('.y-hovercard--trigger').simulate('mouseEnter');
jest.advanceTimersByTime(750);
expect(component.find('.y-hovercard--modal-container').length).toBe(0);
});
});
describe('mousing over the trigger', () => {
beforeEach(() => {
component = shallow(
<Hovercard content={<div>Hovercard content</div>}>
<span>Trigger</span>
</Hovercard>,
);
component.find('.y-hovercard--trigger').simulate('mouseEnter');
jest.advanceTimersByTime(250);
});
it('does not show the hovercard before the show timeout completes', () => {
expect(component.find('.y-hovercard--modal-container').length).toBe(0);
});
describe('then mousing back out before the hovercard is displayed', () => {
beforeEach(() => {
component.find('.y-hovercard--trigger').simulate('mouseLeave');
});
it('cancels the hovercard from being displayed', () => {
jest.runAllTimers();
expect(component.find('.y-hovercard--modal-container').length).toBe(0);
});
});
});
describe('when visible', () => {
beforeEach(() => {
component = shallow(
<Hovercard content={<div>Hovercard content</div>}>
<span>Trigger</span>
</Hovercard>,
);
component.find('.y-hovercard--trigger').simulate('mouseEnter');
jest.advanceTimersByTime(750);
component.update();
});
it('is visible', () => {
expect(component.find('.y-hovercard--modal-container').length).toBe(1);
});
describe('and then unmounted', () => {
beforeEach(() => {
component.unmount();
});
it('should clearTimeout on the window', () => {
expect(window.clearTimeout).toHaveBeenCalled();
});
});
describe('and the mouse hovers out of the trigger', () => {
beforeEach(() => {
component.find('.y-hovercard--trigger').simulate('mouseLeave');
});
it('the Hovercard closes after a delay', () => {
jest.advanceTimersByTime(500);
expect(component.update().find(Callout).length).toBe(0);
});
describe('mousing back in', () => {
beforeEach(() => {
jest.advanceTimersByTime(250);
component.find('.y-hovercard--trigger').simulate('mouseEnter');
});
it('prevents the hovercard from closing', () => {
jest.advanceTimersByTime(500);
expect(component.update().find(Callout).length).toBe(1);
});
describe('and mousing back out', () => {
beforeEach(() => {
component.find('.y-hovercard--trigger').simulate('mouseLeave');
});
it('allows the Hovercard to close', () => {
jest.advanceTimersByTime(500);
expect(component.update().find(Callout).length).toBe(0);
});
});
});
});
describe('and the mouse hovers out of the modal body', () => {
beforeEach(() => {
component.find('.y-hovercard--modal-container').simulate('mouseLeave');
});
describe('mousing back in', () => {
beforeEach(() => {
jest.advanceTimersByTime(250);
component
.update()
.find('.y-hovercard--modal-container')
.simulate('mouseEnter');
});
it('prevents the hovercard from closing', () => {
jest.advanceTimersByTime(500);
expect(component.update().find(Callout).length).toBe(1);
});
describe('and mousing back out', () => {
beforeEach(() => {
component.find('.y-hovercard--modal-container').simulate('mouseLeave');
});
it('allows the Hovercard to close', () => {
jest.advanceTimersByTime(500);
expect(component.update().find(Callout).length).toBe(0);
});
});
});
});
describe('and the ESC key is pressed', () => {
beforeEach(() => {
const event = new KeyboardEvent('keydown', { keyCode: KeyCodes.escape } as any);
document.dispatchEvent(event);
});
it('the Hovercard closes immediately', () => {
expect(component.update().find(Callout).length).toBe(0);
});
});
describe('and a non-ESC key is pressed', () => {
beforeEach(() => {
const event = new KeyboardEvent('keydown', { keyCode: KeyCodes.enter } as any);
document.dispatchEvent(event);
});
it('the Hovercard remains open', () => {
expect(component.find(Callout).length).toBe(1);
});
});
});
describe('does not start visible by default', () => {
beforeEach(() => {
// Need to fully render to fire off componentDidMount
fullComponent = mount(
<Hovercard content={<div>Hovercard content</div>}>
<span>Trigger</span>
</Hovercard>,
);
});
it('renders the Hovercard', () => {
expect(fullComponent.find(Callout).length).toBe(0);
});
});
describe('when asked to start visible', () => {
beforeEach(() => {
// Need to fully render to fire off componentDidMount
fullComponent = mount(
<Hovercard content={<div>Hovercard content</div>} startVisible={true}>
<span>Trigger</span>
</Hovercard>,
);
});
it('renders the Hovercard', () => {
expect(fullComponent.find(Callout).length).toBe(1);
});
describe('when a hover out triggers its close timeout', () => {
beforeEach(() => {
fullComponent.find('.y-hovercard--trigger').simulate('mouseLeave');
});
describe('and the component is unmounted before the timeout completes', () => {
beforeEach(() => {
jest.advanceTimersByTime(250);
fullComponent.unmount();
});
it('the timeout has been cleared without throwing an error', () => {
jest.advanceTimersByTime(500);
expect(fullComponent.find('.y-hovercard--trigger').length).toEqual(0);
});
});
});
});
describe('callbacks', () => {
let onHover: jest.Mock;
let onShow: jest.Mock;
let onHide: jest.Mock;
beforeEach(() => {
onHover = jest.fn();
onShow = jest.fn();
onHide = jest.fn();
component = shallow(
<Hovercard
content={<div>Hovercard content</div>}
onTriggerHover={onHover}
onContentDisplay={onShow}
onContentDismiss={onHide}
>
<span>Trigger</span>
</Hovercard>,
);
});
describe('when trigger content is hovered', () => {
beforeEach(() => {
component.find('.y-hovercard--trigger').simulate('mouseEnter');
});
it('onTriggerHover() is called', () => {
expect(onHover.mock.calls.length).toBe(1);
});
describe('when Hovercard content pops up', () => {
beforeEach(() => {
jest.runAllTimers();
});
it('onContentDisplay is called when shown', () => {
expect(onShow.mock.calls.length).toBe(1);
});
describe('when Hovercard content is removed', () => {
beforeEach(() => {
component.find('.y-hovercard--trigger').simulate('mouseLeave');
jest.runAllTimers();
});
it('onContentDismiss is called', () => {
expect(onHide.mock.calls.length).toBe(1);
});
});
});
});
});
}); | the_stack |
import {eventMap} from '@testing-library/dom/dist/event-map'
import {isElementType} from '../../utils'
// this is pretty helpful:
// https://codesandbox.io/s/quizzical-worker-eo909
// all of the stuff below is complex magic that makes the simpler tests work
// sorrynotsorry...
const unstringSnapshotSerializer: jest.SnapshotSerializerPlugin = {
test: (val: unknown) =>
Boolean(
typeof val === 'object'
? Object.prototype.hasOwnProperty.call(val, 'snapshot')
: false,
),
print: val => String((<null | {snapshot?: string}>val)?.snapshot),
}
expect.addSnapshotSerializer(unstringSnapshotSerializer)
type EventHandlers = Record<string, EventListener>
// The HTMLCollection in lib.d.ts does not allow array access
type HTMLCollection<Elements extends Array<Element>> = Elements & {
item<N extends number>(i: N): Elements[N]
}
function setup<Elements extends Element | Element[] = HTMLElement>(
ui: string,
{
eventHandlers,
}: {
eventHandlers?: EventHandlers
} = {},
) {
const div = document.createElement('div')
div.innerHTML = ui.trim()
document.body.append(div)
type ElementsArray = Elements extends Array<Element> ? Elements : [Elements]
return {
element: div.firstChild as ElementsArray[0],
elements: div.children as unknown as HTMLCollection<ElementsArray>,
// for single elements add the listeners to the element for capturing non-bubbling events
...addListeners(
div.children.length === 1 ? (div.firstChild as Element) : div,
{
eventHandlers,
},
),
}
}
function setupSelect({
disabled = false,
disabledOptions = false,
multiple = false,
pointerEvents = 'auto',
} = {}) {
const form = document.createElement('form')
form.innerHTML = `
<select
name="select"
style="pointer-events: ${pointerEvents}"
${disabled ? 'disabled' : ''}
${multiple ? 'multiple' : ''}
>
<option value="1" ${disabledOptions ? 'disabled' : ''}>1</option>
<option value="2" ${disabledOptions ? 'disabled' : ''}>2</option>
<option value="3" ${disabledOptions ? 'disabled' : ''}>3</option>
</select>
`
document.body.append(form)
const select = form.querySelector('select') as HTMLSelectElement
const options = Array.from(form.querySelectorAll('option'))
return {
...addListeners(select),
form,
select,
options,
}
}
function setupListbox() {
const wrapper = document.createElement('div')
wrapper.innerHTML = `
<button id="button" aria-haspopup="listbox">
Some label
</button>
<ul
role="listbox"
name="listbox"
aria-labelledby="button"
>
<li id="1" role="option" aria-selected="false">1</li>
<li id="2" role="option" aria-selected="false">2</li>
<li id="3" role="option" aria-selected="false">3</li>
</ul>
`
document.body.append(wrapper)
const listbox = wrapper.querySelector('[role="listbox"]') as HTMLUListElement
const options = Array.from(
wrapper.querySelectorAll<HTMLElement>('[role="option"]'),
)
// the user is responsible for handling aria-selected on listbox options
options.forEach(el =>
el.addEventListener('click', e => {
const target = e.currentTarget as HTMLElement
target.setAttribute(
'aria-selected',
JSON.stringify(
!JSON.parse(String(target.getAttribute('aria-selected'))),
),
)
}),
)
return {
...addListeners(listbox),
listbox,
options,
}
}
const eventLabelGetters = {
KeyboardEvent(event: KeyboardEvent) {
return [
event.key,
typeof event.keyCode === 'undefined' ? null : `(${event.keyCode})`,
]
.join(' ')
.trim()
},
MouseEvent(event: MouseEvent) {
// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
const mouseButtonMap: Record<number, string> = {
0: 'Left',
1: 'Middle',
2: 'Right',
3: 'Browser Back',
4: 'Browser Forward',
}
return `${mouseButtonMap[event.button]} (${event.button})`
},
} as const
let eventListeners: Array<{
el: EventTarget
type: string
listener: EventListener
}> = []
// asside from the hijacked listener stuff here, it's also important to call
// this function rather than simply calling addEventListener yourself
// because it adds your listener to an eventListeners array which is cleaned
// up automatically which will help use avoid memory leaks.
function addEventListener(
el: EventTarget,
type: string,
listener: EventListener,
options?: AddEventListenerOptions,
) {
eventListeners.push({el, type, listener})
el.addEventListener(type, listener, options)
}
function getElementValue(element: Element) {
if (isElementType(element, 'select') && element.multiple) {
return JSON.stringify(Array.from(element.selectedOptions).map(o => o.value))
} else if (element.getAttribute('role') === 'listbox') {
return JSON.stringify(
element.querySelector('[aria-selected="true"]')?.innerHTML,
)
} else if (element.getAttribute('role') === 'option') {
return JSON.stringify(element.innerHTML)
} else if (
isElementType(element, 'input', {type: 'checkbox'}) ||
isElementType(element, 'input', {type: 'radio'}) ||
isElementType(element, 'button')
) {
// handled separately
return null
}
return JSON.stringify((element as HTMLInputElement).value)
}
function hasProperty<T extends {}, K extends PropertyKey>(
obj: T,
prop: K,
): obj is T & {[k in K]: unknown} {
return prop in obj
}
function getElementDisplayName(element: Element) {
const value = getElementValue(element)
const hasChecked =
isElementType(element, 'input', {type: 'checkbox'}) ||
isElementType(element, 'input', {type: 'radio'})
return [
element.tagName.toLowerCase(),
element.id ? `#${element.id}` : null,
hasProperty(element, 'name') && element.name
? `[name="${element.name}"]`
: null,
hasProperty(element, 'htmlFor') && element.htmlFor
? `[for="${element.htmlFor}"]`
: null,
value ? `[value=${value}]` : null,
hasChecked ? `[checked=${element.checked}]` : null,
isElementType(element, 'option') ? `[selected=${element.selected}]` : null,
element.getAttribute('role') === 'option'
? `[aria-selected=${element.getAttribute('aria-selected')}]`
: null,
]
.filter(Boolean)
.join('')
}
type CallData = {
event: Event
elementDisplayName: string
testData?: TestData
}
type TestData = {
handled?: boolean
// Where is this assigned?
before?: Element
after?: Element
}
function isElement(target: EventTarget): target is Element {
return 'tagName' in target
}
function isMouseEvent(event: Event): event is MouseEvent {
return event.constructor.name === 'MouseEvent'
}
function addListeners(
element: Element & {testData?: TestData},
{
eventHandlers = {},
}: {
eventHandlers?: EventHandlers
} = {},
) {
const eventHandlerCalls: {current: CallData[]} = {current: []}
const generalListener = jest
.fn((event: Event) => {
const target = event.target
const callData: CallData = {
event,
elementDisplayName:
target && isElement(target) ? getElementDisplayName(target) : '',
}
if (element.testData && !element.testData.handled) {
callData.testData = element.testData
// sometimes firing a single event (like click on a checkbox) will
// automatically fire more events (line input and change).
// and we don't want the test data applied to those, so we'll store
// this and not add the testData to our call if that was already handled
element.testData.handled = true
}
eventHandlerCalls.current.push(callData)
})
.mockName('eventListener')
const listeners = Object.keys(eventMap)
for (const name of listeners) {
addEventListener(element, name.toLowerCase(), (...args) => {
if (name in eventHandlers) {
generalListener(...args)
return eventHandlers[name](...args)
}
return generalListener(...args)
})
}
// prevent default of submits in tests
if (isElementType(element, 'form')) {
addEventListener(element, 'submit', e => e.preventDefault())
}
function getEventSnapshot() {
const eventCalls = eventHandlerCalls.current
.map(({event, testData, elementDisplayName}) => {
const eventName = event.constructor.name
const eventLabel =
eventName in eventLabelGetters
? eventLabelGetters[eventName as keyof typeof eventLabelGetters](
event as KeyboardEvent & MouseEvent,
)
: ''
const modifiers = ['altKey', 'shiftKey', 'metaKey', 'ctrlKey']
.filter(key => event[key as keyof Event])
.map(k => `{${k.replace('Key', '')}}`)
.join('')
const firstLine = [
`${elementDisplayName} - ${event.type}`,
[eventLabel, modifiers].filter(Boolean).join(' '),
]
.filter(Boolean)
.join(': ')
return [firstLine, testData?.before ? getChanges(testData) : null]
.filter(Boolean)
.join('\n')
})
.join('\n')
.trim()
if (eventCalls.length) {
return {
snapshot: [
`Events fired on: ${getElementDisplayName(element)}`,
eventCalls,
].join('\n\n'),
}
} else {
return {
snapshot: `No events were fired on: ${getElementDisplayName(element)}`,
}
}
}
const clearEventCalls = () => {
generalListener.mockClear()
eventHandlerCalls.current = []
}
const getEvents = (type?: string) =>
generalListener.mock.calls
.map(([e]) => e)
.filter(e => !type || e.type === type)
const eventWasFired = (eventType: string) => getEvents(eventType).length > 0
function getClickEventsSnapshot() {
const lines = getEvents().map(e =>
isMouseEvent(e)
? `${e.type} - button=${e.button}; buttons=${e.buttons}; detail=${e.detail}`
: e.type,
)
return {snapshot: lines.join('\n')}
}
return {
getEventSnapshot,
getClickEventsSnapshot,
clearEventCalls,
getEvents,
eventWasFired,
}
}
function getValueWithSelection(element?: Element) {
const {value, selectionStart, selectionEnd} = element as HTMLInputElement
return [
value.slice(0, selectionStart ?? undefined),
...(selectionStart === selectionEnd
? ['{CURSOR}']
: [
'{SELECTION}',
value.slice(selectionStart ?? 0, selectionEnd ?? undefined),
'{/SELECTION}',
]),
value.slice(selectionEnd ?? undefined),
].join('')
}
const changeLabelGetter: Record<PropertyKey, (d: TestData) => string> = {
value: ({before, after}) =>
[
JSON.stringify(getValueWithSelection(before)),
JSON.stringify(getValueWithSelection(after)),
].join(' -> '),
checked: ({before, after}) =>
[
(before as HTMLInputElement).checked ? 'checked' : 'unchecked',
(after as HTMLInputElement).checked ? 'checked' : 'unchecked',
].join(' -> '),
// unfortunately, changing a select option doesn't happen within fireEvent
// but rather imperatively via `options.selected = newValue`
// because of this we don't (currently) have a way to track before/after
// in a given fireEvent call.
}
changeLabelGetter.selectionStart = changeLabelGetter.value
changeLabelGetter.selectionEnd = changeLabelGetter.value
const getDefaultLabel = <T>({
key,
before,
after,
}: {
key: keyof T
before: T
after: T
}) => `${key}: ${JSON.stringify(before[key])} -> ${JSON.stringify(after[key])}`
function getChanges({before, after}: TestData) {
const changes = new Set()
if (before && after) {
for (const key of Object.keys(before) as Array<keyof typeof before>) {
if (after[key] !== before[key]) {
changes.add(
(key in changeLabelGetter ? changeLabelGetter[key] : getDefaultLabel)(
{key, before, after},
),
)
}
}
}
return Array.from(changes)
.filter(Boolean)
.map(line => ` ${line}`)
.join('\n')
}
// eslint-disable-next-line jest/prefer-hooks-on-top
afterEach(() => {
for (const {el, type, listener} of eventListeners) {
el.removeEventListener(type, listener)
}
eventListeners = []
document.body.innerHTML = ''
})
export {setup, setupSelect, setupListbox, addEventListener, addListeners} | the_stack |
import * as coreHttp from "@azure/core-http";
/** The result of a list request. */
export interface KeyListResult {
/** The collection value. */
items?: Key[];
/** The URI that can be used to request the next set of paged results. */
nextLink?: string;
}
export interface Key {
/** NOTE: This property will not be serialized. It can only be populated by the server. */
readonly name?: string;
}
/** Azure App Configuration error object. */
export interface ErrorModel {
/** The type of the error. */
type?: string;
/** A brief summary of the error. */
title?: string;
/** The name of the parameter that resulted in the error. */
name?: string;
/** A detailed description of the error. */
detail?: string;
/** The HTTP status code that the error maps to. */
status?: number;
}
/** The result of a list request. */
export interface KeyValueListResult {
/** The collection value. */
items?: KeyValue[];
/** The URI that can be used to request the next set of paged results. */
nextLink?: string;
}
export interface KeyValue {
key: string;
label?: string;
contentType?: string;
value?: string;
lastModified?: Date;
/** Dictionary of <string> */
tags?: { [propertyName: string]: string };
locked?: boolean;
etag?: string;
}
/** The result of a list request. */
export interface LabelListResult {
/** The collection value. */
items?: Label[];
/** The URI that can be used to request the next set of paged results. */
nextLink?: string;
}
export interface Label {
/** NOTE: This property will not be serialized. It can only be populated by the server. */
readonly name?: string;
}
/** Defines headers for AppConfiguration_getKeys operation. */
export interface AppConfigurationGetKeysHeaders {
/** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */
syncToken?: string;
}
/** Defines headers for AppConfiguration_checkKeys operation. */
export interface AppConfigurationCheckKeysHeaders {
/** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */
syncToken?: string;
}
/** Defines headers for AppConfiguration_getKeyValues operation. */
export interface AppConfigurationGetKeyValuesHeaders {
/** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */
syncToken?: string;
}
/** Defines headers for AppConfiguration_checkKeyValues operation. */
export interface AppConfigurationCheckKeyValuesHeaders {
/** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */
syncToken?: string;
}
/** Defines headers for AppConfiguration_getKeyValue operation. */
export interface AppConfigurationGetKeyValueHeaders {
/** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */
syncToken?: string;
/** An identifier representing the returned state of the resource. */
eTag?: string;
/** A UTC datetime that specifies the last time the resource was modified. */
lastModified?: string;
}
/** Defines headers for AppConfiguration_putKeyValue operation. */
export interface AppConfigurationPutKeyValueHeaders {
/** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */
syncToken?: string;
/** An identifier representing the returned state of the resource. */
eTag?: string;
}
/** Defines headers for AppConfiguration_deleteKeyValue operation. */
export interface AppConfigurationDeleteKeyValueHeaders {
/** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */
syncToken?: string;
/** An identifier representing the returned state of the resource. */
eTag?: string;
}
/** Defines headers for AppConfiguration_checkKeyValue operation. */
export interface AppConfigurationCheckKeyValueHeaders {
/** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */
syncToken?: string;
/** An identifier representing the returned state of the resource. */
eTag?: string;
/** A UTC datetime that specifies the last time the resource was modified. */
lastModified?: string;
}
/** Defines headers for AppConfiguration_getLabels operation. */
export interface AppConfigurationGetLabelsHeaders {
/** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */
syncToken?: string;
}
/** Defines headers for AppConfiguration_checkLabels operation. */
export interface AppConfigurationCheckLabelsHeaders {
/** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */
syncToken?: string;
}
/** Defines headers for AppConfiguration_putLock operation. */
export interface AppConfigurationPutLockHeaders {
/** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */
syncToken?: string;
/** An identifier representing the returned state of the resource. */
eTag?: string;
}
/** Defines headers for AppConfiguration_deleteLock operation. */
export interface AppConfigurationDeleteLockHeaders {
/** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */
syncToken?: string;
/** An identifier representing the returned state of the resource. */
eTag?: string;
}
/** Defines headers for AppConfiguration_getRevisions operation. */
export interface AppConfigurationGetRevisionsHeaders {
/** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */
syncToken?: string;
}
/** Defines headers for AppConfiguration_checkRevisions operation. */
export interface AppConfigurationCheckRevisionsHeaders {
/** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */
syncToken?: string;
}
/** Defines headers for AppConfiguration_getKeysNext operation. */
export interface AppConfigurationGetKeysNextHeaders {
/** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */
syncToken?: string;
}
/** Defines headers for AppConfiguration_getKeyValuesNext operation. */
export interface AppConfigurationGetKeyValuesNextHeaders {
/** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */
syncToken?: string;
}
/** Defines headers for AppConfiguration_getLabelsNext operation. */
export interface AppConfigurationGetLabelsNextHeaders {
/** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */
syncToken?: string;
}
/** Defines headers for AppConfiguration_getRevisionsNext operation. */
export interface AppConfigurationGetRevisionsNextHeaders {
/** Enables real-time consistency between requests by providing the returned value in the next request made to the server. */
syncToken?: string;
}
/** Known values of {@link ApiVersion10} that the service accepts. */
export const enum KnownApiVersion10 {
/** Api Version '1.0' */
One0 = "1.0"
}
/**
* Defines values for ApiVersion10. \
* {@link KnownApiVersion10} can be used interchangeably with ApiVersion10,
* this enum contains the known values that the service supports.
* ### Know values supported by the service
* **1.0**: Api Version '1.0'
*/
export type ApiVersion10 = string;
/** Known values of {@link Get6ItemsItem} that the service accepts. */
export const enum KnownGet6ItemsItem {
Key = "key",
Label = "label",
ContentType = "content_type",
Value = "value",
LastModified = "last_modified",
Tags = "tags",
Locked = "locked",
Etag = "etag"
}
/**
* Defines values for Get6ItemsItem. \
* {@link KnownGet6ItemsItem} can be used interchangeably with Get6ItemsItem,
* this enum contains the known values that the service supports.
* ### Know values supported by the service
* **key** \
* **label** \
* **content_type** \
* **value** \
* **last_modified** \
* **tags** \
* **locked** \
* **etag**
*/
export type Get6ItemsItem = string;
/** Known values of {@link Head6ItemsItem} that the service accepts. */
export const enum KnownHead6ItemsItem {
Key = "key",
Label = "label",
ContentType = "content_type",
Value = "value",
LastModified = "last_modified",
Tags = "tags",
Locked = "locked",
Etag = "etag"
}
/**
* Defines values for Head6ItemsItem. \
* {@link KnownHead6ItemsItem} can be used interchangeably with Head6ItemsItem,
* this enum contains the known values that the service supports.
* ### Know values supported by the service
* **key** \
* **label** \
* **content_type** \
* **value** \
* **last_modified** \
* **tags** \
* **locked** \
* **etag**
*/
export type Head6ItemsItem = string;
/** Known values of {@link Get7ItemsItem} that the service accepts. */
export const enum KnownGet7ItemsItem {
Key = "key",
Label = "label",
ContentType = "content_type",
Value = "value",
LastModified = "last_modified",
Tags = "tags",
Locked = "locked",
Etag = "etag"
}
/**
* Defines values for Get7ItemsItem. \
* {@link KnownGet7ItemsItem} can be used interchangeably with Get7ItemsItem,
* this enum contains the known values that the service supports.
* ### Know values supported by the service
* **key** \
* **label** \
* **content_type** \
* **value** \
* **last_modified** \
* **tags** \
* **locked** \
* **etag**
*/
export type Get7ItemsItem = string;
/** Known values of {@link Head7ItemsItem} that the service accepts. */
export const enum KnownHead7ItemsItem {
Key = "key",
Label = "label",
ContentType = "content_type",
Value = "value",
LastModified = "last_modified",
Tags = "tags",
Locked = "locked",
Etag = "etag"
}
/**
* Defines values for Head7ItemsItem. \
* {@link KnownHead7ItemsItem} can be used interchangeably with Head7ItemsItem,
* this enum contains the known values that the service supports.
* ### Know values supported by the service
* **key** \
* **label** \
* **content_type** \
* **value** \
* **last_modified** \
* **tags** \
* **locked** \
* **etag**
*/
export type Head7ItemsItem = string;
/** Known values of {@link Enum5} that the service accepts. */
export const enum KnownEnum5 {
Key = "key",
Label = "label",
ContentType = "content_type",
Value = "value",
LastModified = "last_modified",
Tags = "tags",
Locked = "locked",
Etag = "etag"
}
/**
* Defines values for Enum5. \
* {@link KnownEnum5} can be used interchangeably with Enum5,
* this enum contains the known values that the service supports.
* ### Know values supported by the service
* **key** \
* **label** \
* **content_type** \
* **value** \
* **last_modified** \
* **tags** \
* **locked** \
* **etag**
*/
export type Enum5 = string;
/** Known values of {@link Enum6} that the service accepts. */
export const enum KnownEnum6 {
Key = "key",
Label = "label",
ContentType = "content_type",
Value = "value",
LastModified = "last_modified",
Tags = "tags",
Locked = "locked",
Etag = "etag"
}
/**
* Defines values for Enum6. \
* {@link KnownEnum6} can be used interchangeably with Enum6,
* this enum contains the known values that the service supports.
* ### Know values supported by the service
* **key** \
* **label** \
* **content_type** \
* **value** \
* **last_modified** \
* **tags** \
* **locked** \
* **etag**
*/
export type Enum6 = string;
/** Optional parameters. */
export interface AppConfigurationGetKeysOptionalParams
extends coreHttp.OperationOptions {
/** A filter for the name of the returned keys. */
name?: string;
/** Instructs the server to return elements that appear after the element referred to by the specified token. */
after?: string;
/** Requests the server to respond with the state of the resource at the specified time. */
acceptDatetime?: string;
}
/** Contains response data for the getKeys operation. */
export type AppConfigurationGetKeysResponse = AppConfigurationGetKeysHeaders &
KeyListResult & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: KeyListResult;
/** The parsed HTTP response headers. */
parsedHeaders: AppConfigurationGetKeysHeaders;
};
};
/** Optional parameters. */
export interface AppConfigurationCheckKeysOptionalParams
extends coreHttp.OperationOptions {
/** A filter for the name of the returned keys. */
name?: string;
/** Instructs the server to return elements that appear after the element referred to by the specified token. */
after?: string;
/** Requests the server to respond with the state of the resource at the specified time. */
acceptDatetime?: string;
}
/** Contains response data for the checkKeys operation. */
export type AppConfigurationCheckKeysResponse = AppConfigurationCheckKeysHeaders & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The parsed HTTP response headers. */
parsedHeaders: AppConfigurationCheckKeysHeaders;
};
};
/** Optional parameters. */
export interface AppConfigurationGetKeyValuesOptionalParams
extends coreHttp.OperationOptions {
/** Instructs the server to return elements that appear after the element referred to by the specified token. */
after?: string;
/** Requests the server to respond with the state of the resource at the specified time. */
acceptDatetime?: string;
/** A filter used to match keys. */
key?: string;
/** A filter used to match labels */
label?: string;
/** Used to select what fields are present in the returned resource(s). */
select?: Get6ItemsItem[];
}
/** Contains response data for the getKeyValues operation. */
export type AppConfigurationGetKeyValuesResponse = AppConfigurationGetKeyValuesHeaders &
KeyValueListResult & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: KeyValueListResult;
/** The parsed HTTP response headers. */
parsedHeaders: AppConfigurationGetKeyValuesHeaders;
};
};
/** Optional parameters. */
export interface AppConfigurationCheckKeyValuesOptionalParams
extends coreHttp.OperationOptions {
/** Instructs the server to return elements that appear after the element referred to by the specified token. */
after?: string;
/** Requests the server to respond with the state of the resource at the specified time. */
acceptDatetime?: string;
/** A filter used to match keys. */
key?: string;
/** A filter used to match labels */
label?: string;
/** Used to select what fields are present in the returned resource(s). */
select?: Head6ItemsItem[];
}
/** Contains response data for the checkKeyValues operation. */
export type AppConfigurationCheckKeyValuesResponse = AppConfigurationCheckKeyValuesHeaders & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The parsed HTTP response headers. */
parsedHeaders: AppConfigurationCheckKeyValuesHeaders;
};
};
/** Optional parameters. */
export interface AppConfigurationGetKeyValueOptionalParams
extends coreHttp.OperationOptions {
/** Requests the server to respond with the state of the resource at the specified time. */
acceptDatetime?: string;
/** The label of the key-value to retrieve. */
label?: string;
/** Used to perform an operation only if the targeted resource's etag matches the value provided. */
ifMatch?: string;
/** Used to perform an operation only if the targeted resource's etag does not match the value provided. */
ifNoneMatch?: string;
/** Used to select what fields are present in the returned resource(s). */
select?: Get7ItemsItem[];
}
/** Contains response data for the getKeyValue operation. */
export type AppConfigurationGetKeyValueResponse = AppConfigurationGetKeyValueHeaders &
KeyValue & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: KeyValue;
/** The parsed HTTP response headers. */
parsedHeaders: AppConfigurationGetKeyValueHeaders;
};
};
/** Optional parameters. */
export interface AppConfigurationPutKeyValueOptionalParams
extends coreHttp.OperationOptions {
/** The label of the key-value to create. */
label?: string;
/** Used to perform an operation only if the targeted resource's etag matches the value provided. */
ifMatch?: string;
/** Used to perform an operation only if the targeted resource's etag does not match the value provided. */
ifNoneMatch?: string;
/** The key-value to create. */
entity?: KeyValue;
}
/** Contains response data for the putKeyValue operation. */
export type AppConfigurationPutKeyValueResponse = AppConfigurationPutKeyValueHeaders &
KeyValue & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: KeyValue;
/** The parsed HTTP response headers. */
parsedHeaders: AppConfigurationPutKeyValueHeaders;
};
};
/** Optional parameters. */
export interface AppConfigurationDeleteKeyValueOptionalParams
extends coreHttp.OperationOptions {
/** The label of the key-value to delete. */
label?: string;
/** Used to perform an operation only if the targeted resource's etag matches the value provided. */
ifMatch?: string;
}
/** Contains response data for the deleteKeyValue operation. */
export type AppConfigurationDeleteKeyValueResponse = AppConfigurationDeleteKeyValueHeaders &
KeyValue & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: KeyValue;
/** The parsed HTTP response headers. */
parsedHeaders: AppConfigurationDeleteKeyValueHeaders;
};
};
/** Optional parameters. */
export interface AppConfigurationCheckKeyValueOptionalParams
extends coreHttp.OperationOptions {
/** Requests the server to respond with the state of the resource at the specified time. */
acceptDatetime?: string;
/** The label of the key-value to retrieve. */
label?: string;
/** Used to perform an operation only if the targeted resource's etag matches the value provided. */
ifMatch?: string;
/** Used to perform an operation only if the targeted resource's etag does not match the value provided. */
ifNoneMatch?: string;
/** Used to select what fields are present in the returned resource(s). */
select?: Head7ItemsItem[];
}
/** Contains response data for the checkKeyValue operation. */
export type AppConfigurationCheckKeyValueResponse = AppConfigurationCheckKeyValueHeaders & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The parsed HTTP response headers. */
parsedHeaders: AppConfigurationCheckKeyValueHeaders;
};
};
/** Optional parameters. */
export interface AppConfigurationGetLabelsOptionalParams
extends coreHttp.OperationOptions {
/** A filter for the name of the returned labels. */
name?: string;
/** Instructs the server to return elements that appear after the element referred to by the specified token. */
after?: string;
/** Requests the server to respond with the state of the resource at the specified time. */
acceptDatetime?: string;
/** Used to select what fields are present in the returned resource(s). */
select?: string[];
}
/** Contains response data for the getLabels operation. */
export type AppConfigurationGetLabelsResponse = AppConfigurationGetLabelsHeaders &
LabelListResult & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: LabelListResult;
/** The parsed HTTP response headers. */
parsedHeaders: AppConfigurationGetLabelsHeaders;
};
};
/** Optional parameters. */
export interface AppConfigurationCheckLabelsOptionalParams
extends coreHttp.OperationOptions {
/** A filter for the name of the returned labels. */
name?: string;
/** Instructs the server to return elements that appear after the element referred to by the specified token. */
after?: string;
/** Requests the server to respond with the state of the resource at the specified time. */
acceptDatetime?: string;
/** Used to select what fields are present in the returned resource(s). */
select?: string[];
}
/** Contains response data for the checkLabels operation. */
export type AppConfigurationCheckLabelsResponse = AppConfigurationCheckLabelsHeaders & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The parsed HTTP response headers. */
parsedHeaders: AppConfigurationCheckLabelsHeaders;
};
};
/** Optional parameters. */
export interface AppConfigurationPutLockOptionalParams
extends coreHttp.OperationOptions {
/** The label, if any, of the key-value to lock. */
label?: string;
/** Used to perform an operation only if the targeted resource's etag matches the value provided. */
ifMatch?: string;
/** Used to perform an operation only if the targeted resource's etag does not match the value provided. */
ifNoneMatch?: string;
}
/** Contains response data for the putLock operation. */
export type AppConfigurationPutLockResponse = AppConfigurationPutLockHeaders &
KeyValue & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: KeyValue;
/** The parsed HTTP response headers. */
parsedHeaders: AppConfigurationPutLockHeaders;
};
};
/** Optional parameters. */
export interface AppConfigurationDeleteLockOptionalParams
extends coreHttp.OperationOptions {
/** The label, if any, of the key-value to unlock. */
label?: string;
/** Used to perform an operation only if the targeted resource's etag matches the value provided. */
ifMatch?: string;
/** Used to perform an operation only if the targeted resource's etag does not match the value provided. */
ifNoneMatch?: string;
}
/** Contains response data for the deleteLock operation. */
export type AppConfigurationDeleteLockResponse = AppConfigurationDeleteLockHeaders &
KeyValue & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: KeyValue;
/** The parsed HTTP response headers. */
parsedHeaders: AppConfigurationDeleteLockHeaders;
};
};
/** Optional parameters. */
export interface AppConfigurationGetRevisionsOptionalParams
extends coreHttp.OperationOptions {
/** Instructs the server to return elements that appear after the element referred to by the specified token. */
after?: string;
/** Requests the server to respond with the state of the resource at the specified time. */
acceptDatetime?: string;
/** A filter used to match keys. */
key?: string;
/** A filter used to match labels */
label?: string;
/** Used to select what fields are present in the returned resource(s). */
select?: Enum5[];
}
/** Contains response data for the getRevisions operation. */
export type AppConfigurationGetRevisionsResponse = AppConfigurationGetRevisionsHeaders &
KeyValueListResult & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: KeyValueListResult;
/** The parsed HTTP response headers. */
parsedHeaders: AppConfigurationGetRevisionsHeaders;
};
};
/** Optional parameters. */
export interface AppConfigurationCheckRevisionsOptionalParams
extends coreHttp.OperationOptions {
/** Instructs the server to return elements that appear after the element referred to by the specified token. */
after?: string;
/** Requests the server to respond with the state of the resource at the specified time. */
acceptDatetime?: string;
/** A filter used to match keys. */
key?: string;
/** A filter used to match labels */
label?: string;
/** Used to select what fields are present in the returned resource(s). */
select?: Enum6[];
}
/** Contains response data for the checkRevisions operation. */
export type AppConfigurationCheckRevisionsResponse = AppConfigurationCheckRevisionsHeaders & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The parsed HTTP response headers. */
parsedHeaders: AppConfigurationCheckRevisionsHeaders;
};
};
/** Optional parameters. */
export interface AppConfigurationGetKeysNextOptionalParams
extends coreHttp.OperationOptions {
/** A filter for the name of the returned keys. */
name?: string;
/** Instructs the server to return elements that appear after the element referred to by the specified token. */
after?: string;
/** Requests the server to respond with the state of the resource at the specified time. */
acceptDatetime?: string;
}
/** Contains response data for the getKeysNext operation. */
export type AppConfigurationGetKeysNextResponse = AppConfigurationGetKeysNextHeaders &
KeyListResult & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: KeyListResult;
/** The parsed HTTP response headers. */
parsedHeaders: AppConfigurationGetKeysNextHeaders;
};
};
/** Optional parameters. */
export interface AppConfigurationGetKeyValuesNextOptionalParams
extends coreHttp.OperationOptions {
/** Instructs the server to return elements that appear after the element referred to by the specified token. */
after?: string;
/** Requests the server to respond with the state of the resource at the specified time. */
acceptDatetime?: string;
/** A filter used to match keys. */
key?: string;
/** A filter used to match labels */
label?: string;
/** Used to select what fields are present in the returned resource(s). */
select?: Get6ItemsItem[];
}
/** Contains response data for the getKeyValuesNext operation. */
export type AppConfigurationGetKeyValuesNextResponse = AppConfigurationGetKeyValuesNextHeaders &
KeyValueListResult & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: KeyValueListResult;
/** The parsed HTTP response headers. */
parsedHeaders: AppConfigurationGetKeyValuesNextHeaders;
};
};
/** Optional parameters. */
export interface AppConfigurationGetLabelsNextOptionalParams
extends coreHttp.OperationOptions {
/** A filter for the name of the returned labels. */
name?: string;
/** Instructs the server to return elements that appear after the element referred to by the specified token. */
after?: string;
/** Requests the server to respond with the state of the resource at the specified time. */
acceptDatetime?: string;
/** Used to select what fields are present in the returned resource(s). */
select?: string[];
}
/** Contains response data for the getLabelsNext operation. */
export type AppConfigurationGetLabelsNextResponse = AppConfigurationGetLabelsNextHeaders &
LabelListResult & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: LabelListResult;
/** The parsed HTTP response headers. */
parsedHeaders: AppConfigurationGetLabelsNextHeaders;
};
};
/** Optional parameters. */
export interface AppConfigurationGetRevisionsNextOptionalParams
extends coreHttp.OperationOptions {
/** Instructs the server to return elements that appear after the element referred to by the specified token. */
after?: string;
/** Requests the server to respond with the state of the resource at the specified time. */
acceptDatetime?: string;
/** A filter used to match keys. */
key?: string;
/** A filter used to match labels */
label?: string;
/** Used to select what fields are present in the returned resource(s). */
select?: Enum5[];
}
/** Contains response data for the getRevisionsNext operation. */
export type AppConfigurationGetRevisionsNextResponse = AppConfigurationGetRevisionsNextHeaders &
KeyValueListResult & {
/** The underlying HTTP response. */
_response: coreHttp.HttpResponse & {
/** The response body as text (string format) */
bodyAsText: string;
/** The response body as parsed JSON or XML */
parsedBody: KeyValueListResult;
/** The parsed HTTP response headers. */
parsedHeaders: AppConfigurationGetRevisionsNextHeaders;
};
};
/** Optional parameters. */
export interface AppConfigurationOptionalParams
extends coreHttp.ServiceClientOptions {
/** Used to guarantee real-time consistency between requests. */
syncToken?: string;
/** Overrides client endpoint. */
endpoint?: string;
} | the_stack |
import { define, tools, eventsApi, EventMap, definitions, mixinRules, EventsDefinition, Mixable } from '../object-plus'
import { ItemsBehavior, transactionApi, Transactional, CloneOptions, Transaction, TransactionOptions, TransactionalDefinition, Owner } from '../transactions'
import { Record, SharedType, AggregatedType, createSharedTypeSpec } from '../record'
import { IdIndex, free, sortElements, dispose, Elements, CollectionCore, addIndex, removeIndex, updateIndex, Comparator, CollectionTransaction } from './commons'
import { addTransaction, AddOptions } from './add'
import { setTransaction, emptySetTransaction } from './set'
import { removeOne, removeMany } from './remove'
import { IOPromise, startIO } from '../io-tools'
const { trigger2, on, off } = eventsApi,
{ begin, commit, markAsDirty } = transactionApi,
{ omit, log, assign, defaults, assignToClassProto } = tools;
let _count = 0;
export type GenericComparator = string | ( ( x : Record ) => number ) | ( ( a : Record, b : Record ) => number );
export interface CollectionOptions extends TransactionOptions {
comparator? : GenericComparator
model? : typeof Record
}
export type Predicate<R> = ( val : R, key : number ) => boolean | object;
export interface CollectionDefinition extends TransactionalDefinition {
model? : typeof Record,
itemEvents? : EventsDefinition
_itemEvents? : EventMap
}
const slice = Array.prototype.slice;
class CollectionRefsType extends SharedType {
static defaultValue = [];
}
@define({
// Default client id prefix
cidPrefix : 'c',
model : Record,
_changeEventName : 'changes',
_aggregationError : null
})
@definitions({
comparator : mixinRules.value,
model : mixinRules.protoValue,
itemEvents : mixinRules.merge
})
export class Collection< R extends Record = Record> extends Transactional implements CollectionCore {
_shared : number
_aggregationError : R[]
static Subset : typeof Collection
static Refs : typeof Collection
static _SubsetOf : typeof Collection
createSubset( models : ElementsArg, options ){
const SubsetOf = (<any>this.constructor).subsetOf( this ).options.type,
subset = new SubsetOf( models, options );
subset.resolve( this );
return subset;
}
static onExtend( BaseClass : typeof Transactional ){
// Cached subset collection must not be inherited.
const Ctor = this;
this._SubsetOf = null;
function RefsCollection( a, b, listen? ){
Ctor.call( this, a, b, ItemsBehavior.share | ( listen ? ItemsBehavior.listen : 0 ) );
}
Mixable.mixins.populate( RefsCollection );
RefsCollection.prototype = this.prototype;
RefsCollection._attribute = CollectionRefsType;
this.Refs = this.Subset = <any>RefsCollection;
Transactional.onExtend.call( this, BaseClass );
createSharedTypeSpec( this, SharedType );
}
static onDefine( definition : CollectionDefinition, BaseClass : any ){
if( definition.itemEvents ){
const eventsMap = new EventMap( BaseClass.prototype._itemEvents );
eventsMap.addEventsMap( definition.itemEvents );
this.prototype._itemEvents = eventsMap;
}
if( definition.comparator !== void 0 ) this.prototype.comparator = definition.comparator;
Transactional.onDefine.call( this, definition );
}
static subsetOf : ( collectionReference : any ) => any;
_itemEvents : EventMap
/***********************************
* Core Members
*/
// Array of the records
models : R[]
// Polymorphic accessor for aggregated attribute's canBeUpdated().
get __inner_state__(){ return this.models; }
// Index by id and cid
_byId : { [ id : string ] : R }
set comparator( x : GenericComparator ){
let compare;
switch( typeof x ){
case 'string' :
this._comparator = ( a, b ) => {
const aa = a[ <string>x ], bb = b[ <string>x ];
if( aa === bb ) return 0;
return aa < bb ? -1 : + 1;
}
break;
case 'function' :
if( x.length === 1 ){
this._comparator = ( a, b ) => {
const aa = (<any>x).call( this, a ), bb = (<any>x).call( this, b );
if( aa === bb ) return 0;
return aa < bb ? -1 : + 1;
}
}
else{
this._comparator = ( a, b ) => (<any>x).call( this, a, b );
}
break;
default :
this._comparator = null;
}
}
// TODO: Improve typing
getStore() : Transactional {
return this._store || ( this._store = this._owner ? this._owner.getStore() : this._defaultStore );
}
_store : Transactional
get comparator(){ return this._comparator; }
_comparator : ( a : R, b : R ) => number
_onChildrenChange( record : R, options : TransactionOptions = {}, initiator? : Transactional ){
// Ignore updates from nested transactions.
if( initiator === this ) return;
const { idAttribute } = this;
if( record.hasChanged( idAttribute ) ){
updateIndex( this._byId, record );
}
const isRoot = begin( this );
if( markAsDirty( this, options ) ){
// Forward change event from the record.
trigger2( this, 'change', record, options )
}
isRoot && commit( this );
}
get( objOrId : string | R | Object ) : R {
if( objOrId == null ) return;
if( typeof objOrId === 'object' ){
const id = objOrId[ this.idAttribute ];
return ( id !== void 0 && this._byId[ id ] ) || this._byId[ (<R>objOrId).cid ];
}
else{
return this._byId[ objOrId ];
}
}
each( iteratee : ( val : R, key : number ) => void, context? : any ){
const fun = bindContext( iteratee, context ),
{ models } = this;
for( let i = 0; i < models.length; i++ ){
fun( models[ i ], i );
}
}
forEach( iteratee : ( val : R, key? : number ) => void, context? : any ){
return this.each( iteratee, context );
}
every( iteratee : Predicate<R>, context? : any ) : boolean {
const fun = toPredicateFunction( iteratee, context ),
{ models } = this;
for( let i = 0; i < models.length; i++ ){
if( !fun( models[ i ], i ) ) return false;
}
return true;
}
filter( iteratee : Predicate<R>, context? : any ) : R[] {
const fun = toPredicateFunction( iteratee, context ),
{ models } = this;
return this.map( ( x, i ) => fun( x, i ) ? x : void 0 );
}
find( iteratee : Predicate<R>, context? : any ) : R {
const fun = toPredicateFunction( iteratee, context ),
{ models } = this;
for( let i = 0; i < models.length; i++ ){
if( fun( models[ i ], i ) ) return models[ i ];
}
return null;
}
some( iteratee : Predicate<R>, context? : any ) : boolean {
return Boolean( this.find( iteratee, context ) );
}
map< T >( iteratee : ( val : R, key : number ) => T, context? : any ) : T[]{
const fun = bindContext( iteratee, context ),
{ models } = this,
mapped = Array( models.length );
let j = 0;
for( let i = 0; i < models.length; i++ ){
const x = fun( models[ i ], i );
x === void 0 || ( mapped[ j++ ] = x );
}
mapped.length = j;
return mapped;
}
_validateNested( errors : {} ) : number {
// Don't validate if not aggregated.
if( this._shared ) return 0;
let count = 0;
this.each( record => {
const error = record.validationError;
if( error ){
errors[ record.cid ] = error;
count++;
}
});
return count;
}
model : typeof Record
// idAttribute extracted from the model type.
idAttribute : string
constructor( records? : ( R | {} )[], options : CollectionOptions = {}, shared? : number ){
super( _count++ );
this.models = [];
this._byId = {};
this.comparator = this.comparator;
if( options.comparator !== void 0 ){
this.comparator = options.comparator;
options.comparator = void 0;
}
this.model = this.model;
if( options.model ){
this.model = options.model;
options.model = void 0;
}
this.idAttribute = this.model.prototype.idAttribute; //TODO: Remove?
this._shared = shared || 0;
if( records ){
const elements = toElements( this, records, options );
emptySetTransaction( this, elements, options, true );
}
this.initialize.apply( this, arguments );
if( this._localEvents ) this._localEvents.subscribe( this, this );
}
initialize(){}
get length() : number { return this.models.length; }
first() : R { return this.models[ 0 ]; }
last() : R { return this.models[ this.models.length - 1 ]; }
at( a_index : number ) : R {
const index = a_index < 0 ? a_index + this.models.length : a_index;
return this.models[ index ];
}
// Deeply clone collection, optionally setting new owner.
clone( options : CloneOptions = {} ) : this {
const models = this._shared & ItemsBehavior.share ? this.models : this.map( model => model.clone() ),
copy : this = new (<any>this.constructor)( models, { model : this.model, comparator : this.comparator }, this._shared );
if( options.pinStore ) copy._defaultStore = this.getStore();
return copy;
}
toJSON( options? : object ) : any {
return this.models.map( model => model.toJSON( options ) );
}
// Apply bulk in-place object update in scope of ad-hoc transaction
set( elements : ElementsArg = [], options : TransactionOptions = {} ) : this {
if( (<any>options).add !== void 0 ){
this._log( 'warn', "Collection.set doesn't support 'add' option, behaving as if options.add === true.", options );
}
// Handle reset option here - no way it will be populated from the top as nested transaction.
if( options.reset ){
this.reset( elements, options )
}
else{
const transaction = this._createTransaction( elements, options );
transaction && transaction.commit();
}
return this;
}
/**
* Enable or disable live updates.
*
* `true` enables full collection synchronization.
* `false` cancel live updates.
* `json => true | false` - filter updates
*/
liveUpdates( enabled : LiveUpdatesOption ) : IOPromise<this> {
if( enabled ){
this.liveUpdates( false );
const filter = typeof enabled === 'function' ? enabled : () => true;
this._liveUpdates = {
updated : json => {
filter( json ) && this.add( json, { parse : true, merge : true } );
},
removed : id => this.remove( id )
};
return this.getEndpoint().subscribe( this._liveUpdates, this ).then( () => this );
}
else{
if( this._liveUpdates ){
this.getEndpoint().unsubscribe( this._liveUpdates, this );
this._liveUpdates = null;
}
}
}
_liveUpdates : object
fetch( a_options : { liveUpdates? : LiveUpdatesOption } & TransactionOptions = {} ) : IOPromise<this> {
const options = { parse : true, ...a_options },
endpoint = this.getEndpoint();
return startIO(
this,
endpoint.list( options, this ),
options,
json => {
let result : any = this.set( json, { parse : true, ...options } as TransactionOptions );
if( options.liveUpdates ){
result = this.liveUpdates( options.liveUpdates );
}
return result;
}
);
}
dispose() : void {
if( this._disposed ) return;
const aggregated = !this._shared;
for( let record of this.models ){
free( this, record );
if( aggregated ) record.dispose();
}
this.liveUpdates( false );
super.dispose();
}
reset( a_elements? : ElementsArg, options : TransactionOptions = {} ) : R[] {
const isRoot = begin( this ),
previousModels = this.models;
// Make all changes required, but be silent.
if( a_elements ){
emptySetTransaction( this, toElements( this, a_elements, options ), options, true );
}
else{
this._byId = {};
this.models = [];
}
markAsDirty( this, options );
options.silent || trigger2( this, 'reset', this, defaults( { previousModels : previousModels }, options ) );
// Dispose models which are not in the updated collection.
const { _byId } = this;
for( let toDispose of previousModels ){
_byId[ toDispose.cid ] || free( this, toDispose );
}
isRoot && commit( this );
return this.models;
}
// Add elements to collection.
add( a_elements : ElementsArg , options : AddOptions = {} ){
const elements = toElements( this, a_elements, options ),
transaction = this.models.length ?
addTransaction( this, elements, options ) :
emptySetTransaction( this, elements, options );
if( transaction ){
transaction.commit();
return transaction.added;
}
}
// Remove elements.
remove( recordsOrIds : any, options : CollectionOptions = {} ) : R[] | R {
if( recordsOrIds ){
return Array.isArray( recordsOrIds ) ?
removeMany( this, recordsOrIds, options ) as R[]:
removeOne( this, recordsOrIds, options ) as R;
}
return [];
}
// Apply bulk object update without any notifications, and return open transaction.
// Used internally to implement two-phase commit.
_createTransaction( a_elements : ElementsArg, options : TransactionOptions = {} ) : CollectionTransaction | void {
const elements = toElements( this, a_elements, options );
if( this.models.length ){
return options.remove === false ?
addTransaction( this, elements, options, true ) :
setTransaction( this, elements, options );
}
else{
return emptySetTransaction( this, elements, options );
}
}
static _attribute = AggregatedType;
/***********************************
* Collection manipulation methods
*/
pluck( key : keyof R ) : any[] {
return this.models.map( model => model[ key ] );
}
sort( options : TransactionOptions = {} ) : this {
if( sortElements( this, options ) ){
const isRoot = begin( this );
if( markAsDirty( this, options ) ){
trigger2( this, 'sort', this, options );
}
isRoot && commit( this );
}
return this;
}
// Add a model to the end of the collection.
push(model : ElementsArg, options : CollectionOptions ) {
return this.add(model, assign({at: this.length}, options));
}
// Remove a model from the end of the collection.
pop( options : CollectionOptions ) : R {
var model = this.at(this.length - 1);
this.remove(model, { unset : true, ...options });
return model;
}
// Remove and return given model.
// TODO: do not dispose the model for aggregated collection.
unset( modelOrId : R | string, options? ) : R {
const value = this.get( modelOrId );
this.remove( modelOrId, { unset : true, ...options } );
return value;
}
// Add a model to the beginning of the collection.
unshift(model : ElementsArg, options : CollectionOptions ) {
return this.add(model, assign({at: 0}, options));
}
// Remove a model from the beginning of the collection.
shift( options? : CollectionOptions ) : R {
var model = this.at(0);
this.remove( model, { unset : true, ...options } );
return model;
}
// Slice out a sub-array of models from the collection.
slice() : R[] {
return slice.apply(this.models, arguments);
}
indexOf( modelOrId : any ) : number {
const record = this.get( modelOrId );
return this.models.indexOf( record );
}
modelId( attrs : {} ) : any {
return attrs[ this.model.prototype.idAttribute ];
}
// Toggle model in collection.
toggle( model : R, a_next? : boolean ) : boolean {
var prev = Boolean( this.get( model ) ),
next = a_next === void 0 ? !prev : Boolean( a_next );
if( prev !== next ){
if( prev ){
this.remove( model );
}
else{
this.add( model );
}
}
return next;
}
_log( level : tools.LogLevel, text : string, value ) : void {
tools.log( level, `[Collection Update] ${ this.model.prototype.getClassName() }.${ this.getClassName() }: ` + text, {
Argument : value,
'Attributes spec' : this.model.prototype._attributes
});
}
getClassName() : string {
return super.getClassName() || 'Collection';
}
}
export type LiveUpdatesOption = boolean | ( ( x : any ) => boolean );
export type ElementsArg = Object | Record | Object[] | Record[];
// TODO: make is safe for parse to return null (?)
function toElements( collection : Collection, elements : ElementsArg, options : CollectionOptions ) : Elements {
const parsed = options.parse ? collection.parse( elements, options ) : elements;
return Array.isArray( parsed ) ? parsed : [ parsed ];
}
createSharedTypeSpec( Collection, SharedType );
Record.Collection = <any>Collection;
function bindContext( fun : Function, context? : any ){
return context !== void 0 ? ( v, k ) => fun.call( context, v, k ) : fun;
}
function toPredicateFunction<R>( iteratee : Predicate<R>, context : any ){
if( typeof iteratee === 'object' ){
// Wrap object to the predicate...
return x => {
for( let key in iteratee as any ){
if( iteratee[ key ] !== x[ key ] )
return false;
}
return true;
}
}
return bindContext( iteratee, context );
} | the_stack |
import find from '../polyfills/find.js';
import arrayFrom from '../polyfills/arrayFrom.js';
import objectValues from '../polyfills/objectValues.js';
import { SYMBOL_TO_STRING_TAG } from '../polyfills/symbols.js';
import inspect from '../jsutils/inspect.js';
import toObjMap from '../jsutils/toObjMap.js';
import devAssert from '../jsutils/devAssert.js';
import instanceOf from '../jsutils/instanceOf.js';
import isObjectLike from '../jsutils/isObjectLike.js';
import { __Schema } from './introspection.js';
import { GraphQLDirective, isDirective, specifiedDirectives } from './directives.js';
import { isObjectType, isInterfaceType, isUnionType, isInputObjectType, getNamedType } from './definition.js';
/**
* Test if the given value is a GraphQL schema.
*/
// eslint-disable-next-line no-redeclare
export function isSchema(schema) {
return instanceOf(schema, GraphQLSchema);
}
export function assertSchema(schema) {
if (!isSchema(schema)) {
throw new Error(`Expected ${inspect(schema)} to be a GraphQL schema.`);
}
return schema;
}
/**
* Schema Definition
*
* A Schema is created by supplying the root types of each type of operation,
* query and mutation (optional). A schema definition is then supplied to the
* validator and executor.
*
* Example:
*
* const MyAppSchema = new GraphQLSchema({
* query: MyAppQueryRootType,
* mutation: MyAppMutationRootType,
* })
*
* Note: When the schema is constructed, by default only the types that are
* reachable by traversing the root types are included, other types must be
* explicitly referenced.
*
* Example:
*
* const characterInterface = new GraphQLInterfaceType({
* name: 'Character',
* ...
* });
*
* const humanType = new GraphQLObjectType({
* name: 'Human',
* interfaces: [characterInterface],
* ...
* });
*
* const droidType = new GraphQLObjectType({
* name: 'Droid',
* interfaces: [characterInterface],
* ...
* });
*
* const schema = new GraphQLSchema({
* query: new GraphQLObjectType({
* name: 'Query',
* fields: {
* hero: { type: characterInterface, ... },
* }
* }),
* ...
* // Since this schema references only the `Character` interface it's
* // necessary to explicitly list the types that implement it if
* // you want them to be included in the final schema.
* types: [humanType, droidType],
* })
*
* Note: If an array of `directives` are provided to GraphQLSchema, that will be
* the exact list of directives represented and allowed. If `directives` is not
* provided then a default set of the specified directives (e.g. @include and
* @skip) will be used. If you wish to provide *additional* directives to these
* specified directives, you must explicitly declare them. Example:
*
* const MyAppSchema = new GraphQLSchema({
* ...
* directives: specifiedDirectives.concat([ myCustomDirective ]),
* })
*
*/
export class GraphQLSchema {
// Used as a cache for validateSchema().
constructor(config) {
// If this schema was built from a source known to be valid, then it may be
// marked with assumeValid to avoid an additional type system validation.
this.__validationErrors = config.assumeValid === true ? [] : undefined; // Check for common mistakes during construction to produce early errors.
devAssert(isObjectLike(config), 'Must provide configuration object.');
devAssert(!config.types || Array.isArray(config.types), `"types" must be Array if provided but got: ${inspect(config.types)}.`);
devAssert(!config.directives || Array.isArray(config.directives), '"directives" must be Array if provided but got: ' + `${inspect(config.directives)}.`);
this.description = config.description;
this.extensions = config.extensions && toObjMap(config.extensions);
this.astNode = config.astNode;
this.extensionASTNodes = config.extensionASTNodes;
this._queryType = config.query;
this._mutationType = config.mutation;
this._subscriptionType = config.subscription; // Provide specified directives (e.g. @include and @skip) by default.
this._directives = config.directives ?? specifiedDirectives; // To preserve order of user-provided types, we add first to add them to
// the set of "collected" types, so `collectReferencedTypes` ignore them.
const allReferencedTypes = new Set(config.types);
if (config.types != null) {
for (const type of config.types) {
// When we ready to process this type, we remove it from "collected" types
// and then add it together with all dependent types in the correct position.
allReferencedTypes.delete(type);
collectReferencedTypes(type, allReferencedTypes);
}
}
if (this._queryType != null) {
collectReferencedTypes(this._queryType, allReferencedTypes);
}
if (this._mutationType != null) {
collectReferencedTypes(this._mutationType, allReferencedTypes);
}
if (this._subscriptionType != null) {
collectReferencedTypes(this._subscriptionType, allReferencedTypes);
}
for (const directive of this._directives) {
// Directives are not validated until validateSchema() is called.
if (isDirective(directive)) {
for (const arg of directive.args) {
collectReferencedTypes(arg.type, allReferencedTypes);
}
}
}
collectReferencedTypes(__Schema, allReferencedTypes); // Storing the resulting map for reference by the schema.
this._typeMap = Object.create(null);
this._subTypeMap = Object.create(null); // Keep track of all implementations by interface name.
this._implementationsMap = Object.create(null);
for (const namedType of arrayFrom(allReferencedTypes)) {
if (namedType == null) {
continue;
}
const typeName = namedType.name;
devAssert(typeName, 'One of the provided types for building the Schema is missing a name.');
if (this._typeMap[typeName] !== undefined) {
throw new Error(`Schema must contain uniquely named types but contains multiple types named "${typeName}".`);
}
this._typeMap[typeName] = namedType;
if (isInterfaceType(namedType)) {
// Store implementations by interface.
for (const iface of namedType.getInterfaces()) {
if (isInterfaceType(iface)) {
let implementations = this._implementationsMap[iface.name];
if (implementations === undefined) {
implementations = this._implementationsMap[iface.name] = {
objects: [],
interfaces: []
};
}
implementations.interfaces.push(namedType);
}
}
} else if (isObjectType(namedType)) {
// Store implementations by objects.
for (const iface of namedType.getInterfaces()) {
if (isInterfaceType(iface)) {
let implementations = this._implementationsMap[iface.name];
if (implementations === undefined) {
implementations = this._implementationsMap[iface.name] = {
objects: [],
interfaces: []
};
}
implementations.objects.push(namedType);
}
}
}
}
}
getQueryType() {
return this._queryType;
}
getMutationType() {
return this._mutationType;
}
getSubscriptionType() {
return this._subscriptionType;
}
getTypeMap() {
return this._typeMap;
}
getType(name) {
return this.getTypeMap()[name];
}
getPossibleTypes(abstractType) {
return isUnionType(abstractType) ? abstractType.getTypes() : this.getImplementations(abstractType).objects;
}
getImplementations(interfaceType) {
const implementations = this._implementationsMap[interfaceType.name];
return implementations ?? {
objects: [],
interfaces: []
};
} // @deprecated: use isSubType instead - will be removed in v16.
isPossibleType(abstractType, possibleType) {
return this.isSubType(abstractType, possibleType);
}
isSubType(abstractType, maybeSubType) {
let map = this._subTypeMap[abstractType.name];
if (map === undefined) {
map = Object.create(null);
if (isUnionType(abstractType)) {
for (const type of abstractType.getTypes()) {
map[type.name] = true;
}
} else {
const implementations = this.getImplementations(abstractType);
for (const type of implementations.objects) {
map[type.name] = true;
}
for (const type of implementations.interfaces) {
map[type.name] = true;
}
}
this._subTypeMap[abstractType.name] = map;
}
return map[maybeSubType.name] !== undefined;
}
getDirectives() {
return this._directives;
}
getDirective(name) {
return find(this.getDirectives(), directive => directive.name === name);
}
toConfig() {
return {
description: this.description,
query: this.getQueryType(),
mutation: this.getMutationType(),
subscription: this.getSubscriptionType(),
types: objectValues(this.getTypeMap()),
directives: this.getDirectives().slice(),
extensions: this.extensions,
astNode: this.astNode,
extensionASTNodes: this.extensionASTNodes ?? [],
assumeValid: this.__validationErrors !== undefined
};
} // $FlowFixMe Flow doesn't support computed properties yet
get [SYMBOL_TO_STRING_TAG]() {
return 'GraphQLSchema';
}
}
function collectReferencedTypes(type, typeSet) {
const namedType = getNamedType(type);
if (!typeSet.has(namedType)) {
typeSet.add(namedType);
if (isUnionType(namedType)) {
for (const memberType of namedType.getTypes()) {
collectReferencedTypes(memberType, typeSet);
}
} else if (isObjectType(namedType) || isInterfaceType(namedType)) {
for (const interfaceType of namedType.getInterfaces()) {
collectReferencedTypes(interfaceType, typeSet);
}
for (const field of objectValues(namedType.getFields())) {
collectReferencedTypes(field.type, typeSet);
for (const arg of field.args) {
collectReferencedTypes(arg.type, typeSet);
}
}
} else if (isInputObjectType(namedType)) {
for (const field of objectValues(namedType.getFields())) {
collectReferencedTypes(field.type, typeSet);
}
}
}
return typeSet;
} | the_stack |
import { ActionsInTestEnum, IInputNodeInfo, InputNodeTypeEnum } from "@shared/constants/recordedActions";
import { DOM } from "../utils/dom";
import EventsController from "../eventsController";
import { RelevantHoverDetection } from "./relevantHoverDetection";
import { v4 as uuidv4 } from "uuid";
import { sendRecorderReadySignal, turnOffInspectMode, turnOnElementMode, turnOnInspectMode } from "../host-proxy";
import { ElementsIdMap } from "../elementsMap";
const KEYS_TO_TRACK_FOR_INPUT = new Set(["Enter", "Escape", "Tab"]);
const KEYS_TO_TRACK_FOR_TEXTAREA = new Set([
// Enter types a line break, shouldn't be a press.
"Escape",
"Tab",
]);
type iPerformActionMeta = any;
export default class EventRecording {
defaultState: any = {
targetElement: null,
sessionGoingOn: false,
showingEventsBox: false,
pinned: false,
};
private state: any;
private eventsController: EventsController;
private _overlayCover: any;
private isInspectorMoving = false;
private pointerEventsMap: Array<{ data: PointerEvent }> = [];
private recordedHoverArr: Array<any> = [];
private hoveringState: any = {
element: null,
time: Date.now(),
};
private scrollTimer: any = null;
private lastScrollFireTime = 0;
private resetUserEventsToDefaultCallback: any = undefined;
private releventHoverDetectionManager: RelevantHoverDetection;
private _pageRecordedEventsArr = [];
private _clickEvents = [];
constructor(options = {} as any) {
this.state = {
...this.defaultState,
};
this.onRightClick = this.onRightClick.bind(this);
this.handleFocus = this.handleFocus.bind(this);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.handleMouseOver = this.handleMouseOver.bind(this);
this.handleMouseOut = this.handleMouseOut.bind(this);
this.handleScroll = this.handleScroll.bind(this);
this.handleBeforeNavigation = this.handleBeforeNavigation.bind(this);
this.handlePointerEnter = this.handlePointerEnter.bind(this);
this.handleCrusherHoverTrace = this.handleCrusherHoverTrace.bind(this);
this.handleElementSelected = this.handleElementSelected.bind(this);
this.trackAndSaveRelevantHover = this.trackAndSaveRelevantHover.bind(this);
this.getHoverDependentNodes = this.getHoverDependentNodes.bind(this);
this.clickThroughElectron = this.clickThroughElectron.bind(this);
this.hoverThroughElectron = this.hoverThroughElectron.bind(this);
this.handleElementInput = this.handleElementInput.bind(this);
this.handleElementChange = this.handleElementChange.bind(this);
this.releventHoverDetectionManager = new RelevantHoverDetection();
this.turnOnElementModeInParentFrame = this.turnOnElementModeInParentFrame.bind(this);
this.handleWindowClick = this.handleWindowClick.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
this.eventsController = new EventsController(this);
this.pollInterval = this.pollInterval.bind(this);
}
getState() {
return this.state;
}
initNodes() {
console.debug("Registering all nodes");
this._overlayCover = document.querySelector("#overlay_cover");
}
updateEventTarget(target: HTMLElement, event: any) {
this.state = {
...this.state,
targetElement: target,
};
}
elementsAtLocation(x: number, y: number) {
const stack = [];
let el;
do {
el = document.elementFromPoint(x, y);
if (!el) {
break;
}
stack.push(el);
if (stack.length > 5) {
break;
}
el?.classList.add("pointerEventsNone");
} while (el?.tagName !== "HTML");
// clean up
for (let i = 0; i < stack.length; i += 1) stack[i]?.classList.remove("pointerEventsNone");
return stack;
}
executeCustomElementScript(script: string) {
return new Function(
"element",
`return new Promise(async function (resolve, reject) {
try{
const l = ${script};
resolve(l(element));
} catch(err){
reject(err);
}
});`,
)(this.state.targetElement);
}
getOffset(el: any) {
let _x = 0;
let _y = 0;
while (el && !isNaN(el.offsetLeft) && !isNaN(el.offsetTop)) {
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return { top: _y, left: _x };
}
highlightNode(_target: any, event: any = null) {
this._overlayCover.style.position = "absolute";
let target = _target;
if (event) {
const elements = this.elementsAtLocation(event.clientX, event.clientY);
if (elements && elements.length > 1 && elements[0].id === "overlay_cover") {
target = elements[1];
}
}
this._overlayCover.style.top = window.scrollY + target.getBoundingClientRect().y + "px";
this._overlayCover.style.left = window.scrollX + target.getBoundingClientRect().x + "px";
this._overlayCover.style.width = target.getBoundingClientRect().width + "px";
this._overlayCover.style.height = target.getBoundingClientRect().height + "px";
this._overlayCover.style["z-index"] = 299999999;
this._overlayCover.style.outlineStyle = "solid";
this._overlayCover.style.outlineColor = "rgb(226, 223, 108)";
this._overlayCover.style.outlineWidth = "1px";
}
removeHighLightFromNode(target: HTMLElement) {
// @FIXME: What if the target had set outlineColor and outlineStyleBefore.
if (target) {
target.style.outlineStyle = "none";
target.style.outlineColor = "none";
target.style.outlineWidth = "0px";
}
}
clickThroughElectron(node) {
console.log("CRUSHER_CLICK_ELEMENT", node);
return true;
}
hoverThroughElectron(node) {
console.log("CRUSHER_HOVER_ELEMENT", node);
return true;
}
enableJavascriptEvents() {
if (this.resetUserEventsToDefaultCallback) {
this.resetUserEventsToDefaultCallback();
this.resetUserEventsToDefaultCallback = null;
}
}
performSimulatedClick() {
DOM.removeAllTargetBlankFromLinks();
this.eventsController.simulateClickOnElement(this.state.targetElement);
}
performSimulatedHover() {
this.eventsController.simulateHoverOnElement(this.state.targetElement);
}
onRightClick(event: Event) {
event.preventDefault();
if (this.isInspectorMoving) {
this.enableJavascriptEvents();
this.turnInspectModeOffInParentFrame();
this.unpin();
} else {
this.turnInspectModeOnInParentFrame();
const eventExceptions = {
mousemove: this.handleMouseMove.bind(this),
mouseover: this.handleMouseMove.bind(this),
pointerenter: this.handlePointerEnter.bind(this),
mouseout: this.handleMouseOut.bind(this),
click: this.handleWindowClick.bind(this),
};
if (!this.resetUserEventsToDefaultCallback) {
this.resetUserEventsToDefaultCallback = DOM.disableAllUserEvents(eventExceptions);
}
}
}
handleMouseMove(event: MouseEvent) {
const { targetElement } = this.state;
if (!this.state.pinned) {
// Remove Highlight from last element hovered
this.removeHighLightFromNode(targetElement);
// this.updateEventTarget(event.target as HTMLElement, event);
}
}
handleMouseOver(event: MouseEvent) {
if (this.hoveringState !== event.target && (event.target as any).id !== "overlay_cover") {
this.hoveringState = {
element: event.target,
time: Date.now(),
};
}
}
handleMouseOut(event: MouseEvent) {
if (this.hoveringState.element === event.target) {
this.hoveringState = {
element: null,
time: Date.now(),
};
}
}
handleScroll(event: any) {
if (!event.isFromUser) return;
const minScrollTime = 100;
const now = new Date().getTime();
// console.log("Scrolled, ", event.target);
// eslint-disable-next-line @typescript-eslint/no-this-alias
const _this = this;
const processScroll = () => {
const target = event.target;
const isDocumentScrolled = event.target === document;
if (isDocumentScrolled) {
return _this.eventsController.saveCapturedEventInBackground(ActionsInTestEnum.PAGE_SCROLL, null, window.scrollY);
}
const isRecorderCover = target.getAttribute("data-recorder-cover");
if (!isRecorderCover && !event.simulatedEvent) {
const inputNodeInfo = this._getInputNodeInfo(event.target);
if (inputNodeInfo && [InputNodeTypeEnum.CONTENT_EDITABLE, InputNodeTypeEnum.INPUT, InputNodeTypeEnum.TEXTAREA].includes(inputNodeInfo.type))
return;
// @TODO: Need a proper way to detect real and fake scroll events
_this.eventsController.saveCapturedEventInBackground(ActionsInTestEnum.ELEMENT_SCROLL, event.target, event.target.scrollTop);
} else {
return event.preventDefault();
}
};
if (!this.scrollTimer) {
if (now - this.lastScrollFireTime > 3 * minScrollTime) {
processScroll(); // fire immediately on first scroll
this.lastScrollFireTime = now;
}
this.scrollTimer = setTimeout(function () {
_this.scrollTimer = null;
_this.lastScrollFireTime = window.performance.now();
processScroll();
}, minScrollTime);
}
}
pollInterval() {
if (this.hoveringState.element && this.hoveringState.time) {
const diffInMilliSeconds = Date.now() - this.hoveringState.time;
const activeFocusElement: any = document.activeElement;
if (diffInMilliSeconds > 1000 && activeFocusElement.tagName !== "INPUT") {
// Only record hover if not in input mode focus.
// this.eventsController.saveCapturedEventInBackground(
// ActionsInTestEnum.HOVER,
// this.hoveringState.element,
// );
this.hoveringState = {
element: null,
time: Date.now(),
};
}
}
}
async getHoverDependentNodes(_element: HTMLElement, baseLineTimeStamp: number | null = null): Promise<Array<any>> {
// Use parent svg element if element is an svg element
const element = _element instanceof SVGElement && _element.tagName.toLocaleLowerCase() !== "svg" ? _element.ownerSVGElement : _element;
const needsOtherActions = await this.releventHoverDetectionManager.isCoDependentNode(element, baseLineTimeStamp, this._clickEvents);
if (needsOtherActions) {
const hoverNodesRecord = this.releventHoverDetectionManager.getParentDOMMutations(element, baseLineTimeStamp, this._clickEvents);
const hoverNodes = hoverNodesRecord.map((record) => record.eventNode);
if (hoverNodes.length && hoverNodes[hoverNodes.length - 1] === element) {
hoverNodes.pop();
}
return hoverNodes.filter((node: HTMLElement) => {
const boundingBox = node.getBoundingClientRect();
const centerX = boundingBox.x + boundingBox.width / 2;
const centerY = boundingBox.y + boundingBox.height / 2;
const nodeAtCenter = document.elementFromPoint(centerX, centerY);
return nodeAtCenter === node || node.contains(nodeAtCenter);
});
}
return [];
}
async trackAndSaveRelevantHover(element, baseLineTimeStamp: number | null = null) {
const hoverNodes = this.eventsController.getRelevantHoverRecordsFromSavedEvents(await this.getHoverDependentNodes(element, baseLineTimeStamp), element);
for (let i = 0; i < hoverNodes.length; i++) {
await this.eventsController.saveCapturedEventInBackground(ActionsInTestEnum.HOVER, hoverNodes[i], "", null, true);
}
}
async turnOnElementModeInParentFrame(selectedElement = this.state.targetElement) {
this.isInspectorMoving = false;
const element =
selectedElement instanceof SVGElement && selectedElement.tagName.toLocaleLowerCase() !== "svg" ? selectedElement.ownerSVGElement : selectedElement;
// const capturedElementScreenshot = await html2canvas(element).then((canvas: any) => canvas.toDataURL());
const hoverDependedNodes = this.eventsController.getRelevantHoverRecordsFromSavedEvents(await this.getHoverDependentNodes(element), element) as HTMLElement[];
const dependentHovers = hoverDependedNodes.map((node) => {
return {
uniqueElementId: ElementsIdMap.getUniqueId(node),
selectors: this.eventsController.getSelectors(selectedElement),
}
});
turnOnElementMode({
uniqueElementId: ElementsIdMap.getUniqueId(selectedElement),
selectors: this.eventsController.getSelectors(selectedElement),
dependentHovers: dependentHovers,
});
}
unpin() {
this.state.pinned = false;
if (this._overlayCover) {
this._overlayCover.classList.remove("pointerEventsNone");
this._overlayCover.style.left = "0px";
this._overlayCover.style.top = "0px";
this._overlayCover.style.width = "0px";
this._overlayCover.style.height = "0px";
}
}
stopRightClickFocusLoose(event: any) {
if (event.which === 3) {
event.preventDefault();
}
this.handleWindowClick(event);
}
private checkIfElementIsAnchored(target: HTMLElement) {
// Check if element has some a tag parent
let parent = target.parentElement;
if (target.tagName.toLocaleLowerCase() === "a") return target;
while (parent) {
if (parent.tagName.toLowerCase() === "a") {
return parent;
}
parent = parent.parentElement;
}
return false;
}
// eslint-disable-next-line consistent-return
async handleWindowClick(event: any) {
event.timestamp = Date.now();
if (event.which === 3) {
return this.onRightClick(event);
}
if (event.which === 2) return;
let target = event.target;
const mainAnchorNode = this.checkIfElementIsAnchored(target);
if (mainAnchorNode) target = mainAnchorNode;
const inputNodeInfo = this._getInputNodeInfo(target);
const tagName = target.tagName.toLowerCase();
if (["option", "select"].includes(tagName)) return;
const closestLink: HTMLAnchorElement = target.tagName === "a" ? target : target.closest("a");
// If clientX and clientY is 0 it may mean that the event is not triggered
// by user. Found during creating tests for ielts search
if (!event.simulatedEvent && event.isTrusted && (event.clientX || event.clientY)) {
this._clickEvents.push(event);
await this.trackAndSaveRelevantHover(target, event.timeStamp);
await this.eventsController.saveCapturedEventInBackground(ActionsInTestEnum.CLICK, target, {
inputInfo: tagName === "label" ? inputNodeInfo : null,
});
}
if (closestLink && closestLink.tagName.toLowerCase() === "a") {
const href = closestLink.getAttribute("href");
if (href) {
window.location.href = href;
return event.preventDefault();
}
}
}
handleKeyDown(event: KeyboardEvent) {
const key = event.key;
if (KEYS_TO_TRACK_FOR_INPUT.has(key)) {
this.eventsController.saveCapturedEventInBackground(ActionsInTestEnum.PRESS, event.target, key);
}
}
handleFocus(event: FocusEvent) {
// const target = event.target as HTMLElement;
// if ((target as any) != window && ["textarea", "input"].includes(target.tagName.toLowerCase())) {
// this.eventsController.saveCapturedEventInBackground(ActionsInTestEnum.ELEMENT_FOCUS, target, true);
// }
}
handlePointerEnter(event: PointerEvent) {
const timeNow = window.performance.now();
if (this.scrollTimer) {
return;
}
const lastEvent = this.recordedHoverArr.length > 0 ? this.recordedHoverArr[this.recordedHoverArr.length - 1] : null;
if (lastEvent) {
const diff = timeNow - lastEvent.timeStamp;
if (diff > 200) {
this.pointerEventsMap.push({ data: event });
this.recordedHoverArr.push(event);
}
return;
}
this.pointerEventsMap.push({ data: event });
this.recordedHoverArr.push(event);
}
handleCrusherHoverTrace(
event: CustomEvent & {
detail: { type: string; key: string; eventNode: Node; targetNode: Node };
},
) {
this.releventHoverDetectionManager.registerDOMMutation({
...event.detail,
});
}
handleElementSelected(event: CustomEvent & { detail: { element: HTMLElement } }) {
this.state.targetElement = event.detail.element;
this.turnOnElementModeInParentFrame(event.detail.element);
this.enableJavascriptEvents();
}
_getInputNodeInfo(eventNode: HTMLElement): IInputNodeInfo | null {
const nodeTagName = eventNode.tagName.toLowerCase();
switch (nodeTagName) {
case "select": {
const selectElement = event.target as HTMLSelectElement;
const selectedOptions = selectElement.selectedOptions ? Array.from(selectElement.selectedOptions) : [];
return { type: InputNodeTypeEnum.SELECT, value: selectedOptions.map((option, index) => option.index), name: selectElement.name };
}
case "input": {
const inputElement = eventNode as HTMLInputElement;
const inputType = inputElement.type;
const inputName = inputElement.name;
const parentForm = inputElement.form ? inputElement.form : document.body;
switch (inputType) {
case "file":
return null;
case "checkbox":
return { type: InputNodeTypeEnum.CHECKBOX, value: inputElement.checked, name: inputName, inputType: inputType };
case "radio":
return { type: InputNodeTypeEnum.RADIO, value: inputElement.checked, name: inputName, inputType };
default:
// color, date, datetime, datetime-local, email, month, number, password, range, search, tel, text, time, url, week
return { type: InputNodeTypeEnum.INPUT, value: inputElement.value, name: inputName, inputType: inputType.toLowerCase() };
}
}
case "textarea": {
const textAreaElement = eventNode as HTMLTextAreaElement;
return { type: InputNodeTypeEnum.TEXTAREA, value: textAreaElement.value, name: textAreaElement.name };
}
default: {
if (!eventNode.isContentEditable) return null;
const contentEditableElement = eventNode as HTMLElement;
return { type: InputNodeTypeEnum.CONTENT_EDITABLE, name: contentEditableElement.id, value: contentEditableElement.innerText };
}
}
}
async _getUniqueNodeId(node: Node) {
const id = uuidv4();
(window as any)[id] = node;
return id;
}
async handleElementInput(event: InputEvent) {
if (!event.isTrusted) return;
const inputNodeInfo = this._getInputNodeInfo(event.target as HTMLElement);
if (!inputNodeInfo || ![InputNodeTypeEnum.INPUT, InputNodeTypeEnum.TEXTAREA, InputNodeTypeEnum.CONTENT_EDITABLE].includes(inputNodeInfo.type)) return;
const labelsArr = (event.target as HTMLInputElement).labels ? Array.from((event.target as HTMLInputElement).labels) : [];
const labelsUniqId = [];
for (const label of labelsArr) {
labelsUniqId.push(await this._getUniqueNodeId(label));
}
this.eventsController.saveCapturedEventInBackground(ActionsInTestEnum.ADD_INPUT, event.target, { ...inputNodeInfo, labelsUniqId });
}
async handleElementChange(event: InputEvent) {
if (!event.isTrusted) return;
const inputNodeInfo = await this._getInputNodeInfo(event.target as HTMLElement);
if (!inputNodeInfo) return;
if ([InputNodeTypeEnum.INPUT, InputNodeTypeEnum.CONTENT_EDITABLE].includes(inputNodeInfo.type)) return;
const labelsArr = (event.target as HTMLInputElement).labels ? Array.from((event.target as HTMLInputElement).labels) : [];
const labelsUniqId = [];
for (const label of labelsArr) {
labelsUniqId.push(await this._getUniqueNodeId(label));
}
this.eventsController.saveCapturedEventInBackground(ActionsInTestEnum.ADD_INPUT, event.target, { ...inputNodeInfo, labelsUniqId });
}
registerNodeListeners() {
window.addEventListener("mousemove", this.handleMouseMove, true);
window.addEventListener("mouseover", this.handleMouseOver, true);
window.addEventListener("mouseout", this.handleMouseOut, true);
window.addEventListener("focus", this.handleFocus, true);
window.addEventListener("crusherHoverTrace", this.handleCrusherHoverTrace);
window.addEventListener("elementSelected", this.handleElementSelected);
window.addEventListener("input", this.handleElementInput);
window.addEventListener("change", this.handleElementChange);
document.body.addEventListener("pointerenter", this.handlePointerEnter, true);
window.addEventListener("scroll", this.handleScroll, true);
window.onbeforeunload = this.handleBeforeNavigation;
window.addEventListener("keydown", this.handleKeyDown, true);
window.addEventListener("mousedown", this.stopRightClickFocusLoose.bind(this), true);
let lastPush = Date.now();
window.history.pushState = new Proxy(window.history.pushState, {
apply: async (target, thisArg, argArray) => {
this.releventHoverDetectionManager.reset();
const out = target.apply(thisArg, argArray);
if (argArray[0] && (Date.now() - lastPush) > 1000) {
lastPush = Date.now();
this.eventsController.saveCapturedEventInBackground(
ActionsInTestEnum.WAIT_FOR_NAVIGATION,
null,
argArray[2]
? !this.isAbsoluteURL(argArray[2])
? new URL(argArray[2], document.baseURI).toString()
: argArray[2]
: window.location.href,
);
}
return out;
},
});
window.history.replaceState = new Proxy(window.history.pushState, {
apply: async (target, thisArg, argArray) => {
this.releventHoverDetectionManager.reset();
const out = target.apply(thisArg, argArray);
if (argArray[0] & (Date.now() - lastPush) > 1000) {
lastPush = Date.now();
this.eventsController.saveCapturedEventInBackground(
ActionsInTestEnum.WAIT_FOR_NAVIGATION,
null,
argArray[2]
? !this.isAbsoluteURL(argArray[2])
? new URL(argArray[2], document.baseURI).toString()
: argArray[2]
: window.location.href,
);
}
return out;
},
});
setInterval(this.pollInterval, 300);
}
removeNodeListeners() {
window.removeEventListener("mousemove", this.handleMouseMove, true);
}
boot(isFirstTime = false) {
console.log("Starting...");
this.initNodes();
if (isFirstTime) {
const currentURL = new URL(window.location.href);
currentURL.searchParams.delete("__crusherAgent__");
}
sendRecorderReadySignal();
this.registerNodeListeners();
}
private isAbsoluteURL(url: string) {
const rgx = new RegExp("^(?:[a-z]+:)?//", "i");
return rgx.test(url);
}
handleBeforeNavigation() {
const activeElementHref = (document.activeElement as any).getAttribute("href");
if (activeElementHref) {
this.eventsController.saveCapturedEventInBackground(
ActionsInTestEnum.WAIT_FOR_NAVIGATION,
document.body,
activeElementHref && activeElementHref.trim() !== ""
? !this.isAbsoluteURL(activeElementHref)
? new URL(activeElementHref, document.baseURI).toString()
: activeElementHref
: window.location.href.toString(),
);
} else {
this.eventsController.saveCapturedEventInBackground(ActionsInTestEnum.WAIT_FOR_NAVIGATION, document.body, {
url: "",
isBeforeNavigation: true,
});
}
}
turnInspectModeOnInParentFrame() {
this.isInspectorMoving = true;
turnOnInspectMode();
}
turnInspectModeOffInParentFrame() {
this.isInspectorMoving = false;
turnOffInspectMode();
}
toggleInspectorInParentFrame() {
if (this.isInspectorMoving) {
this.turnInspectModeOffInParentFrame();
} else {
this.turnInspectModeOnInParentFrame();
}
console.info("Info Overlay booted up");
}
shutdown() {
console.debug("Shutting down Recording Overlay");
this.removeNodeListeners();
this.state = {
...this.state,
sessionGoingOn: false,
};
}
} | the_stack |
import { expect } from "chai";
import * as _ from "lodash";
import * as nock from "nock";
import * as querystring from "querystring";
import {
AlexaEvent,
AlexaPlatform,
AlexaReply,
EventBuilder,
GARBAGE_COLLECTION_DAY,
GARBAGE_TYPE,
MEDIA_CONTENT_METHOD,
MEDIA_CONTENT_TYPE,
MediaContentEventBuilder,
MESSAGE_ALERT_FRESHNESS,
MESSAGE_ALERT_STATUS,
MESSAGE_ALERT_URGENCY,
MessageAlertEventBuilder,
OCCASION_CONFIRMATION_STATUS,
OCCASION_TYPE,
OccasionEventBuilder,
ORDER_STATUS,
OrderStatusEventBuilder,
ProactiveEvents,
SOCIAL_GAME_INVITE_TYPE,
SOCIAL_GAME_OFFER,
SOCIAL_GAME_RELATIONSHIP_TO_INVITEE,
SocialGameInviteEventBuilder,
SportsEventBuilder,
TrashCollectionAlertEventBuilder,
VoxaApp,
WEATHER_ALERT_TYPE,
WeatherAlertEventBuilder,
} from "../../src";
import { AlexaRequestBuilder } from "./../tools";
import { variables } from "./../variables";
import { views } from "./../views";
const rb = new AlexaRequestBuilder();
const clientId: string = "clientId";
const clientSecret: string = "clientSecret";
describe("ProactiveEvents", () => {
const tokenResponse = {
access_token: "Atc|MQEWYJxEnP3I1ND03ZzbY_NxQkA7Kn7Aioev_OfMRcyVQ4NxGzJMEaKJ8f0lSOiV-yW270o6fnkI",
expires_in: 3600,
scope: "alexa::proactive_events",
token_type: "Bearer",
};
let reqheaders: any = {};
beforeEach(() => {
reqheaders = {
"accept": "application/json",
"content-length": 105,
"content-type": "application/x-www-form-urlencoded",
"host": "api.amazon.com",
};
const bodyRequest = {
client_id: clientId,
client_secret: clientSecret,
grant_type: "client_credentials",
scope: "alexa::proactive_events",
};
const body = decodeURIComponent(querystring.stringify(bodyRequest));
nock("https://api.amazon.com", { reqheaders })
.post("/auth/O2/token", body)
.reply(200, JSON.stringify(tokenResponse));
});
afterEach(() => {
nock.cleanAll();
});
it("should get a new access token and send a WeatherAlert event", async () => {
reqheaders = {
"accept": "application/json",
"authorization": `Bearer ${tokenResponse.access_token}`,
"content-length": 389,
"content-type": "application/json",
"host": "api.amazonalexa.com",
};
const userId = "userId";
const endpoint: string = "https://api.amazonalexa.com";
const event: WeatherAlertEventBuilder = new WeatherAlertEventBuilder();
event
.setHurricane()
.setSnowStorm()
.setThunderStorm()
.setTornado()
.addContent("en-US", "source", "CNN")
.addContent("en-GB", "source", "BBC")
.setReferenceId("referenceId1")
.setTimestamp("2018-12-19T21:56:24.00Z")
.setExpiryTime("2018-12-19T22:57:24.00Z")
.setMulticast();
nock(endpoint, { reqheaders })
.post("/v1/proactiveEvents/stages/development", event.build())
.reply(200);
const proactiveEvents = new ProactiveEvents(clientId, clientSecret);
const messageResponse = await proactiveEvents.createEvent(endpoint, event, true);
expect(messageResponse).to.be.undefined;
});
it("should get a new access token and send a SportsEvent event", async () => {
reqheaders = {
"accept": "application/json",
"authorization": `Bearer ${tokenResponse.access_token}`,
"content-length": 604,
"content-type": "application/json",
"host": "api.amazonalexa.com",
};
const userId = "userId";
const endpoint: string = "https://api.amazonalexa.com";
const event: SportsEventBuilder = new SportsEventBuilder();
event
.setAwayTeamStatistic("Boston Red Sox", 5)
.setHomeTeamStatistic("New York Yankees", 2)
.setUpdate("Boston Red Sox", 5)
.addContent("en-US", "eventLeagueName", "CNN")
.addContent("en-GB", "eventLeagueName", "BBC")
.setReferenceId("referenceId1")
.setTimestamp("2018-12-19T21:56:24.00Z")
.setExpiryTime("2018-12-19T22:57:24.00Z")
.setMulticast()
.setUnicast("userId");
nock(endpoint, { reqheaders })
.post("/v1/proactiveEvents/stages/development", event.build())
.reply(200);
const proactiveEvents = new ProactiveEvents(clientId, clientSecret);
const messageResponse = await proactiveEvents.createEvent(endpoint, event, true);
expect(messageResponse).to.be.undefined;
});
it("should get a new access token and send a MessageAlert event", async () => {
reqheaders = {
"accept": "application/json",
"authorization": `Bearer ${tokenResponse.access_token}`,
"content-length": 366,
"content-type": "application/json",
"host": "api.amazonalexa.com",
};
const userId = "userId";
const endpoint: string = "https://api.amazonalexa.com";
const event: MessageAlertEventBuilder = new MessageAlertEventBuilder();
event
.setMessageGroup("Friend", 2, MESSAGE_ALERT_URGENCY.URGENT)
.setState(MESSAGE_ALERT_STATUS.UNREAD, MESSAGE_ALERT_FRESHNESS.NEW)
.setReferenceId("referenceId1")
.setTimestamp("2018-12-19T21:56:24.00Z")
.setExpiryTime("2018-12-19T22:57:24.00Z")
.setMulticast();
nock(endpoint, { reqheaders })
.post("/v1/proactiveEvents/stages/development", event.build())
.reply(200);
const proactiveEvents = new ProactiveEvents(clientId, clientSecret);
const messageResponse = await proactiveEvents.createEvent(endpoint, event, true);
expect(messageResponse).to.be.undefined;
});
it("should get a new access token and send a OrderStatus event", async () => {
reqheaders = {
"accept": "application/json",
"authorization": `Bearer ${tokenResponse.access_token}`,
"content-length": 522,
"content-type": "application/json",
"host": "api.amazonalexa.com",
};
const userId = "userId";
const endpoint: string = "https://api.amazonalexa.com";
const event: OrderStatusEventBuilder = new OrderStatusEventBuilder();
event
.setStatus(ORDER_STATUS.ORDER_DELIVERED, "2018-12-19T22:56:24.00Z", "2018-12-19T22:56:24.00Z")
.addContent("en-US", "sellerName", "CNN")
.addContent("en-GB", "sellerName", "BBC")
.setReferenceId("referenceId1")
.setTimestamp("2018-12-19T21:56:24.00Z")
.setExpiryTime("2018-12-19T22:57:24.00Z")
.setMulticast();
nock(endpoint, { reqheaders })
.post("/v1/proactiveEvents/stages/development", event.build())
.reply(200);
const proactiveEvents = new ProactiveEvents(clientId, clientSecret);
const messageResponse = await proactiveEvents.createEvent(endpoint, event, true);
expect(messageResponse).to.be.undefined;
});
it("should get a new access token and send a Occasion event", async () => {
reqheaders = {
"accept": "application/json",
"authorization": `Bearer ${tokenResponse.access_token}`,
"content-length": 717,
"content-type": "application/json",
"host": "api.amazonalexa.com",
};
const userId = "userId";
const endpoint: string = "https://api.amazonalexa.com";
const event: OccasionEventBuilder = new OccasionEventBuilder();
event
.setOccasion("2018-12-19T22:56:24.00Z", OCCASION_TYPE.APPOINTMENT)
.setStatus(OCCASION_CONFIRMATION_STATUS.CONFIRMED)
.addContent("en-US", "brokerName", "CNN Chicago")
.addContent("en-GB", "brokerName", "BBC London")
.addContent("en-US", "providerName", "CNN")
.addContent("en-GB", "providerName", "BBC")
.addContent("en-US", "subject", "Merry Christmas in Chicago")
.addContent("en-GB", "subject", "Merry Christmas in London")
.setReferenceId("referenceId1")
.setTimestamp("2018-12-19T21:56:24.00Z")
.setExpiryTime("2018-12-19T22:57:24.00Z")
.setMulticast();
nock(endpoint, { reqheaders })
.post("/v1/proactiveEvents/stages/development", event.build())
.reply(200);
const proactiveEvents = new ProactiveEvents(clientId, clientSecret);
const messageResponse = await proactiveEvents.createEvent(endpoint, event, true);
expect(messageResponse).to.be.undefined;
});
it("should get a new access token and send a TrashCollectionAlert event", async () => {
reqheaders = {
"accept": "application/json",
"authorization": `Bearer ${tokenResponse.access_token}`,
"content-length": 348,
"content-type": "application/json",
"host": "api.amazonalexa.com",
};
const userId = "userId";
const endpoint: string = "https://api.amazonalexa.com";
const event: TrashCollectionAlertEventBuilder = new TrashCollectionAlertEventBuilder();
event
.setAlert(GARBAGE_COLLECTION_DAY.MONDAY,
GARBAGE_TYPE.BOTTLES,
GARBAGE_TYPE.BULKY,
GARBAGE_TYPE.CANS,
GARBAGE_TYPE.CLOTHING)
.setReferenceId("referenceId1")
.setTimestamp("2018-12-19T21:56:24.00Z")
.setExpiryTime("2018-12-19T22:57:24.00Z")
.setMulticast();
nock(endpoint, { reqheaders })
.post("/v1/proactiveEvents/stages/development", event.build())
.reply(200);
const proactiveEvents = new ProactiveEvents(clientId, clientSecret);
const messageResponse = await proactiveEvents.createEvent(endpoint, event, true);
expect(messageResponse).to.be.undefined;
});
it("should get a new access token and send a MediaContent event", async () => {
reqheaders = {
"accept": "application/json",
"authorization": `Bearer ${tokenResponse.access_token}`,
"content-length": 568,
"content-type": "application/json",
"host": "api.amazonalexa.com",
};
const userId = "userId";
const endpoint: string = "https://api.amazonalexa.com";
const event: MediaContentEventBuilder = new MediaContentEventBuilder();
event
.setAvailability(MEDIA_CONTENT_METHOD.AIR)
.setContentType(MEDIA_CONTENT_TYPE.ALBUM)
.addContent("en-US", "providerName", "CNN")
.addContent("en-GB", "providerName", "BBC")
.addContent("en-US", "contentName", "News")
.addContent("en-GB", "contentName", "Alerts")
.setReferenceId("referenceId1")
.setTimestamp("2018-12-19T21:56:24.00Z")
.setExpiryTime("2018-12-19T22:57:24.00Z")
.setMulticast();
nock(endpoint, { reqheaders })
.post("/v1/proactiveEvents/stages/development", event.build())
.reply(200);
const proactiveEvents = new ProactiveEvents(clientId, clientSecret);
const messageResponse = await proactiveEvents.createEvent(endpoint, event, true);
expect(messageResponse).to.be.undefined;
});
it("should get a new access token and send a SocialGameInvite event", async () => {
reqheaders = {
"accept": "application/json",
"authorization": `Bearer ${tokenResponse.access_token}`,
"content-length": 478,
"content-type": "application/json",
"host": "api.amazonalexa.com",
};
const userId = "userId";
const endpoint: string = "https://api.amazonalexa.com";
const event: SocialGameInviteEventBuilder = new SocialGameInviteEventBuilder();
event
.setGame(SOCIAL_GAME_OFFER.GAME)
.setInvite("Test", SOCIAL_GAME_INVITE_TYPE.CHALLENGE, SOCIAL_GAME_RELATIONSHIP_TO_INVITEE.CONTACT)
.addContent("en-US", "gameName", "CNN")
.addContent("en-GB", "gameName", "BBC")
.setReferenceId("referenceId1")
.setTimestamp("2018-12-19T21:56:24.00Z")
.setExpiryTime("2018-12-19T22:57:24.00Z")
.setMulticast();
nock(endpoint, { reqheaders })
.post("/v1/proactiveEvents/stages/development", event.build())
.reply(200);
const proactiveEvents = new ProactiveEvents(clientId, clientSecret);
const messageResponse = await proactiveEvents.createEvent(endpoint, event, true);
expect(messageResponse).to.be.undefined;
});
it("should get a new access token and send a general/custom event", async () => {
reqheaders = {
"accept": "application/json",
"authorization": `Bearer ${tokenResponse.access_token}`,
"content-length": 328,
"content-type": "application/json",
"host": "api.amazonalexa.com",
};
const userId = "userId";
const endpoint: string = "https://api.amazonalexa.com";
const event: EventBuilder = new EventBuilder("MyCustomEvent");
event
.addContent("en-US", "source", "CNN")
.addContent("en-GB", "source", "BBC")
.setPayload({ customProperty: "customValue" })
.setReferenceId("referenceId1")
.setTimestamp("2018-12-19T21:56:24.00Z")
.setExpiryTime("2018-12-19T22:57:24.00Z")
.setMulticast();
nock(endpoint, { reqheaders })
.post("/v1/proactiveEvents/stages/development", event.build())
.reply(200);
const proactiveEvents = new ProactiveEvents(clientId, clientSecret);
const messageResponse = await proactiveEvents.createEvent(endpoint, event, true);
expect(messageResponse).to.be.undefined;
});
}); | the_stack |
import * as coreClient from "@azure/core-client";
/** Describes the result of the request to list management groups. */
export interface ManagementGroupListResult {
/** The list of management groups. */
value?: ManagementGroupInfo[];
/**
* The URL to use for getting the next set of results.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly nextLink?: string;
}
/** The management group resource. */
export interface ManagementGroupInfo {
/**
* The fully qualified ID for the management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
/**
* The type of the resource. For example, Microsoft.Management/managementGroups
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
/**
* The name of the management group. For example, 00000000-0000-0000-0000-000000000000
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/** The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000 */
tenantId?: string;
/** The friendly name of the management group. */
displayName?: string;
}
/** The error object. */
export interface ErrorResponse {
/** The details of the error. */
error?: ErrorDetails;
}
/** The details of the error. */
export interface ErrorDetails {
/** One of a server-defined set of error codes. */
code?: string;
/** A human-readable representation of the error. */
message?: string;
/** A human-readable representation of the error's details. */
details?: string;
}
/** The management group details. */
export interface ManagementGroup {
/**
* The fully qualified ID for the management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
/**
* The type of the resource. For example, Microsoft.Management/managementGroups
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
/**
* The name of the management group. For example, 00000000-0000-0000-0000-000000000000
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/** The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000 */
tenantId?: string;
/** The friendly name of the management group. */
displayName?: string;
/** The details of a management group. */
details?: ManagementGroupDetails;
/** The list of children. */
children?: ManagementGroupChildInfo[];
}
/** The details of a management group. */
export interface ManagementGroupDetails {
/** The version number of the object. */
version?: number;
/** The date and time when this object was last updated. */
updatedTime?: Date;
/** The identity of the principal or process that updated the object. */
updatedBy?: string;
/** (Optional) The ID of the parent management group. */
parent?: ParentGroupInfo;
/** The path from the root to the current group. */
path?: ManagementGroupPathElement[];
/** The ancestors of the management group. */
managementGroupAncestors?: string[];
/** The ancestors of the management group displayed in reversed order, from immediate parent to the root. */
managementGroupAncestorsChain?: ManagementGroupPathElement[];
}
/** (Optional) The ID of the parent management group. */
export interface ParentGroupInfo {
/** The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 */
id?: string;
/** The name of the parent management group */
name?: string;
/** The friendly name of the parent management group. */
displayName?: string;
}
/** A path element of a management group ancestors. */
export interface ManagementGroupPathElement {
/** The name of the group. */
name?: string;
/** The friendly name of the group. */
displayName?: string;
}
/** The child information of a management group. */
export interface ManagementGroupChildInfo {
/** The fully qualified resource type which includes provider namespace (e.g. Microsoft.Management/managementGroups) */
type?: ManagementGroupChildType;
/** The fully qualified ID for the child resource (management group or subscription). For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 */
id?: string;
/** The name of the child entity. */
name?: string;
/** The friendly name of the child resource. */
displayName?: string;
/** The list of children. */
children?: ManagementGroupChildInfo[];
}
/** Management group creation parameters. */
export interface CreateManagementGroupRequest {
/**
* The fully qualified ID for the management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
/**
* The type of the resource. For example, Microsoft.Management/managementGroups
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
/** The name of the management group. For example, 00000000-0000-0000-0000-000000000000 */
name?: string;
/**
* The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly tenantId?: string;
/** The friendly name of the management group. If no value is passed then this field will be set to the groupId. */
displayName?: string;
/** The details of a management group used during creation. */
details?: CreateManagementGroupDetails;
/**
* The list of children.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly children?: CreateManagementGroupChildInfo[];
}
/** The details of a management group used during creation. */
export interface CreateManagementGroupDetails {
/**
* The version number of the object.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly version?: number;
/**
* The date and time when this object was last updated.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly updatedTime?: Date;
/**
* The identity of the principal or process that updated the object.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly updatedBy?: string;
/** (Optional) The ID of the parent management group used during creation. */
parent?: CreateParentGroupInfo;
}
/** (Optional) The ID of the parent management group used during creation. */
export interface CreateParentGroupInfo {
/** The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 */
id?: string;
/**
* The name of the parent management group
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/**
* The friendly name of the parent management group.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly displayName?: string;
}
/** The child information of a management group used during creation. */
export interface CreateManagementGroupChildInfo {
/**
* The fully qualified resource type which includes provider namespace (e.g. Microsoft.Management/managementGroups)
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: ManagementGroupChildType;
/**
* The fully qualified ID for the child resource (management group or subscription). For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
/**
* The name of the child entity.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/**
* The friendly name of the child resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly displayName?: string;
/**
* The list of children.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly children?: CreateManagementGroupChildInfo[];
}
/** The results of Azure-AsyncOperation. */
export interface AzureAsyncOperationResults {
/**
* The fully qualified ID for the management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
/**
* The type of the resource. For example, Microsoft.Management/managementGroups
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
/**
* The name of the management group. For example, 00000000-0000-0000-0000-000000000000
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/**
* The current status of the asynchronous operation performed . For example, Running, Succeeded, Failed
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly status?: string;
/** The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000 */
tenantId?: string;
/** The friendly name of the management group. */
displayName?: string;
}
/** Management group patch parameters. */
export interface PatchManagementGroupRequest {
/** The friendly name of the management group. */
displayName?: string;
/** (Optional) The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 */
parentGroupId?: string;
}
/** Describes the result of the request to view descendants. */
export interface DescendantListResult {
/** The list of descendants. */
value?: DescendantInfo[];
/**
* The URL to use for getting the next set of results.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly nextLink?: string;
}
/** The descendant. */
export interface DescendantInfo {
/**
* The fully qualified ID for the descendant. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 or /subscriptions/0000000-0000-0000-0000-000000000000
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
/**
* The type of the resource. For example, Microsoft.Management/managementGroups or /subscriptions
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
/**
* The name of the descendant. For example, 00000000-0000-0000-0000-000000000000
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/** The friendly name of the management group. */
displayName?: string;
/** The ID of the parent management group. */
parent?: DescendantParentGroupInfo;
}
/** The ID of the parent management group. */
export interface DescendantParentGroupInfo {
/** The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 */
id?: string;
}
/** The details of subscription under management group. */
export interface SubscriptionUnderManagementGroup {
/**
* The fully qualified ID for the subscription. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000/subscriptions/0000000-0000-0000-0000-000000000001
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
/**
* The type of the resource. For example, Microsoft.Management/managementGroups/subscriptions
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
/**
* The stringified id of the subscription. For example, 00000000-0000-0000-0000-000000000000
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/** The AAD Tenant ID associated with the subscription. For example, 00000000-0000-0000-0000-000000000000 */
tenant?: string;
/** The friendly name of the subscription. */
displayName?: string;
/** The ID of the parent management group. */
parent?: DescendantParentGroupInfo;
/** The state of the subscription. */
state?: string;
}
/** The details of all subscriptions under management group. */
export interface ListSubscriptionUnderManagementGroup {
/** The list of subscriptions. */
value?: SubscriptionUnderManagementGroup[];
/**
* The URL to use for getting the next set of results.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly nextLink?: string;
}
/** Lists all hierarchy settings. */
export interface HierarchySettingsList {
/** The list of hierarchy settings. */
value?: HierarchySettingsInfo[];
/**
* The URL to use for getting the next set of results.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly nextLink?: string;
}
/** The hierarchy settings resource. */
export interface HierarchySettingsInfo {
/**
* The fully qualified ID for the settings object. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000/settings/default.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
/**
* The type of the resource. For example, Microsoft.Management/managementGroups/settings.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
/**
* The name of the object. In this case, default.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/** The AAD Tenant ID associated with the hierarchy settings. For example, 00000000-0000-0000-0000-000000000000 */
tenantId?: string;
/** Indicates whether RBAC access is required upon group creation under the root Management Group. If set to true, user will require Microsoft.Management/managementGroups/write action on the root Management Group scope in order to create new Groups directly under the root. This will prevent new users from creating new Management Groups, unless they are given access. */
requireAuthorizationForGroupCreation?: boolean;
/** Settings that sets the default Management Group under which new subscriptions get added in this tenant. For example, /providers/Microsoft.Management/managementGroups/defaultGroup */
defaultManagementGroup?: string;
}
/** Settings defined at the Management Group scope. */
export interface HierarchySettings {
/**
* The fully qualified ID for the settings object. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000/settings/default.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
/**
* The type of the resource. For example, Microsoft.Management/managementGroups/settings.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
/**
* The name of the object. In this case, default.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/** The AAD Tenant ID associated with the hierarchy settings. For example, 00000000-0000-0000-0000-000000000000 */
tenantId?: string;
/** Indicates whether RBAC access is required upon group creation under the root Management Group. If set to true, user will require Microsoft.Management/managementGroups/write action on the root Management Group scope in order to create new Groups directly under the root. This will prevent new users from creating new Management Groups, unless they are given access. */
requireAuthorizationForGroupCreation?: boolean;
/** Settings that sets the default Management Group under which new subscriptions get added in this tenant. For example, /providers/Microsoft.Management/managementGroups/defaultGroup */
defaultManagementGroup?: string;
}
/** Parameters for creating or updating Management Group settings */
export interface CreateOrUpdateSettingsRequest {
/** Indicates whether RBAC access is required upon group creation under the root Management Group. If set to true, user will require Microsoft.Management/managementGroups/write action on the root Management Group scope in order to create new Groups directly under the root. This will prevent new users from creating new Management Groups, unless they are given access. */
requireAuthorizationForGroupCreation?: boolean;
/** Settings that sets the default Management Group under which new subscriptions get added in this tenant. For example, /providers/Microsoft.Management/managementGroups/defaultGroup */
defaultManagementGroup?: string;
}
/** Describes the result of the request to list Microsoft.Management operations. */
export interface OperationListResult {
/**
* List of operations supported by the Microsoft.Management resource provider.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly value?: Operation[];
/**
* URL to get the next set of operation list results if there are any.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly nextLink?: string;
}
/** Operation supported by the Microsoft.Management resource provider. */
export interface Operation {
/**
* Operation name: {provider}/{resource}/{operation}.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/** The object that represents the operation. */
display?: OperationDisplayProperties;
}
/** The object that represents the operation. */
export interface OperationDisplayProperties {
/**
* The name of the provider.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly provider?: string;
/**
* The resource on which the operation is performed.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly resource?: string;
/**
* The operation that can be performed.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly operation?: string;
/**
* Operation description.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly description?: string;
}
/** Management group name availability check parameters. */
export interface CheckNameAvailabilityRequest {
/** the name to check for availability */
name?: string;
/** fully qualified resource type which includes provider namespace */
type?: "Microsoft.Management/managementGroups";
}
/** Describes the result of the request to check management group name availability. */
export interface CheckNameAvailabilityResult {
/**
* Required. True indicates name is valid and available. False indicates the name is invalid, unavailable, or both.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly nameAvailable?: boolean;
/**
* Required if nameAvailable == false. Invalid indicates the name provided does not match the resource provider's naming requirements (incorrect length, unsupported characters, etc.) AlreadyExists indicates that the name is already in use and is therefore unavailable.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly reason?: Reason;
/**
* Required if nameAvailable == false. Localized. If reason == invalid, provide the user with the reason why the given name is invalid, and provide the resource naming requirements so that the user can select a valid name. If reason == AlreadyExists, explain that is already in use, and direct them to select a different name.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly message?: string;
}
/** Describes the result of the request to view entities. */
export interface EntityListResult {
/** The list of entities. */
value?: EntityInfo[];
/**
* Total count of records that match the filter
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly count?: number;
/**
* The URL to use for getting the next set of results.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly nextLink?: string;
}
/** The entity. */
export interface EntityInfo {
/**
* The fully qualified ID for the entity. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
/**
* The type of the resource. For example, Microsoft.Management/managementGroups
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
/**
* The name of the entity. For example, 00000000-0000-0000-0000-000000000000
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/** The AAD Tenant ID associated with the entity. For example, 00000000-0000-0000-0000-000000000000 */
tenantId?: string;
/** The friendly name of the management group. */
displayName?: string;
/** (Optional) The ID of the parent management group. */
parent?: EntityParentGroupInfo;
/** The users specific permissions to this item. */
permissions?: Permissions;
/** The users specific permissions to this item. */
inheritedPermissions?: Permissions;
/** Number of Descendants */
numberOfDescendants?: number;
/** Number of children is the number of Groups and Subscriptions that are exactly one level underneath the current Group. */
numberOfChildren?: number;
/** Number of children is the number of Groups that are exactly one level underneath the current Group. */
numberOfChildGroups?: number;
/** The parent display name chain from the root group to the immediate parent */
parentDisplayNameChain?: string[];
/** The parent name chain from the root group to the immediate parent */
parentNameChain?: string[];
}
/** (Optional) The ID of the parent management group. */
export interface EntityParentGroupInfo {
/** The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 */
id?: string;
}
/** The tenant backfill status */
export interface TenantBackfillStatusResult {
/**
* The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly tenantId?: string;
/**
* The status of the Tenant Backfill
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly status?: Status;
}
/** The results of an asynchronous operation. */
export interface OperationResults {
/**
* The fully qualified ID for the management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
/**
* The type of the resource. For example, Microsoft.Management/managementGroups
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
/**
* The name of the management group. For example, 00000000-0000-0000-0000-000000000000
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/** The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000 */
tenantId?: string;
/** The friendly name of the management group. */
displayName?: string;
}
/** The management group details for the hierarchy view. */
export interface EntityHierarchyItem {
/**
* The fully qualified ID for the management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
/**
* The type of the resource. For example, Microsoft.Management/managementGroups
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
/**
* The name of the management group. For example, 00000000-0000-0000-0000-000000000000
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/** The friendly name of the management group. */
displayName?: string;
/** The users specific permissions to this item. */
permissions?: Permissions;
/** The list of children. */
children?: EntityHierarchyItem[];
}
/** Defines headers for ManagementGroups_createOrUpdate operation. */
export interface ManagementGroupsCreateOrUpdateHeaders {
/**
* URL for determining when an operation has completed. Send a GET request to the URL in Location header.
* The URI should return a 202 until the operation reaches a terminal state and 200 once it reaches a terminal state.
*
* For more info: https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/Addendum.md#202-accepted-and-location-headers
*/
location?: string;
/**
* URL for checking the ongoing status of the operation.
* To get the status of the asynchronous operation, send a GET request to the URL in Azure-AsyncOperation header value.
*
* For more info: https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/Addendum.md#asynchronous-operations
*/
azureAsyncOperation?: string;
}
/** Defines headers for ManagementGroups_delete operation. */
export interface ManagementGroupsDeleteHeaders {
/**
* URL for determining when an operation has completed. Send a GET request to the URL in Location header.
* The URI should return a 202 until the operation reaches a terminal state and 200 once it reaches a terminal state.
*
* For more info: https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/Addendum.md#202-accepted-and-location-headers
*/
location?: string;
/**
* URL for checking the ongoing status of the operation.
* To get the status of the asynchronous operation, send a GET request to the URL in Azure-AsyncOperation header value.
*
* For more info: https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/Addendum.md#asynchronous-operations
*/
azureAsyncOperation?: string;
}
/** Known values of {@link Enum0} that the service accepts. */
export enum KnownEnum0 {
Children = "children",
Path = "path",
Ancestors = "ancestors"
}
/**
* Defines values for Enum0. \
* {@link KnownEnum0} can be used interchangeably with Enum0,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **children** \
* **path** \
* **ancestors**
*/
export type Enum0 = string;
/** Known values of {@link ManagementGroupChildType} that the service accepts. */
export enum KnownManagementGroupChildType {
MicrosoftManagementManagementGroups = "Microsoft.Management/managementGroups",
Subscriptions = "/subscriptions"
}
/**
* Defines values for ManagementGroupChildType. \
* {@link KnownManagementGroupChildType} can be used interchangeably with ManagementGroupChildType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Microsoft.Management\/managementGroups** \
* **\/subscriptions**
*/
export type ManagementGroupChildType = string;
/** Known values of {@link Enum2} that the service accepts. */
export enum KnownEnum2 {
AllowedParents = "AllowedParents",
AllowedChildren = "AllowedChildren",
ParentAndFirstLevelChildren = "ParentAndFirstLevelChildren",
ParentOnly = "ParentOnly",
ChildrenOnly = "ChildrenOnly"
}
/**
* Defines values for Enum2. \
* {@link KnownEnum2} can be used interchangeably with Enum2,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **AllowedParents** \
* **AllowedChildren** \
* **ParentAndFirstLevelChildren** \
* **ParentOnly** \
* **ChildrenOnly**
*/
export type Enum2 = string;
/** Known values of {@link Enum3} that the service accepts. */
export enum KnownEnum3 {
FullHierarchy = "FullHierarchy",
GroupsOnly = "GroupsOnly",
SubscriptionsOnly = "SubscriptionsOnly",
Audit = "Audit"
}
/**
* Defines values for Enum3. \
* {@link KnownEnum3} can be used interchangeably with Enum3,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **FullHierarchy** \
* **GroupsOnly** \
* **SubscriptionsOnly** \
* **Audit**
*/
export type Enum3 = string;
/** Known values of {@link Permissions} that the service accepts. */
export enum KnownPermissions {
Noaccess = "noaccess",
View = "view",
Edit = "edit",
Delete = "delete"
}
/**
* Defines values for Permissions. \
* {@link KnownPermissions} can be used interchangeably with Permissions,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **noaccess** \
* **view** \
* **edit** \
* **delete**
*/
export type Permissions = string;
/** Defines values for Reason. */
export type Reason = "Invalid" | "AlreadyExists";
/** Defines values for Status. */
export type Status =
| "NotStarted"
| "NotStartedButGroupsExist"
| "Started"
| "Failed"
| "Cancelled"
| "Completed";
/** Optional parameters. */
export interface ManagementGroupsListOptionalParams
extends coreClient.OperationOptions {
/** Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. */
cacheControl?: string;
/**
* Page continuation token is only used if a previous operation returned a partial result.
* If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls.
*
*/
skiptoken?: string;
}
/** Contains response data for the list operation. */
export type ManagementGroupsListResponse = ManagementGroupListResult;
/** Optional parameters. */
export interface ManagementGroupsGetOptionalParams
extends coreClient.OperationOptions {
/** Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. */
cacheControl?: string;
/** The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. */
expand?: Enum0;
/** The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children must be passed up if $recurse is set to true. */
recurse?: boolean;
/** A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription') */
filter?: string;
}
/** Contains response data for the get operation. */
export type ManagementGroupsGetResponse = ManagementGroup;
/** Optional parameters. */
export interface ManagementGroupsCreateOrUpdateOptionalParams
extends coreClient.OperationOptions {
/** Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. */
cacheControl?: string;
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Contains response data for the createOrUpdate operation. */
export type ManagementGroupsCreateOrUpdateResponse = ManagementGroup;
/** Optional parameters. */
export interface ManagementGroupsUpdateOptionalParams
extends coreClient.OperationOptions {
/** Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. */
cacheControl?: string;
}
/** Contains response data for the update operation. */
export type ManagementGroupsUpdateResponse = ManagementGroup;
/** Optional parameters. */
export interface ManagementGroupsDeleteOptionalParams
extends coreClient.OperationOptions {
/** Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. */
cacheControl?: string;
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Contains response data for the delete operation. */
export type ManagementGroupsDeleteResponse = ManagementGroupsDeleteHeaders &
AzureAsyncOperationResults;
/** Optional parameters. */
export interface ManagementGroupsGetDescendantsOptionalParams
extends coreClient.OperationOptions {
/**
* Page continuation token is only used if a previous operation returned a partial result.
* If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls.
*
*/
skiptoken?: string;
/** Number of elements to return when retrieving results. Passing this in will override $skipToken. */
top?: number;
}
/** Contains response data for the getDescendants operation. */
export type ManagementGroupsGetDescendantsResponse = DescendantListResult;
/** Optional parameters. */
export interface ManagementGroupsListNextOptionalParams
extends coreClient.OperationOptions {
/** Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. */
cacheControl?: string;
/**
* Page continuation token is only used if a previous operation returned a partial result.
* If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls.
*
*/
skiptoken?: string;
}
/** Contains response data for the listNext operation. */
export type ManagementGroupsListNextResponse = ManagementGroupListResult;
/** Optional parameters. */
export interface ManagementGroupsGetDescendantsNextOptionalParams
extends coreClient.OperationOptions {
/**
* Page continuation token is only used if a previous operation returned a partial result.
* If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls.
*
*/
skiptoken?: string;
/** Number of elements to return when retrieving results. Passing this in will override $skipToken. */
top?: number;
}
/** Contains response data for the getDescendantsNext operation. */
export type ManagementGroupsGetDescendantsNextResponse = DescendantListResult;
/** Optional parameters. */
export interface ManagementGroupSubscriptionsCreateOptionalParams
extends coreClient.OperationOptions {
/** Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. */
cacheControl?: string;
}
/** Contains response data for the create operation. */
export type ManagementGroupSubscriptionsCreateResponse = SubscriptionUnderManagementGroup;
/** Optional parameters. */
export interface ManagementGroupSubscriptionsDeleteOptionalParams
extends coreClient.OperationOptions {
/** Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. */
cacheControl?: string;
}
/** Optional parameters. */
export interface ManagementGroupSubscriptionsGetSubscriptionOptionalParams
extends coreClient.OperationOptions {
/** Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. */
cacheControl?: string;
}
/** Contains response data for the getSubscription operation. */
export type ManagementGroupSubscriptionsGetSubscriptionResponse = SubscriptionUnderManagementGroup;
/** Optional parameters. */
export interface ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupOptionalParams
extends coreClient.OperationOptions {
/**
* Page continuation token is only used if a previous operation returned a partial result.
* If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls.
*
*/
skiptoken?: string;
}
/** Contains response data for the getSubscriptionsUnderManagementGroup operation. */
export type ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupResponse = ListSubscriptionUnderManagementGroup;
/** Optional parameters. */
export interface ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupNextOptionalParams
extends coreClient.OperationOptions {
/**
* Page continuation token is only used if a previous operation returned a partial result.
* If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls.
*
*/
skiptoken?: string;
}
/** Contains response data for the getSubscriptionsUnderManagementGroupNext operation. */
export type ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupNextResponse = ListSubscriptionUnderManagementGroup;
/** Optional parameters. */
export interface HierarchySettingsListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type HierarchySettingsListResponse = HierarchySettingsList;
/** Optional parameters. */
export interface HierarchySettingsGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type HierarchySettingsGetResponse = HierarchySettings;
/** Optional parameters. */
export interface HierarchySettingsCreateOrUpdateOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the createOrUpdate operation. */
export type HierarchySettingsCreateOrUpdateResponse = HierarchySettings;
/** Optional parameters. */
export interface HierarchySettingsUpdateOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the update operation. */
export type HierarchySettingsUpdateResponse = HierarchySettings;
/** Optional parameters. */
export interface HierarchySettingsDeleteOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface OperationsListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type OperationsListResponse = OperationListResult;
/** Optional parameters. */
export interface OperationsListNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listNext operation. */
export type OperationsListNextResponse = OperationListResult;
/** Optional parameters. */
export interface CheckNameAvailabilityOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the checkNameAvailability operation. */
export type CheckNameAvailabilityResponse = CheckNameAvailabilityResult;
/** Optional parameters. */
export interface StartTenantBackfillOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the startTenantBackfill operation. */
export type StartTenantBackfillResponse = TenantBackfillStatusResult;
/** Optional parameters. */
export interface TenantBackfillStatusOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the tenantBackfillStatus operation. */
export type TenantBackfillStatusResponse = TenantBackfillStatusResult;
/** Optional parameters. */
export interface EntitiesListOptionalParams
extends coreClient.OperationOptions {
/** Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. */
cacheControl?: string;
/**
* Page continuation token is only used if a previous operation returned a partial result.
* If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls.
*
*/
skiptoken?: string;
/** The filter parameter allows you to filter on the the name or display name fields. You can check for equality on the name field (e.g. name eq '{entityName}') and you can check for substrings on either the name or display name fields(e.g. contains(name, '{substringToSearch}'), contains(displayName, '{substringToSearch')). Note that the '{entityName}' and '{substringToSearch}' fields are checked case insensitively. */
filter?: string;
/** Number of elements to return when retrieving results. Passing this in will override $skipToken. */
top?: number;
/** Number of entities to skip over when retrieving results. Passing this in will override $skipToken. */
skip?: number;
/** This parameter specifies the fields to include in the response. Can include any combination of Name,DisplayName,Type,ParentDisplayNameChain,ParentChain, e.g. '$select=Name,DisplayName,Type,ParentDisplayNameChain,ParentNameChain'. When specified the $select parameter can override select in $skipToken. */
select?: string;
/**
* The $search parameter is used in conjunction with the $filter parameter to return three different outputs depending on the parameter passed in.
* With $search=AllowedParents the API will return the entity info of all groups that the requested entity will be able to reparent to as determined by the user's permissions.
* With $search=AllowedChildren the API will return the entity info of all entities that can be added as children of the requested entity.
* With $search=ParentAndFirstLevelChildren the API will return the parent and first level of children that the user has either direct access to or indirect access via one of their descendants.
* With $search=ParentOnly the API will return only the group if the user has access to at least one of the descendants of the group.
* With $search=ChildrenOnly the API will return only the first level of children of the group entity info specified in $filter. The user must have direct access to the children entities or one of it's descendants for it to show up in the results.
*/
search?: Enum2;
/** The view parameter allows clients to filter the type of data that is returned by the getEntities call. */
view?: Enum3;
/** A filter which allows the get entities call to focus on a particular group (i.e. "$filter=name eq 'groupName'") */
groupName?: string;
}
/** Contains response data for the list operation. */
export type EntitiesListResponse = EntityListResult;
/** Optional parameters. */
export interface EntitiesListNextOptionalParams
extends coreClient.OperationOptions {
/** Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. */
cacheControl?: string;
/**
* Page continuation token is only used if a previous operation returned a partial result.
* If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point to use for subsequent calls.
*
*/
skiptoken?: string;
/** The filter parameter allows you to filter on the the name or display name fields. You can check for equality on the name field (e.g. name eq '{entityName}') and you can check for substrings on either the name or display name fields(e.g. contains(name, '{substringToSearch}'), contains(displayName, '{substringToSearch')). Note that the '{entityName}' and '{substringToSearch}' fields are checked case insensitively. */
filter?: string;
/** Number of elements to return when retrieving results. Passing this in will override $skipToken. */
top?: number;
/** Number of entities to skip over when retrieving results. Passing this in will override $skipToken. */
skip?: number;
/** This parameter specifies the fields to include in the response. Can include any combination of Name,DisplayName,Type,ParentDisplayNameChain,ParentChain, e.g. '$select=Name,DisplayName,Type,ParentDisplayNameChain,ParentNameChain'. When specified the $select parameter can override select in $skipToken. */
select?: string;
/**
* The $search parameter is used in conjunction with the $filter parameter to return three different outputs depending on the parameter passed in.
* With $search=AllowedParents the API will return the entity info of all groups that the requested entity will be able to reparent to as determined by the user's permissions.
* With $search=AllowedChildren the API will return the entity info of all entities that can be added as children of the requested entity.
* With $search=ParentAndFirstLevelChildren the API will return the parent and first level of children that the user has either direct access to or indirect access via one of their descendants.
* With $search=ParentOnly the API will return only the group if the user has access to at least one of the descendants of the group.
* With $search=ChildrenOnly the API will return only the first level of children of the group entity info specified in $filter. The user must have direct access to the children entities or one of it's descendants for it to show up in the results.
*/
search?: Enum2;
/** The view parameter allows clients to filter the type of data that is returned by the getEntities call. */
view?: Enum3;
/** A filter which allows the get entities call to focus on a particular group (i.e. "$filter=name eq 'groupName'") */
groupName?: string;
}
/** Contains response data for the listNext operation. */
export type EntitiesListNextResponse = EntityListResult;
/** Optional parameters. */
export interface ManagementGroupsAPIOptionalParams
extends coreClient.ServiceClientOptions {
/** server parameter */
$host?: string;
/** Api Version */
apiVersion?: string;
/** Overrides client endpoint. */
endpoint?: string;
} | the_stack |
namespace LiteMol.Extensions.ComplexReprensetation {
import Model = Core.Structure.Molecule.Model
import CU = Core.Utils
import S = Core.Structure
import Q = S.Query
export interface Info {
sequence: {
all: number[],
interacting: number[],
modified: number[]
},
het: {
carbohydrates: Carbohydrates.Info,
other: number[]
},
freeWaterAtoms: number[]
}
const MAX_AMINO_SEQ_LIGAND_LENGTH = 10;
const MAX_NUCLEOTIDE_SEQ_LIGAND_LENGTH = 2;
export async function createComplexRepresentation(computation: Core.Computation.Context, model: Model, queryCtx: Q.Context): Promise<Info> {
await computation.updateProgress('Determing main sequence atoms...');
const sequenceAtoms = findMainSequence(model, queryCtx);
const modRes = model.data.modifiedResidues;
const hasModRes = modRes && modRes.count > 0;
// is everything cartoon?
if (sequenceAtoms.length === queryCtx.atomCount && !hasModRes) {
const ret: Info = { sequence: { all: sequenceAtoms, interacting: [], modified: [] }, het: { other: [], carbohydrates: Carbohydrates.EmptyInfo([]) }, freeWaterAtoms: [] };
return ret;
}
const sequenceCtx = Q.Context.ofAtomIndices(model, sequenceAtoms);
const modifiedSequence = getModRes(model, sequenceCtx);
if (sequenceAtoms.length === queryCtx.atomCount) {
const ret: Info = { sequence: { all: sequenceAtoms, interacting: [], modified: modifiedSequence }, het: { other: [], carbohydrates: Carbohydrates.EmptyInfo([]) }, freeWaterAtoms: [] };
return ret;
}
const waterAtoms = Q.entities({ type: 'water' }).union().compile()(queryCtx).unionAtomIndices();
const possibleHetGroupsAndInteractingSequenceQ = Q.or(Q.atomsFromIndices(waterAtoms), Q.atomsFromIndices(sequenceAtoms)).complement().ambientResidues(getMaxInteractionRadius(model)).union().compile();
const possibleHetGroupsAndInteractingSequence = possibleHetGroupsAndInteractingSequenceQ(queryCtx).fragments[0];
// is everything cartoon?
if (!possibleHetGroupsAndInteractingSequence) {
const ret: Info = { sequence: { all: sequenceAtoms, interacting: [], modified: modifiedSequence }, het: { other: [], carbohydrates: Carbohydrates.EmptyInfo([]) }, freeWaterAtoms: waterAtoms };
return ret;
}
await computation.updateProgress('Computing bonds...');
const bonds = S.computeBonds(model, possibleHetGroupsAndInteractingSequence.atomIndices);
const { entityIndex, residueIndex } = model.data.atoms;
const { type: entType } = model.data.entities;
const { atomAIndex, atomBIndex } = bonds;
/////////////////////////////////////////////////////
// WATERS
await computation.updateProgress('Identifying free waters...');
const boundWaters = CU.FastSet.create<number>();
for (let i = 0, __i = bonds.count; i < __i; i++) {
const a = atomAIndex[i], b = atomBIndex[i];
const tA = entType[entityIndex[a]], tB = entType[entityIndex[b]];
if (tA === 'water') {
if (tB !== 'water') boundWaters.add(residueIndex[a]);
} else if (tB === 'water') {
boundWaters.add(residueIndex[b]);
}
}
const freeWaterAtoms = new Int32Array(waterAtoms.length - boundWaters.size) as any as number[];
let waterAtomsOffset = 0;
for (const aI of waterAtoms) {
if (!boundWaters.has(aI)) freeWaterAtoms[waterAtomsOffset++] = aI;
}
/////////////////////////////////////////////////////
// HET GROUPS with SEQUENCE RESIDUES
await computation.updateProgress('Identifying HET groups...');
const sequenceMask = sequenceCtx.mask;
const _hetGroupsWithSequence = CU.ChunkedArray.forInt32(possibleHetGroupsAndInteractingSequence.atomCount / 2);
const boundSequence = CU.FastSet.create<number>(), boundHetAtoms = CU.FastSet.create<number>();
for (let i = 0, __i = bonds.count; i < __i; i++) {
const a = atomAIndex[i], b = atomBIndex[i];
const hasA = sequenceMask.has(a), hasB = sequenceMask.has(b);
if (hasA) {
if (!hasB) {
boundSequence.add(residueIndex[a]);
boundHetAtoms.add(b);
}
} else if (hasB) {
boundSequence.add(residueIndex[b]);
boundHetAtoms.add(a);
}
}
for (const aI of possibleHetGroupsAndInteractingSequence.atomIndices) {
const rI = residueIndex[aI];
if (sequenceMask.has(aI) && !boundSequence.has(rI)) continue;
if (entType[entityIndex[aI]] === 'water' && !boundWaters.has(rI)) continue;
CU.ChunkedArray.add(_hetGroupsWithSequence, aI);
}
const hetGroupsWithSequence = CU.ChunkedArray.compact(_hetGroupsWithSequence);
/////////////////////////////////////////////////////
// CARBS
await computation.updateProgress('Identifying carbohydrates...');
const carbohydrates = Carbohydrates.getInfo({ model, fragment: Q.Fragment.ofArray(queryCtx, hetGroupsWithSequence[0], hetGroupsWithSequence), atomMask: queryCtx.mask, bonds });
/////////////////////////////////////////////////////
// OTHER HET GROUPS
await computation.updateProgress('Identifying non-carbohydrate HET groups...');
const commonAtoms = CU.ChunkedArray.forInt32(hetGroupsWithSequence.length);
const { map: carbMap } = carbohydrates;
for (const aI of hetGroupsWithSequence) {
const rI = residueIndex[aI];
if (!carbMap.has(rI) && !sequenceMask.has(aI)) CU.ChunkedArray.add(commonAtoms, aI);
}
/////////////////////////////////////////////////////
// INTERACTING SEQUENCE
await computation.updateProgress('Identifying interacting sequence residues...');
const interactingSequenceAtoms = CU.ChunkedArray.forInt32(hetGroupsWithSequence.length);
for (const aI of hetGroupsWithSequence) {
const rI = residueIndex[aI];
if (boundSequence.has(rI) || (boundHetAtoms.has(aI) && !carbMap.has(rI))) CU.ChunkedArray.add(interactingSequenceAtoms, aI);
}
const ret: Info = {
sequence: { all: sequenceAtoms, interacting: CU.ChunkedArray.compact(interactingSequenceAtoms), modified: modifiedSequence },
het: { other: CU.ChunkedArray.compact(commonAtoms), carbohydrates },
freeWaterAtoms
};
return ret;
}
function getModRes(model: Model, ctx: Q.Context): number[] {
const modRes = model.data.modifiedResidues;
const hasModRes = modRes && modRes.count > 0;
if (!modRes || !hasModRes) return [];
const { asymId, seqNumber, insCode } = modRes;
const residues: Q.ResidueIdSchema[] = [];
for (let i = 0, __i = modRes.count; i < __i; i++) {
residues.push({ asymId: asymId[i], seqNumber: seqNumber[i], insCode: insCode[i] });
}
const q = Q.residues.apply(null, residues).compile() as Q;
return q(ctx).unionAtomIndices();
}
function getMaxInteractionRadius(model: Model) {
let maxLength = 3;
if (model.data.bonds.structConn) {
for (const c of model.data.bonds.structConn.entries) {
if (c.distance > maxLength) maxLength = c.distance;
}
}
return maxLength + 0.1;
}
function chainLengthAndType(model: Model, cI: number, mask: CU.Mask) {
const { secondaryStructure } = model.data;
const { residueStartIndex, residueEndIndex } = model.data.chains;
const { atomStartIndex, atomEndIndex, secondaryStructureIndex: ssi } = model.data.residues;
let length = 0;
let isAmk = false, isNucleotide = false;
for (let rI = residueStartIndex[cI], __b = residueEndIndex[cI]; rI < __b; rI++) {
const ss = secondaryStructure[ssi[rI]].type;
if (ss === S.SecondaryStructureType.Strand) {
isNucleotide = true;
} else if (ss !== S.SecondaryStructureType.None) {
isAmk = true;
}
for (let aI = atomStartIndex[rI], __i = atomEndIndex[rI]; aI < __i; aI++) {
if (mask.has(aI)) {
length++;
break;
}
}
}
return { length, isAmk, isNucleotide };
}
function findMainSequence(model: Model, queryCtx: Q.Context) {
const { mask } = queryCtx;
const { residueStartIndex, residueEndIndex } = model.data.chains;
const { atomStartIndex, atomEndIndex } = model.data.residues;
const atoms = CU.ChunkedArray.forInt32(queryCtx.atomCount);
for (const cI of model.data.chains.indices) {
const { length, isAmk, isNucleotide } = chainLengthAndType(model, cI, mask);
if ((isAmk && length <= MAX_AMINO_SEQ_LIGAND_LENGTH) || (isNucleotide && length <= MAX_NUCLEOTIDE_SEQ_LIGAND_LENGTH)) continue;
for (let rI = residueStartIndex[cI], __b = residueEndIndex[cI]; rI < __b; rI++) {
if (!isCartoonLike(model, mask, rI)) continue;
for (let aI = atomStartIndex[rI], __i = atomEndIndex[rI]; aI < __i; aI++) {
if (mask.has(aI)) {
CU.ChunkedArray.add(atoms, aI);
}
}
}
}
return CU.ChunkedArray.compact(atoms);
}
function _isCartoonLike(mask: CU.Mask, start: number, end: number, name: string[], a: string, b: string, isAmk: boolean) {
let aU = false, aV = false, hasP = false;
for (let i = start; i < end; i++) {
if (!mask.has(i)) continue;
let n = name[i];
if (!aU && n === a) {
aU = true;
} else if (!aV && n === b) {
aV = true;
}
if (aU && aV) return true;
if (n === 'P') {
hasP = true;
}
}
if (isAmk) return aU;
return hasP;
}
function isCartoonLike(model: Model, mask: CU.Mask, rI: number) {
const { secondaryStructure, residues, atoms } = model.data;
const { atomStartIndex, atomEndIndex, secondaryStructureIndex: ssi } = residues;
const ss = secondaryStructure[ssi[rI]].type;
if (ss === S.SecondaryStructureType.None) return false;
const { name } = atoms;
if (ss === S.SecondaryStructureType.Strand) {
return _isCartoonLike(mask, atomStartIndex[rI], atomEndIndex[rI], name, "O5'", "C3'", false);
} else {
return _isCartoonLike(mask, atomStartIndex[rI], atomEndIndex[rI], name, "CA", "O", true);
}
}
} | the_stack |
import * as React from "react";
import * as ReactDOM from "react-dom";
import {
EventEmitter,
EventSubscription,
Expression,
getById,
Prototypes,
Specification,
} from "../../../../core";
import { DragData } from "../../../actions";
import { ColorPicker, SVGImageIcon } from "../../../components";
import { ContextedComponent } from "../../../context_component";
import { getAlignment, PopupAlignment, PopupView } from "../../../controllers";
import * as globals from "../../../globals";
import * as R from "../../../resources";
import { isKindAcceptable } from "../../dataset/common";
import { DataFieldSelector } from "../../dataset/data_field_selector";
import { ScaleEditor } from "../scale_editor";
import { Button, InputExpression } from "./controls";
import { CharticulatorPropertyAccessors, DropZoneView } from "./manager";
import { ValueEditor } from "./value_editor";
import { AppStore } from "../../../stores";
import { ScaleValueSelector } from "../scale_value_selector";
import { FunctionCall } from "../../../../core/expression";
import { getAligntment } from "../../../utils";
import { MappingType } from "../../../../core/specification";
import { ObjectClass } from "../../../../core/prototypes";
import { strings } from "../../../../strings";
export interface MappingEditorProps {
parent: Prototypes.Controls.WidgetManager & CharticulatorPropertyAccessors;
attribute: string;
type: Specification.AttributeType;
options: Prototypes.Controls.MappingEditorOptions;
store?: AppStore;
}
export interface MappingEditorState {
showNoneAsValue: boolean;
}
export class MappingEditor extends React.Component<
MappingEditorProps,
MappingEditorState
> {
public mappingButton: Element;
public noneLabel: HTMLSpanElement;
public scaleMappingDisplay: HTMLSpanElement;
public updateEvents = new EventEmitter();
public state: MappingEditorState = {
showNoneAsValue: false,
};
private beginDataFieldSelection(anchor: Element = this.mappingButton) {
const parent = this.props.parent;
const attribute = this.props.attribute;
const options = this.props.options;
const mapping = parent.getAttributeMapping(attribute);
const {
alignLeft,
alignX,
}: { alignLeft: boolean; alignX: PopupAlignment } = getAlignment(anchor);
globals.popupController.popupAt(
(context) => {
return (
<PopupView context={context}>
<DataMappAndScaleEditor
plotSegment={parentOfType(
(this.props.parent as any).objectClass.parent,
"plot-segment"
)}
attribute={attribute}
parent={this}
defaultMapping={mapping}
options={options}
alignLeft={alignLeft}
onClose={() => context.close()}
/>
</PopupView>
);
},
{ anchor, alignX }
);
}
private beginDataFieldValueSelection(anchor: Element = this.mappingButton) {
const parent = this.props.parent;
const attribute = this.props.attribute;
const mapping = parent.getAttributeMapping(attribute);
const {
alignX,
}: { alignLeft: boolean; alignX: PopupAlignment } = getAlignment(anchor);
globals.popupController.popupAt(
(context) => {
const scaleMapping = mapping as Specification.ScaleMapping;
if (scaleMapping.scale) {
const scaleObject = getById(
this.props.store.chart.scales,
scaleMapping.scale
);
return (
<PopupView context={context}>
<ScaleValueSelector
scale={scaleObject}
scaleMapping={mapping as any}
store={this.props.store}
onSelect={(index) => {
const paresedExpression = Expression.parse(
scaleMapping.expression
) as FunctionCall;
// change the second param of get function
(paresedExpression.args[1] as any).value = index;
scaleMapping.expression = paresedExpression.toString();
this.props.parent.onEditMappingHandler(
this.props.attribute,
scaleMapping
);
context.close();
}}
/>
</PopupView>
);
}
},
{ anchor, alignX }
);
}
private initiateValueEditor() {
switch (this.props.type) {
case "number":
case "font-family":
case "text":
{
this.setState({
showNoneAsValue: true,
});
}
break;
case "color":
{
if (this.mappingButton == null) {
return;
}
const { alignX }: { alignLeft: boolean; alignX: any } = getAligntment(
this.mappingButton
);
globals.popupController.popupAt(
(context) => (
<PopupView context={context}>
<ColorPicker
store={this.props.store}
defaultValue={null}
allowNull={true}
onPick={(color) => {
if (color == null) {
this.clearMapping();
context.close();
} else {
this.setValueMapping(color);
}
}}
/>
</PopupView>
),
{ anchor: this.mappingButton, alignX }
);
}
break;
}
}
private setValueMapping(value: Specification.AttributeValue) {
this.props.parent.onEditMappingHandler(this.props.attribute, {
type: MappingType.value,
value,
} as Specification.ValueMapping);
}
public clearMapping() {
this.props.parent.onEditMappingHandler(this.props.attribute, null);
this.setState({
showNoneAsValue: false,
});
}
public mapData(
data: DragData.DataExpression,
hints: Prototypes.DataMappingHints
) {
this.props.parent.onMapDataHandler(this.props.attribute, data, hints);
}
public componentDidUpdate() {
this.updateEvents.emit("update");
}
public getTableOrDefault() {
if (this.props.options.table) {
return this.props.options.table;
} else {
return this.props.parent.store.getTables()[0].name;
}
}
private renderValueEditor(value: Specification.AttributeValue) {
let placeholderText = this.props.options.defaultAuto
? strings.core.auto
: strings.core.none;
if (this.props.options.defaultValue != null) {
placeholderText = this.props.options.defaultValue.toString();
}
return (
<ValueEditor
value={value}
type={this.props.type}
placeholder={placeholderText}
onClear={() => this.clearMapping()}
onEmitValue={(value) => this.setValueMapping(value)}
onEmitMapping={(mapping) =>
this.props.parent.onEditMappingHandler(this.props.attribute, mapping)
}
onBeginDataFieldSelection={(ref) => this.beginDataFieldSelection(ref)}
getTable={() => this.getTableOrDefault()}
hints={this.props.options.hints}
numberOptions={this.props.options.numberOptions}
anchorReference={this.mappingButton}
/>
);
}
// eslint-disable-next-line
private renderCurrentAttributeMapping() {
const parent = this.props.parent;
const attribute = this.props.attribute;
const options = this.props.options;
const mapping = parent.getAttributeMapping(attribute);
if (!mapping) {
if (options.defaultValue != undefined) {
return this.renderValueEditor(options.defaultValue);
} else {
let alwaysShowNoneAsValue = false;
if (
this.props.type == "number" ||
this.props.type == "enum" ||
this.props.type == "image"
) {
alwaysShowNoneAsValue = true;
}
if (this.state.showNoneAsValue || alwaysShowNoneAsValue) {
return this.renderValueEditor(null);
} else {
if (options.defaultAuto) {
return (
<span
className="el-clickable-label"
ref={(e) => (this.noneLabel = e)}
onClick={() => {
if (!mapping || (mapping as any).valueIndex == undefined) {
this.initiateValueEditor();
}
}}
>
(auto)
</span>
);
} else {
return (
<span
className="el-clickable-label"
ref={(e) => (this.noneLabel = e)}
onClick={() => {
if (!mapping || (mapping as any).valueIndex == undefined) {
this.initiateValueEditor();
}
}}
>
{strings.core.none}
</span>
);
}
}
}
} else {
switch (mapping.type) {
case MappingType.value: {
const valueMapping = mapping as Specification.ValueMapping;
return this.renderValueEditor(valueMapping.value);
}
case MappingType.text: {
const textMapping = mapping as Specification.TextMapping;
return (
<InputExpression
defaultValue={textMapping.textExpression}
textExpression={true}
validate={(value) =>
parent.store.verifyUserExpressionWithTable(
value,
textMapping.table,
{ textExpression: true, expectedTypes: ["string"] }
)
}
allowNull={true}
onEnter={(newValue) => {
if (newValue == null || newValue.trim() == "") {
this.clearMapping();
} else {
if (
Expression.parseTextExpression(newValue).isTrivialString()
) {
this.props.parent.onEditMappingHandler(
this.props.attribute,
{
type: MappingType.value,
value: newValue,
} as Specification.ValueMapping
);
} else {
this.props.parent.onEditMappingHandler(
this.props.attribute,
{
type: MappingType.text,
table: textMapping.table,
textExpression: newValue,
} as Specification.TextMapping
);
}
}
return true;
}}
/>
);
}
case MappingType.scale: {
const scaleMapping = mapping as Specification.ScaleMapping;
if (scaleMapping.scale) {
let scaleIcon = <span>f</span>;
if (this.props.type == "color") {
scaleIcon = <SVGImageIcon url={R.getSVGIcon("scale/color")} />;
}
return (
<span
className="el-mapping-scale"
ref={(e) => (this.scaleMappingDisplay = e)}
onClick={() => {
if (!scaleMapping || scaleMapping.valueIndex == undefined) {
const {
alignLeft,
alignX,
}: {
alignLeft: boolean;
alignX: PopupAlignment;
} = getAlignment(this.scaleMappingDisplay);
globals.popupController.popupAt(
(context) => (
<PopupView context={context}>
<DataMappAndScaleEditor
plotSegment={parentOfType(
(this.props.parent as any).objectClass.parent,
"plot-segment"
)}
attribute={this.props.attribute}
parent={this}
defaultMapping={mapping}
options={options}
alignLeft={alignLeft}
onClose={() => context.close()}
/>
</PopupView>
),
{ anchor: this.scaleMappingDisplay, alignX }
);
} else {
this.beginDataFieldValueSelection();
}
}}
>
<span className="el-mapping-scale-scale is-left">
{scaleIcon}
</span>
<svg width={6} height={20}>
<path d="M3.2514,10A17.37314,17.37314,0,0,1,6,0H0V20H6A17.37342,17.37342,0,0,1,3.2514,10Z" />
</svg>
<span className="el-mapping-scale-column">
{scaleMapping.expression}
</span>
<svg width={6} height={20}>
<path d="M2.7486,10A17.37314,17.37314,0,0,0,0,0H6V20H0A17.37342,17.37342,0,0,0,2.7486,10Z" />
</svg>
</span>
);
} else {
return (
<span className="el-mapping-scale">
<span className="el-mapping-scale-scale is-left">=</span>
<svg width={6} height={20}>
<path d="M3.2514,10A17.37314,17.37314,0,0,1,6,0H0V20H6A17.37342,17.37342,0,0,1,3.2514,10Z" />
</svg>
<span className="el-mapping-scale-column">
{scaleMapping.expression}
</span>
<svg width={6} height={20}>
<path d="M2.7486,10A17.37314,17.37314,0,0,0,0,0H6V20H0A17.37342,17.37342,0,0,0,2.7486,10Z" />
</svg>
</span>
);
}
}
default: {
return <span>(...)</span>;
}
}
}
}
// eslint-disable-next-line
public render() {
const parent = this.props.parent;
const attribute = this.props.attribute;
const options = this.props.options;
const currentMapping = parent.getAttributeMapping(attribute);
// If there is a mapping, also not having default or using auto
let shouldShowEraser =
currentMapping != null &&
(currentMapping.type != MappingType.value ||
!options.defaultValue ||
options.defaultAuto);
shouldShowEraser = shouldShowEraser || this.state.showNoneAsValue;
const shouldShowBindData = parent.onMapDataHandler != null;
const isDataMapping =
currentMapping != null && currentMapping.type == MappingType.scale;
shouldShowEraser = isDataMapping;
const valueIndex = currentMapping && (currentMapping as any).valueIndex;
if (this.props.options.openMapping) {
setTimeout(() => {
if (valueIndex == undefined) {
this.beginDataFieldSelection();
} else {
this.beginDataFieldValueSelection();
}
});
}
return (
<div
ref={(e) => (this.mappingButton = ReactDOM.findDOMNode(e) as Element)}
className="charticulator__widget-control-mapping-editor"
>
<DropZoneView
filter={(data) => {
if (!shouldShowBindData) {
return false;
}
if (data instanceof DragData.DataExpression) {
return isKindAcceptable(data.metadata.kind, options.acceptKinds);
} else {
return false;
}
}}
onDrop={(data: DragData.DataExpression, point, modifiers) => {
if (!options.hints) {
options.hints = {};
}
options.hints.newScale = modifiers.shiftKey;
options.hints.scaleID = data.scaleID;
const parsedExpression = Expression.parse(
data.expression
) as FunctionCall;
if (data.allowSelectValue && parsedExpression.name !== "get") {
data.expression = `get(${data.expression}, 0)`;
}
// because original mapping allowed it
if (parsedExpression.name === "get") {
data.allowSelectValue = true;
}
this.mapData(data, {
...options.hints,
allowSelectValue: data.allowSelectValue,
});
}}
className="charticulator__widget-control-mapping-editor"
>
{parent.horizontal(
[1, 0],
this.renderCurrentAttributeMapping(),
<span>
{shouldShowEraser ? (
<Button
icon="general/eraser"
active={false}
title="Remove"
onClick={() => {
if (parent.getAttributeMapping(attribute)) {
this.clearMapping();
}
this.setState({
showNoneAsValue: false,
});
}}
/>
) : null}
{valueIndex == undefined && shouldShowBindData ? (
<Button
icon={"general/bind-data"}
title="Bind data"
// ref={(e) =>
// (this.mappingButton = ReactDOM.findDOMNode(e) as Element)
// }
onClick={() => {
this.beginDataFieldSelection();
}}
active={isDataMapping}
/>
) : null}
{valueIndex != undefined ? (
<Button
icon={"general/bind-data"}
title="Bind data value"
// ref={(e) =>
// (this.mappingButton = ReactDOM.findDOMNode(e) as Element)
// }
onClick={() => {
this.beginDataFieldValueSelection();
}}
active={isDataMapping}
/>
) : null}
</span>
)}
</DropZoneView>
</div>
);
}
}
export interface DataMappAndScaleEditorProps {
plotSegment: ObjectClass;
attribute: string;
defaultMapping: Specification.Mapping;
options: Prototypes.Controls.MappingEditorOptions;
parent: MappingEditor;
onClose: () => void;
alignLeft?: boolean;
}
export interface DataMappAndScaleEditorState {
currentMapping: Specification.Mapping;
}
export class DataMappAndScaleEditor extends ContextedComponent<
DataMappAndScaleEditorProps,
DataMappAndScaleEditorState
> {
public state = {
currentMapping: this.props.defaultMapping,
};
private tokens: EventSubscription[];
public componentDidMount() {
this.tokens = [
this.props.parent.updateEvents.addListener("update", () => {
this.setState({
currentMapping: this.props.parent.props.parent.getAttributeMapping(
this.props.attribute
),
});
}),
];
}
public componentWillUnmount() {
for (const t of this.tokens) {
t.remove();
}
}
public renderScaleEditor() {
const mapping = this.state.currentMapping;
if (mapping && mapping.type == MappingType.scale) {
const scaleMapping = mapping as Specification.ScaleMapping;
if (scaleMapping.scale) {
const scaleObject = getById(
this.store.chart.scales,
scaleMapping.scale
);
if (scaleObject) {
return (
<ScaleEditor
plotSegment={this.props.plotSegment}
scale={scaleObject}
scaleMapping={scaleMapping}
store={this.store}
/>
);
} else {
return null;
}
}
}
return null;
}
public renderDataPicker() {
const options = this.props.options;
let currentExpression: string = null;
const mapping = this.state.currentMapping;
if (mapping != null && mapping.type == MappingType.scale) {
currentExpression = (mapping as Specification.ScaleMapping).expression;
}
return (
<div>
<DataFieldSelector
table={mapping ? (mapping as any).table : options.table}
datasetStore={this.store}
kinds={options.acceptKinds}
useAggregation={true}
defaultValue={
currentExpression
? { table: options.table, expression: currentExpression }
: null
}
nullDescription={strings.core.none}
nullNotHighlightable={true}
onChange={(value) => {
if (value != null) {
this.props.parent.mapData(
new DragData.DataExpression(
this.store.getTable(value.table),
value.expression,
value.type,
value.metadata,
value.rawExpression
),
options.hints
);
} else {
this.props.parent.clearMapping();
this.props.onClose();
}
}}
/>
</div>
);
}
public render() {
const scaleElement = this.renderScaleEditor();
if (scaleElement) {
return (
<div className="charticulator__data-mapping-and-scale-editor">
<div
className={
this.props.alignLeft ? "el-scale-editor-left" : "el-scale-editor"
}
>
{scaleElement}
</div>
<div className="el-data-picker">{this.renderDataPicker()}</div>
</div>
);
} else {
return (
<div className="charticulator__data-mapping-and-scale-editor">
<div className="el-data-picker">{this.renderDataPicker()}</div>
</div>
);
}
}
}
function parentOfType(p: ObjectClass, typeSought: string) {
while (p) {
if (Prototypes.isType(p.object.classID, typeSought)) {
return p;
}
p = p.parent;
}
} | the_stack |
import type {Mutable, Cursor} from "@swim/util";
import {BTree} from "@swim/collections";
import {AnyItem, Item, Field, Slot, AnyValue, Value, Record, AnyText, Text, AnyNum, MathModule} from "@swim/structure";
import {KeyEffect, MapOutlet} from "@swim/streamlet";
import {RecordStreamlet} from "./RecordStreamlet";
import {AbstractRecordOutlet} from "./AbstractRecordOutlet";
import {RecordFieldUpdater} from "./RecordFieldUpdater";
import {RecordScope} from "./"; // forward import
import {Reifier} from "./"; // forward import
import {Dataflow} from "./"; // forward import
/** @public */
export class RecordModel extends AbstractRecordOutlet {
constructor(state?: Record) {
super();
if (state === void 0) {
state = Record.create();
}
this.state = state;
this.fieldUpdaters = new BTree();
}
/** @internal */
readonly state: Record;
/** @internal */
readonly fieldUpdaters: BTree<Value, RecordFieldUpdater>;
override isEmpty(): boolean {
return this.state.isEmpty();
}
override isArray(): boolean {
return this.state.isArray();
}
override isObject(): boolean {
return this.state.isObject();
}
override get length(): number {
return this.state.length;
}
declare readonly fieldCount: number; // getter defined below to work around useDefineForClassFields lunacy
override get valueCount(): number {
return this.state.valueCount;
}
override has(key: AnyValue): boolean {
if (this.state.has(key)) {
return true;
} else {
const scope = this.streamletScope;
return scope instanceof Record ? scope.has(key) : false;
}
}
override hasOwn(key: AnyValue): boolean {
return this.state.has(key);
}
override indexOf(item: AnyItem, index?: number): number {
return this.state.indexOf(item, index);
}
override lastIndexOf(item: AnyItem, index: number = 0): number {
return this.state.lastIndexOf(item, index);
}
override get(): Record;
override get(key: AnyValue): Value;
override get(key?: AnyValue): Record | Value {
if (key === void 0) {
return this;
} else {
key = Value.fromAny(key);
let value = this.state.get(key);
if (!value.isDefined()) {
const scope = this.streamletScope;
if (scope instanceof Record) {
value = scope.get(key);
}
}
return value;
}
}
override getAttr(key: AnyText): Value {
key = Text.fromAny(key);
let value = this.state.getAttr(key);
if (!value.isDefined()) {
const scope = this.streamletScope;
if (scope instanceof Record) {
value = scope.getAttr(key);
}
}
return value;
}
override getSlot(key: AnyValue): Value {
key = Value.fromAny(key);
let value = this.state.getSlot(key);
if (!value.isDefined()) {
const scope = this.streamletScope;
if (scope instanceof Record) {
value = scope.getSlot(key);
}
}
return value;
}
override getField(key: AnyValue): Field | undefined {
key = Value.fromAny(key);
let field = this.state.getField(key);
if (field === void 0) {
const scope = this.streamletScope;
if (scope instanceof Record) {
field = scope.getField(key);
}
}
return field;
}
override getItem(index: AnyNum): Item {
return this.state.getItem(index);
}
bindValue(key: Value, expr: Value): void {
const fieldUpdater = new RecordFieldUpdater(this, key);
const valueInput = Dataflow.compile(expr, this);
fieldUpdater.bindInput(valueInput);
// TODO: clean up existing field updater
(this as Mutable<this>).fieldUpdaters = this.fieldUpdaters.updated(key, fieldUpdater);
}
override set(key: AnyValue, newValue: AnyValue): this {
key = Value.fromAny(key);
if (!this.state.has(key)) {
const scope = this.streamletScope;
if (scope instanceof Record && scope.has(key)) {
scope.set(key, newValue);
} else {
this.state.set(key, newValue);
}
} else {
this.state.set(key, newValue);
}
this.decohereInputKey(key, KeyEffect.Update);
return this;
}
override setAttr(key: AnyText, newValue: AnyValue): this {
key = Text.fromAny(key);
if (!this.state.has(key)) {
const scope = this.streamletScope;
if (scope instanceof Record && scope.has(key)) {
scope.setAttr(key, newValue);
} else {
this.state.setAttr(key, newValue);
}
} else {
this.state.setAttr(key, newValue);
}
this.decohereInputKey(key, KeyEffect.Update);
return this;
}
override setSlot(key: AnyValue, newValue: AnyValue): this {
key = Value.fromAny(key);
if (!this.state.has(key)) {
const scope = this.streamletScope;
if (scope instanceof Record && scope.has(key)) {
scope.setSlot(key, newValue);
} else {
this.state.setSlot(key, newValue);
}
} else {
this.state.setSlot(key, newValue);
}
this.decohereInputKey(key, KeyEffect.Update);
return this;
}
override setItem(index: number, newItem: AnyItem): this {
const oldItem = this.state.getItem(index);
newItem = Item.fromAny(newItem);
this.state.setItem(index, newItem);
if (oldItem instanceof Field && newItem instanceof Field) {
if (oldItem.key.equals(newItem.key)) {
this.decohereInputKey(oldItem.key, KeyEffect.Update);
} else {
this.decohereInputKey(oldItem.key, KeyEffect.Remove);
this.decohereInputKey(newItem.key, KeyEffect.Update);
}
} else if (oldItem instanceof Field) {
this.decohereInputKey(oldItem.key, KeyEffect.Remove);
} else if (newItem instanceof Field) {
this.decohereInputKey(newItem.key, KeyEffect.Update);
} else {
this.decohereInput();
}
return this;
}
override push(...newItems: AnyItem[]): number {
let i = this.state.length;
const n = this.state.push(...newItems);
while (i < n) {
const newItem = this.state.get(i);
if (newItem instanceof Field) {
this.decohereInputKey(newItem.key, KeyEffect.Update);
}
i += 1;
}
return n;
}
override splice(start: number, deleteCount: number = 0, ...newItems: AnyItem[]): Item[] {
const n = this.state.length;
if (start < 0) {
start = n + start;
}
start = Math.max(0, start);
deleteCount = Math.max(0, deleteCount);
const deleted = this.state.splice(start, deleteCount, ...newItems);
for (let i = 0; i < deleted.length; i += 1) {
const oldItem = deleted[i];
if (oldItem instanceof Field) {
this.decohereInputKey(oldItem.key, KeyEffect.Remove);
}
}
for (let i = start; i < start + newItems.length; i += 1) {
const newItem = this.state.get(i);
if (newItem instanceof Field) {
this.decohereInputKey(newItem.key, KeyEffect.Update);
}
}
return deleted;
}
override delete(key: AnyValue): Item {
const oldItem = this.state.delete(key);
if (oldItem instanceof Field) {
this.decohereInputKey(oldItem.key, KeyEffect.Remove);
}
return oldItem;
}
override clear(): void {
const oldState = this.state.branch();
this.state.clear();
oldState.forEach(function (oldItem: Item): void {
if (oldItem instanceof Field) {
this.decohereInputKey(oldItem.key, KeyEffect.Remove);
}
}, this);
}
override forEach<T>(callback: (item: Item, index: number) => T | void): T | undefined;
override forEach<T, S>(callback: (this: S, item: Item, index: number) => T | void,
thisArg: S): T | undefined;
override forEach<T, S>(callback: (this: S | undefined, item: Item, index: number) => T | void,
thisArg?: S): T | undefined {
return this.state.forEach(callback, thisArg);
}
override keyIterator(): Cursor<Value> {
throw new Error(); // TODO
}
override disconnectInputs(): void {
const oldFieldUpdaters = this.fieldUpdaters;
if (!oldFieldUpdaters.isEmpty()) {
(this as Mutable<this>).fieldUpdaters = new BTree();
oldFieldUpdaters.forEach(function (key: Value, inlet: RecordFieldUpdater): void {
inlet.disconnectInputs();
}, this);
}
}
override memoize(): MapOutlet<Value, Value, Record> {
return this;
}
materialize(record: Record): void {
record.forEach(function (item: Item): void {
this.materializeItem(item);
}, this);
}
materializeItem(item: Item): void {
if (item instanceof Field) {
this.materializeField(item);
} else {
this.materializeValue(item);
}
}
materializeField(field: Field): void {
const value = field.value;
if (value instanceof RecordStreamlet) {
value.setStreamletScope(this);
this.state.push(field);
} else if (value instanceof Record) {
// Add recursively materialized nested scope.
const child = new RecordScope(this);
child.materialize(value);
this.state.push(field.updatedValue(child));
} else {
this.state.push(field);
}
}
materializeValue(value: Value): void {
if (value instanceof RecordStreamlet) {
value.setStreamletScope(this);
this.state.push(value);
} else if (value instanceof Record) {
// Add recursively materialized nested scope.
const child = new RecordScope(this);
child.materialize(value);
this.state.push(child);
} else {
this.state.push(value);
}
}
compile(record: Record): void {
record.forEach(function (item: Item, index: number): void {
this.compileItem(item, index);
}, this);
}
compileItem(item: Item, index: number): void {
if (item instanceof Field) {
this.compileField(item, index);
} else {
this.compileValue(item, index);
}
}
compileField(field: Field, index: number): void {
const key = field.key;
const value = field.value;
if (!key.isConstant()) {
// TODO: Add dynamic key updater.
} else if (!value.isConstant()) {
if (value instanceof RecordStreamlet) {
// Lexically bind nested streamlet.
value.compile();
// Decohere nested scope key.
this.decohereInputKey(key, KeyEffect.Update);
} else if (value instanceof Record) {
// Recursively compile nested scope.
(this.state.getItem(index).toValue() as RecordModel).compile(value);
// Decohere nested scope key.
this.decohereInputKey(key, KeyEffect.Update);
} else {
// Set placeholder value.
field.setValue(Value.extant());
// Bind dynamic value updater.
this.bindValue(key, value);
}
} else {
// Decohere constant key.
this.decohereInputKey(key, KeyEffect.Update);
}
}
compileValue(value: Value, index: number): void {
if (value instanceof RecordStreamlet) {
value.compile();
} else if (value instanceof Record) {
// Recursively compile nested scope.
(this.state.getItem(index) as RecordModel).compile(value);
} else if (!value.isConstant()) {
// TODO: Bind dynamic item updater.
} else {
// TODO: Fold constant expressions.
}
}
/** @beta */
reify(reifier: Reifier | null = Reifier.system()): void {
this.forEach(function (oldItem: Item, index: number): void {
const newItem = this.reifyItem(oldItem, reifier);
if (oldItem !== newItem) {
this.setItem(index, newItem);
}
}, this);
}
/** @beta */
reifyItem(item: Item, reifier: Reifier | null): Item {
if (reifier !== null) {
item = reifier.reify(item);
}
const scope = this.streamletScope;
if (scope instanceof RecordModel) {
return scope.reifyItem(item, reifier);
} else {
return item;
}
}
static from(record: Record): RecordModel {
const model = new RecordModel();
model.materialize(record);
model.compile(record);
return model;
}
static override of(...items: AnyItem[]): RecordModel {
return RecordModel.from(Record.of(...items));
}
static override globalScope(): RecordModel {
const model = new RecordModel();
model.materializeField(Slot.of("math", MathModule.scope.branch()));
return model;
}
}
Object.defineProperty(RecordModel.prototype, "fieldCount", {
get(this: RecordModel): number {
return this.state.fieldCount;
},
configurable: true,
}); | the_stack |
import { ECObjectsError, ECObjectsStatus } from "../Exception";
import { CustomAttribute } from "../Metadata/CustomAttribute";
import { CustomAttributeClass } from "../Metadata/CustomAttributeClass";
import { ECName } from "../ECName";
import { AbstractParser, CAProviderTuple } from "./AbstractParser";
import {
ConstantProps, CustomAttributeClassProps, EntityClassProps, EnumerationProps, FormatProps, InvertedUnitProps, KindOfQuantityProps, MixinProps,
NavigationPropertyProps, PhenomenonProps, PrimitiveArrayPropertyProps, PrimitiveOrEnumPropertyBaseProps, PrimitivePropertyProps,
PropertyCategoryProps, PropertyProps, RelationshipClassProps, SchemaProps, SchemaReferenceProps, StructArrayPropertyProps, StructClassProps,
StructPropertyProps, UnitProps, UnitSystemProps,
} from "./JsonProps";
interface UnknownObject { readonly [name: string]: unknown }
function isObject(x: unknown): x is UnknownObject {
return typeof (x) === "object";
}
/** @internal */
export class JsonParser extends AbstractParser<UnknownObject> {
private _rawSchema: UnknownObject;
private _schemaName?: string;
private _currentItemFullName?: string;
constructor(rawSchema: Readonly<unknown>) {
super();
if (!isObject(rawSchema))
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `Invalid JSON object.`);
this._rawSchema = rawSchema;
this._schemaName = rawSchema.name as string | undefined;
}
/**
* Type checks Schema and returns SchemaProps interface
* @param this._rawSchema
* @returns SchemaProps
*/
public parseSchema(): SchemaProps {
if (undefined === this._rawSchema.name)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `An ECSchema is missing the required 'name' attribute.`);
if (typeof (this._rawSchema.name) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `An ECSchema has an invalid 'name' attribute. It should be of type 'string'.`);
if (undefined === this._rawSchema.$schema)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECSchema ${this._schemaName} is missing the required '$schema' attribute.`);
if (typeof (this._rawSchema.$schema) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECSchema ${this._schemaName} has an invalid '$schema' attribute. It should be of type 'string'.`);
if (undefined === this._rawSchema.version)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECSchema ${this._schemaName} is missing the required 'version' attribute.`);
if (typeof (this._rawSchema.version) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECSchema ${this._schemaName} has an invalid 'version' attribute. It should be of type 'string'.`);
if (undefined !== this._rawSchema.alias) {
if (typeof (this._rawSchema.alias) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECSchema ${this._schemaName} has an invalid 'alias' attribute. It should be of type 'string'.`);
}
if (undefined !== this._rawSchema.label) {
if (typeof (this._rawSchema.label) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECSchema ${this._schemaName} has an invalid 'label' attribute. It should be of type 'string'.`);
}
if (undefined !== this._rawSchema.description) {
if (typeof (this._rawSchema.description) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECSchema ${this._schemaName} has an invalid 'description' attribute. It should be of type 'string'.`);
}
return (this._rawSchema as unknown) as SchemaProps;
}
public *getReferences(): Iterable<SchemaReferenceProps> {
if (undefined !== this._rawSchema.references) {
if (!Array.isArray(this._rawSchema.references))
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The schema ${this._rawSchema.name} has an invalid 'references' attribute. It should be of type 'object[]'.`);
for (const ref of this._rawSchema.references) {
yield this.checkSchemaReference(ref);
}
}
}
private checkSchemaReference(jsonObj: Readonly<unknown>): SchemaReferenceProps {
if (!isObject(jsonObj))
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The schema ${this._schemaName} has an invalid 'references' attribute. It should be of type 'object[]'.`);
if (undefined === jsonObj.name)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The schema ${this._schemaName} has an invalid 'references' attribute. One of the references is missing the required 'name' attribute.`);
if (typeof (jsonObj.name) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The schema ${this._schemaName} has an invalid 'references' attribute. One of the references has an invalid 'name' attribute. It should be of type 'string'.`);
if (undefined === jsonObj.version)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The schema ${this._schemaName} has an invalid 'references' attribute. One of the references is missing the required 'version' attribute.`);
if (typeof (jsonObj.version) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The schema ${this._schemaName} has an invalid 'references' attribute. One of the references has an invalid 'version' attribute. It should be of type 'string'.`);
return (jsonObj as unknown) as SchemaReferenceProps;
}
public *getItems(): Iterable<[string, string, UnknownObject]> {
const items = this._rawSchema.items;
if (undefined !== items) {
if (!isObject(items) || Array.isArray(items))
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The schema ${this._schemaName} has an invalid 'items' attribute. It should be of type 'object'.`);
// eslint-disable-next-line guard-for-in
for (const itemName in items) {
const item = items[itemName];
if (!isObject(item))
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `A SchemaItem in ${this._schemaName} is an invalid JSON object.`);
if (!ECName.validate(itemName))
throw new ECObjectsError(ECObjectsStatus.InvalidECName, `A SchemaItem in ${this._schemaName} has an invalid 'name' attribute. '${itemName}' is not a valid ECName.`);
if (undefined === item.schemaItemType)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The SchemaItem ${this._schemaName}.${itemName} is missing the required 'schemaItemType' attribute.`);
if (typeof (item.schemaItemType) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The SchemaItem ${this._schemaName}.${itemName} has an invalid 'schemaItemType' attribute. It should be of type 'string'.`);
this._currentItemFullName = `${this._schemaName}.${itemName}`;
yield [itemName, item.schemaItemType, item];
}
}
}
public findItem(itemName: string): [string, string, UnknownObject] | undefined {
const items = this._rawSchema.items;
if (undefined !== items) {
if (!isObject(items) || Array.isArray(items))
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The schema ${this._schemaName} has an invalid 'items' attribute. It should be of type 'object'.`);
const item = items[itemName];
if (undefined !== item) {
if (!isObject(item))
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `A SchemaItem in ${this._schemaName} is an invalid JSON object.`);
if (!ECName.validate(itemName))
throw new ECObjectsError(ECObjectsStatus.InvalidECName, `A SchemaItem in ${this._schemaName} has an invalid 'name' attribute. '${itemName}' is not a valid ECName.`);
if (undefined === item.schemaItemType)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The SchemaItem ${this._schemaName}.${itemName} is missing the required 'schemaItemType' attribute.`);
if (typeof (item.schemaItemType) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The SchemaItem ${this._schemaName}.${itemName} has an invalid 'schemaItemType' attribute. It should be of type 'string'.`);
this._currentItemFullName = `${this._schemaName}.${itemName}`;
return [itemName, item.schemaItemType, item];
}
}
return undefined;
}
/**
* Type checks all Schema Item attributes.
* @param jsonObj The JSON object to check if it represents a Schema Item.
*/
private checkSchemaItemProps(jsonObj: UnknownObject): void {
if (undefined !== jsonObj.description) {
if (typeof (jsonObj.description) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The SchemaItem ${this._currentItemFullName} has an invalid 'description' attribute. It should be of type 'string'.`);
}
if (undefined !== jsonObj.label) {
if (typeof (jsonObj.label) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The SchemaItem ${this._currentItemFullName} has an invalid 'label' attribute. It should be of type 'string'.`);
}
}
public *getProperties(jsonObj: UnknownObject): Iterable<[string, string, UnknownObject]> {
const properties = jsonObj.properties;
if (undefined !== properties) {
if (!Array.isArray(properties))
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECClass ${this._currentItemFullName} has an invalid 'properties' attribute. It should be of type 'object[]'.`);
for (const property of properties as unknown[]) {
if (!isObject(property))
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `An ECProperty in ${this._currentItemFullName} is an invalid JSON object.`);
if (undefined === property.name)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `An ECProperty in ${this._currentItemFullName} is missing the required 'name' attribute.`);
if (typeof (property.name) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `An ECProperty in ${this._currentItemFullName} has an invalid 'name' attribute. It should be of type 'string'.`);
if (undefined === property.type)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECProperty ${this._currentItemFullName}.${property.name} does not have the required 'type' attribute.`);
if (typeof (property.type) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECProperty ${this._currentItemFullName}.${property.name} has an invalid 'type' attribute. It should be of type 'string'.`);
if (!this.isValidPropertyType(property.type))
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECProperty ${this._currentItemFullName}.${property.name} has an invalid 'type' attribute. '${property.type}' is not a valid type.`);
yield [property.name, property.type, property];
}
}
}
/**
* Type checks Class and returns ClassProps interface
* @param jsonObj The JSON object to check if it represents a Class.
*/
private checkClassProps(jsonObj: UnknownObject): void {
this.checkSchemaItemProps(jsonObj);
if (undefined !== jsonObj.modifier) {
if (typeof (jsonObj.modifier) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECClass ${this._currentItemFullName} has an invalid 'modifier' attribute. It should be of type 'string'.`);
}
if (undefined !== jsonObj.baseClass) {
if (typeof (jsonObj.baseClass) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECClass ${this._currentItemFullName} has an invalid 'baseClass' attribute. It should be of type 'string'.`);
}
if (undefined !== jsonObj.customAttributes) {
if (!Array.isArray(jsonObj.customAttributes)) {
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECClass ${this._currentItemFullName} has an invalid 'customAttributes' attribute. It should be of type 'array'.`);
}
}
}
/**
* Type checks entity class and returns EntityClassProps interface
* @param jsonObj
* @returns EntityClassProps
*/
public parseEntityClass(jsonObj: UnknownObject): EntityClassProps {
this.checkClassProps(jsonObj);
if (undefined !== jsonObj.mixins) {
if (!Array.isArray(jsonObj.mixins))
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECEntityClass ${this._currentItemFullName} has an invalid 'mixins' attribute. It should be of type 'string[]'.`);
for (const mixinName of jsonObj.mixins) {
if (typeof (mixinName) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECEntityClass ${this._currentItemFullName} has an invalid 'mixins' attribute. It should be of type 'string[]'.`);
}
}
return jsonObj as EntityClassProps;
}
/**
* Type checks mixin and returns MixinProps interface
* @param jsonObj
* @returns MixinProps
*/
public parseMixin(jsonObj: UnknownObject): MixinProps {
this.checkClassProps(jsonObj);
if (undefined === jsonObj.appliesTo)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Mixin ${this._currentItemFullName} is missing the required 'appliesTo' attribute.`);
if (typeof (jsonObj.appliesTo) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Mixin ${this._currentItemFullName} has an invalid 'appliesTo' attribute. It should be of type 'string'.`);
return (jsonObj as unknown) as MixinProps;
}
/**
* Type checks custom attribute class and returns CustomAttributeClassProps interface
* @param jsonObj
* @returns CustomAttributeClassProps
*/
public parseCustomAttributeClass(jsonObj: UnknownObject): CustomAttributeClassProps {
this.checkClassProps(jsonObj);
if (undefined === jsonObj.appliesTo)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The CustomAttributeClass ${this._currentItemFullName} is missing the required 'appliesTo' attribute.`);
if (typeof (jsonObj.appliesTo) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The CustomAttributeClass ${this._currentItemFullName} has an invalid 'appliesTo' attribute. It should be of type 'string'.`);
return (jsonObj as unknown) as CustomAttributeClassProps;
}
public parseStructClass(jsonObj: UnknownObject): StructClassProps {
this.checkClassProps(jsonObj);
return jsonObj as StructClassProps;
}
public parseUnitSystem(jsonObj: UnknownObject): UnitSystemProps {
this.checkSchemaItemProps(jsonObj);
return jsonObj as UnitSystemProps;
}
/**
* Type checks Relationship Class and returns RelationshipClassProps interface
* @param jsonObj
* @returns RelationshipClassProps
*/
public parseRelationshipClass(jsonObj: UnknownObject): RelationshipClassProps {
this.checkClassProps(jsonObj);
if (undefined === jsonObj.strength)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The RelationshipClass ${this._currentItemFullName} is missing the required 'strength' attribute.`);
if (typeof (jsonObj.strength) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The RelationshipClass ${this._currentItemFullName} has an invalid 'strength' attribute. It should be of type 'string'.`);
if (undefined === jsonObj.strengthDirection)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The RelationshipClass ${this._currentItemFullName} is missing the required 'strengthDirection' attribute.`);
if (typeof (jsonObj.strengthDirection) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The RelationshipClass ${this._currentItemFullName} has an invalid 'strengthDirection' attribute. It should be of type 'string'.`);
if (undefined === jsonObj.source)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The RelationshipClass ${this._currentItemFullName} is missing the required source constraint.`);
if (!isObject(jsonObj.source))
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The RelationshipClass ${this._currentItemFullName} has an invalid source constraint. It should be of type 'object'.`);
this.checkRelationshipConstraintProps(jsonObj.source, true);
if (undefined === jsonObj.target)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The RelationshipClass ${this._currentItemFullName} is missing the required target constraint.`);
if (!isObject(jsonObj.target))
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The RelationshipClass ${this._currentItemFullName} has an invalid target constraint. It should be of type 'object'.`);
this.checkRelationshipConstraintProps(jsonObj.target, false);
return (jsonObj as unknown) as RelationshipClassProps;
}
/**
* Type checks Relationship Constraint and returns RelationshipConstraintProps interface.
* @param jsonObj
* @param isSource For sake of error message, is this relationship constraint a source or target
* @returns RelationshipConstraintProps
*/
private checkRelationshipConstraintProps(jsonObj: UnknownObject, isSource: boolean): void {
const constraintName = `${(isSource) ? "Source" : "Target"} Constraint of ${this._currentItemFullName}`; // most specific name to call RelationshipConstraint
if (undefined === jsonObj.multiplicity)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ${constraintName} is missing the required 'multiplicity' attribute.`);
if (typeof (jsonObj.multiplicity) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ${constraintName} has an invalid 'multiplicity' attribute. It should be of type 'string'.`);
if (undefined === jsonObj.roleLabel)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ${constraintName} is missing the required 'roleLabel' attribute.`);
if (typeof (jsonObj.roleLabel) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ${constraintName} has an invalid 'roleLabel' attribute. It should be of type 'string'.`);
if (undefined === jsonObj.polymorphic)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ${constraintName} is missing the required 'polymorphic' attribute.`);
if (typeof (jsonObj.polymorphic) !== "boolean")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ${constraintName} has an invalid 'polymorphic' attribute. It should be of type 'boolean'.`);
if (undefined !== jsonObj.abstractConstraint && typeof (jsonObj.abstractConstraint) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ${constraintName} has an invalid 'abstractConstraint' attribute. It should be of type 'string'.`);
if (undefined === jsonObj.constraintClasses)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ${constraintName} is missing the required 'constraintClasses' attribute.`);
if (!Array.isArray(jsonObj.constraintClasses))
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ${constraintName} has an invalid 'constraintClasses' attribute. It should be of type 'string[]'.`);
for (const constraintClassName of jsonObj.constraintClasses) {
if (typeof (constraintClassName) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ${constraintName} has an invalid 'constraintClasses' attribute. It should be of type 'string[]'.`);
}
if (undefined !== jsonObj.customAttributes && !Array.isArray(jsonObj.customAttributes))
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ${constraintName} has an invalid 'customAttributes' attribute. It should be of type 'array'.`);
}
/**
* Type checks Enumeration and returns EnumerationProps interface
* @param jsonObj
* @returns EnumerationProps
*/
public parseEnumeration(jsonObj: UnknownObject): EnumerationProps {
this.checkSchemaItemProps(jsonObj);
if (undefined === jsonObj.type)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Enumeration ${this._currentItemFullName} is missing the required 'type' attribute.`);
if (typeof (jsonObj.type) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Enumeration ${this._currentItemFullName} has an invalid 'type' attribute. It should be of type 'string'.`);
const isValidEnumerationType = (type: string): boolean => {
type = type.toLowerCase();
return (type === "int") ||
(type === "integer") ||
(type === "string");
};
if (!isValidEnumerationType(jsonObj.type))
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Enumeration ${this._currentItemFullName} has an invalid 'type' attribute. It should be either "int" or "string".`);
if (undefined !== jsonObj.isStrict) { // TODO: make required
if (typeof (jsonObj.isStrict) !== "boolean")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Enumeration ${this._currentItemFullName} has an invalid 'isStrict' attribute. It should be of type 'boolean'.`);
}
if (undefined === jsonObj.enumerators)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Enumeration ${this._currentItemFullName} is missing the required 'enumerators' attribute.`);
if (!Array.isArray(jsonObj.enumerators))
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Enumeration ${this._currentItemFullName} has an invalid 'enumerators' attribute. It should be of type 'object[]'.`);
for (const enumerator of jsonObj.enumerators) {
if (!isObject(enumerator))
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Enumeration ${this._currentItemFullName} has an invalid 'enumerators' attribute. It should be of type 'object[]'.`);
if (undefined === enumerator.value)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Enumeration ${this._currentItemFullName} has an enumerator that is missing the required attribute 'value'.`);
// TODO: Should this really be handled here?
const expectedType = jsonObj.type;
const receivedType = (typeof (enumerator.value) === "number") ? "int" : typeof (enumerator.value);
if (!expectedType.includes(receivedType)) // is receivedType a substring of expectedType? - easiest way to check "int" === "int" | "integer" && "string" === "string"
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Enumeration ${this._currentItemFullName} has an incompatible type. It must be "${expectedType}", not "${receivedType}".`);
if (undefined === enumerator.name)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Enumeration ${this._currentItemFullName} has an enumerator that is missing the required attribute 'name'.`);
if (typeof (enumerator.name) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Enumeration ${this._currentItemFullName} has an enumerator with an invalid 'name' attribute. It should be of type 'string'.`);
if (undefined !== enumerator.label) {
if (typeof (enumerator.label) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Enumeration ${this._currentItemFullName} has an enumerator with an invalid 'label' attribute. It should be of type 'string'.`);
}
if (undefined !== enumerator.description) {
if (typeof (enumerator.description) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Enumeration ${this._currentItemFullName} has an enumerator with an invalid 'description' attribute. It should be of type 'string'.`);
}
}
return (jsonObj as unknown) as EnumerationProps;
}
/**
* Type checks KindOfQuantity and returns KindOfQuantityProps interface
* @param jsonObj
* @returns KindOfQuantityProps
*/
public parseKindOfQuantity(jsonObj: UnknownObject): KindOfQuantityProps {
this.checkSchemaItemProps(jsonObj);
if (undefined === jsonObj.relativeError)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The KindOfQuantity ${this._currentItemFullName} is missing the required 'relativeError' attribute.`);
if (typeof (jsonObj.relativeError) !== "number")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The KindOfQuantity ${this._currentItemFullName} has an invalid 'relativeError' attribute. It should be of type 'number'.`);
if (undefined !== jsonObj.presentationUnits) {
if (!Array.isArray(jsonObj.presentationUnits) && typeof (jsonObj.presentationUnits) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The KindOfQuantity ${this._currentItemFullName} has an invalid 'presentationUnits' attribute. It should be of type 'string' or 'string[]'.`);
}
if (undefined === jsonObj.persistenceUnit)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The KindOfQuantity ${this._currentItemFullName} is missing the required 'persistenceUnit' attribute.`);
if (typeof (jsonObj.persistenceUnit) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The KindOfQuantity ${this._currentItemFullName} has an invalid 'persistenceUnit' attribute. It should be of type 'string'.`);
return (jsonObj as unknown) as KindOfQuantityProps;
}
/**
* Type checks Property Category and returns PropertyCategoryProps interface
* @param jsonObj
* @returns PropertyCategoryProps
*/
public parsePropertyCategory(jsonObj: UnknownObject): PropertyCategoryProps {
this.checkSchemaItemProps(jsonObj);
if (undefined !== jsonObj.priority) { // TODO: make required
if (typeof (jsonObj.priority) !== "number")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The PropertyCategory ${this._currentItemFullName} has an invalid 'priority' attribute. It should be of type 'number'.`);
}
return (jsonObj as unknown) as PropertyCategoryProps;
}
/**
* Type checks unit and returns UnitProps interface
* @param jsonObj
* @returns UnitProps
*/
public parseUnit(jsonObj: UnknownObject): UnitProps {
this.checkSchemaItemProps(jsonObj);
if (undefined === jsonObj.phenomenon)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Unit ${this._currentItemFullName} does not have the required 'phenomenon' attribute.`);
if (typeof (jsonObj.phenomenon) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Unit ${this._currentItemFullName} has an invalid 'phenomenon' attribute. It should be of type 'string'.`);
if (undefined === jsonObj.unitSystem)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Unit ${this._currentItemFullName} does not have the required 'unitSystem' attribute.`);
if (typeof (jsonObj.unitSystem) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Unit ${this._currentItemFullName} has an invalid 'unitSystem' attribute. It should be of type 'string'.`);
if (undefined === jsonObj.definition)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Unit ${this._currentItemFullName} does not have the required 'definition' attribute.`);
if (typeof (jsonObj.definition) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Unit ${this._currentItemFullName} has an invalid 'definition' attribute. It should be of type 'string'.`);
if (undefined !== jsonObj.numerator) {
if (typeof (jsonObj.numerator) !== "number")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Unit ${this._currentItemFullName} has an invalid 'numerator' attribute. It should be of type 'number'.`);
}
if (undefined !== jsonObj.denominator) {
if (typeof (jsonObj.denominator) !== "number")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Unit ${this._currentItemFullName} has an invalid 'denominator' attribute. It should be of type 'number'.`);
}
if (undefined !== jsonObj.offset) {
if (typeof (jsonObj.offset) !== "number")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Unit ${this._currentItemFullName} has an invalid 'offset' attribute. It should be of type 'number'.`);
}
return (jsonObj as unknown) as UnitProps;
}
/**
* Type checks inverted unit and returns InvertedUnitProps interface
* @param jsonObj
* @returns InvertedUnitProps
*/
public parseInvertedUnit(jsonObj: UnknownObject): InvertedUnitProps {
this.checkSchemaItemProps(jsonObj);
if (undefined === jsonObj.invertsUnit)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The InvertedUnit ${this._currentItemFullName} does not have the required 'invertsUnit' attribute.`);
if (typeof (jsonObj.invertsUnit) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The InvertedUnit ${this._currentItemFullName} has an invalid 'invertsUnit' attribute. It should be of type 'string'.`);
if (undefined === jsonObj.unitSystem)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The InvertedUnit ${this._currentItemFullName} does not have the required 'unitSystem' attribute.`);
if (typeof (jsonObj.unitSystem) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The InvertedUnit ${this._currentItemFullName} has an invalid 'unitSystem' attribute. It should be of type 'string'.`);
return (jsonObj as unknown) as InvertedUnitProps;
}
/**
* Type checks constant and returns ConstantProps interface
* @param jsonObj
* @returns ConstantProps
*/
public parseConstant(jsonObj: UnknownObject): ConstantProps {
this.checkSchemaItemProps(jsonObj);
if (undefined === jsonObj.phenomenon)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Constant ${this._currentItemFullName} does not have the required 'phenomenon' attribute.`);
if (typeof (jsonObj.phenomenon) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Constant ${this._currentItemFullName} has an invalid 'phenomenon' attribute. It should be of type 'string'.`);
if (undefined === jsonObj.definition)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Constant ${this._currentItemFullName} does not have the required 'definition' attribute.`);
if (typeof (jsonObj.definition) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Constant ${this._currentItemFullName} has an invalid 'definition' attribute. It should be of type 'string'.`);
if (undefined !== jsonObj.numerator) {
if (typeof (jsonObj.numerator) !== "number")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Constant ${this._currentItemFullName} has an invalid 'numerator' attribute. It should be of type 'number'.`);
}
if (undefined !== jsonObj.denominator) {
if (typeof (jsonObj.denominator) !== "number")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Constant ${this._currentItemFullName} has an invalid 'denominator' attribute. It should be of type 'number'.`);
}
return (jsonObj as unknown) as ConstantProps;
}
/**
* Type checks phenomenon and returns PhenomenonProps interface
* @param jsonObj
* @returns PhenomenonProps
*/
public parsePhenomenon(jsonObj: UnknownObject): PhenomenonProps {
this.checkSchemaItemProps(jsonObj);
if (undefined === jsonObj.definition)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Phenomenon ${this._currentItemFullName} does not have the required 'definition' attribute.`);
if (typeof (jsonObj.definition) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Phenomenon ${this._currentItemFullName} has an invalid 'definition' attribute. It should be of type 'string'.`);
return (jsonObj as unknown) as PhenomenonProps;
}
/**
* Type checks format and returns FormatProps interface
* @param jsonObj
* @returns FormatProps
*/
public parseFormat(jsonObj: UnknownObject): FormatProps {
this.checkSchemaItemProps(jsonObj);
if (undefined === jsonObj.type)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this._currentItemFullName} does not have the required 'type' attribute.`);
if (typeof (jsonObj.type) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this._currentItemFullName} has an invalid 'type' attribute. It should be of type 'string'.`);
if (undefined !== jsonObj.precision && typeof (jsonObj.precision) !== "number")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this._currentItemFullName} has an invalid 'precision' attribute. It should be of type 'number'.`);
if (undefined !== jsonObj.roundFactor && typeof (jsonObj.roundFactor) !== "number")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this._currentItemFullName} has an invalid 'roundFactor' attribute. It should be of type 'number'.`);
if (undefined !== jsonObj.minWidth && typeof (jsonObj.minWidth) !== "number")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this._currentItemFullName} has an invalid 'minWidth' attribute. It should be of type 'number'.`);
if (undefined !== jsonObj.showSignOption && typeof (jsonObj.showSignOption) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this._currentItemFullName} has an invalid 'showSignOption' attribute. It should be of type 'string'.`);
if (undefined !== jsonObj.formatTraits) {
if (!Array.isArray(jsonObj.formatTraits) && typeof (jsonObj.formatTraits) !== "string") // must be either an array of strings or a string
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this._currentItemFullName} has an invalid 'formatTraits' attribute. It should be of type 'string' or 'string[]'.`);
}
if (undefined !== jsonObj.decimalSeparator && typeof (jsonObj.decimalSeparator) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this._currentItemFullName} has an invalid 'decimalSeparator' attribute. It should be of type 'string'.`);
if (undefined !== jsonObj.thousandSeparator && typeof (jsonObj.thousandSeparator) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this._currentItemFullName} has an invalid 'thousandSeparator' attribute. It should be of type 'string'.`);
if (undefined !== jsonObj.uomSeparator && typeof (jsonObj.uomSeparator) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this._currentItemFullName} has an invalid 'uomSeparator' attribute. It should be of type 'string'.`);
if (undefined !== jsonObj.scientificType && typeof (jsonObj.scientificType) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this._currentItemFullName} has an invalid 'scientificType' attribute. It should be of type 'string'.`);
if (undefined !== jsonObj.stationOffsetSize && typeof (jsonObj.stationOffsetSize) !== "number")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this._currentItemFullName} has an invalid 'stationOffsetSize' attribute. It should be of type 'number'.`);
if (undefined !== jsonObj.stationSeparator && typeof (jsonObj.stationSeparator) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this._currentItemFullName} has an invalid 'stationSeparator' attribute. It should be of type 'string'.`);
if (undefined !== jsonObj.composite) { // optional
if (!isObject(jsonObj.composite))
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this._currentItemFullName} has an invalid 'composite' object.`);
if (undefined !== jsonObj.composite.includeZero && typeof (jsonObj.composite.includeZero) !== "boolean")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this._currentItemFullName} has a Composite with an invalid 'includeZero' attribute. It should be of type 'boolean'.`);
if (undefined !== jsonObj.composite.spacer && typeof (jsonObj.composite.spacer) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this._currentItemFullName} has a Composite with an invalid 'spacer' attribute. It should be of type 'string'.`);
// if composite is defined
if (undefined === jsonObj.composite.units)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this._currentItemFullName} has an invalid 'Composite' attribute. It should have 1-4 units.`);
if (!Array.isArray(jsonObj.composite.units))
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this._currentItemFullName} has a Composite with an invalid 'units' attribute. It should be of type 'object[]'.`);
for (let i = 0; i < jsonObj.composite.units.length; i++) {
if (!isObject(jsonObj.composite.units[i]))
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this._currentItemFullName} has a Composite with an invalid 'units' attribute. It should be of type 'object[]'.`);
if (undefined === jsonObj.composite.units[i].name) // required
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this._currentItemFullName} has a Composite with an invalid 'units' attribute. The object at position ${i} is missing the required 'name' attribute.`);
if (typeof (jsonObj.composite.units[i].name) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this._currentItemFullName} has a Composite with an invalid 'units' attribute. The object at position ${i} has an invalid 'name' attribute. It should be of type 'string'.`);
if (undefined !== jsonObj.composite.units[i].label && typeof (jsonObj.composite.units[i].label) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this._currentItemFullName} has a Composite with an invalid 'units' attribute. The object at position ${i} has an invalid 'label' attribute. It should be of type 'string'.`);
}
}
return (jsonObj as unknown) as FormatProps;
}
private isValidPropertyType(type: string): boolean {
type = type.toLowerCase();
return (type === "primitiveproperty") ||
(type === "structproperty") ||
(type === "primitivearrayproperty") ||
(type === "structarrayproperty") ||
(type === "navigationproperty");
}
/**
* Type checks property and returns PropertyProps interface
* @param jsonObj
* @returns PropertyProps
*/
private checkPropertyProps(jsonObj: UnknownObject): PropertyProps {
const propName = jsonObj.name;
if (undefined !== jsonObj.label && typeof (jsonObj.label) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECProperty ${this._currentItemFullName}.${propName} has an invalid 'label' attribute. It should be of type 'string'.`);
if (undefined !== jsonObj.description && typeof (jsonObj.description) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECProperty ${this._currentItemFullName}.${propName} has an invalid 'description' attribute. It should be of type 'string'.`);
if (undefined !== jsonObj.priority && typeof (jsonObj.priority) !== "number")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECProperty ${this._currentItemFullName}.${propName} has an invalid 'priority' attribute. It should be of type 'number'.`);
if (undefined !== jsonObj.isReadOnly && typeof (jsonObj.isReadOnly) !== "boolean")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECProperty ${this._currentItemFullName}.${propName} has an invalid 'isReadOnly' attribute. It should be of type 'boolean'.`);
if (undefined !== jsonObj.category && typeof (jsonObj.category) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECProperty ${this._currentItemFullName}.${propName} has an invalid 'category' attribute. It should be of type 'string'.`);
if (undefined !== jsonObj.kindOfQuantity && typeof (jsonObj.kindOfQuantity) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECProperty ${this._currentItemFullName}.${propName} has an invalid 'kindOfQuantity' attribute. It should be of type 'string'.`);
if (undefined !== jsonObj.inherited && typeof (jsonObj.inherited) !== "boolean")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECProperty ${this._currentItemFullName}.${propName} has an invalid 'inherited' attribute. It should be of type 'boolean'.`);
if (undefined !== jsonObj.customAttributes && !Array.isArray(jsonObj.customAttributes))
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECProperty ${this._currentItemFullName}.${propName} has an invalid 'customAttributes' attribute. It should be of type 'array'.`);
return (jsonObj as unknown) as PropertyProps;
}
private checkPropertyTypename(jsonObj: UnknownObject): void {
const propName = jsonObj.name;
if (undefined === jsonObj.typeName)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECProperty ${this._currentItemFullName}.${propName} is missing the required 'typeName' attribute.`);
if (typeof (jsonObj.typeName) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECProperty ${this._currentItemFullName}.${propName} has an invalid 'typeName' attribute. It should be of type 'string'.`);
}
private checkPropertyMinAndMaxOccurs(jsonObj: UnknownObject): void {
const propName = jsonObj.name;
if (undefined !== jsonObj.minOccurs && typeof (jsonObj.minOccurs) !== "number")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECProperty ${this._currentItemFullName}.${propName} has an invalid 'minOccurs' attribute. It should be of type 'number'.`);
if (undefined !== jsonObj.maxOccurs && typeof (jsonObj.maxOccurs) !== "number")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECProperty ${this._currentItemFullName}.${propName} has an invalid 'maxOccurs' attribute. It should be of type 'number'.`);
}
/**
* Type checks PrimitiveOrEnumProperty and returns PrimitiveOrEnumPropertyBaseProps interface
* @param jsonObj
* @returns PrimitiveOrEnumPropertyBaseProps
*/
private checkPrimitiveOrEnumPropertyBaseProps(jsonObj: UnknownObject): PrimitiveOrEnumPropertyBaseProps {
this.checkPropertyProps(jsonObj);
this.checkPropertyTypename(jsonObj);
const propName = jsonObj.name;
if (undefined !== jsonObj.minLength && typeof (jsonObj.minLength) !== "number")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECProperty ${this._currentItemFullName}.${propName} has an invalid 'minLength' attribute. It should be of type 'number'.`);
if (undefined !== jsonObj.maxLength && typeof (jsonObj.maxLength) !== "number")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECProperty ${this._currentItemFullName}.${propName} has an invalid 'maxLength' attribute. It should be of type 'number'.`);
if (undefined !== jsonObj.minValue && typeof (jsonObj.minValue) !== "number")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECProperty ${this._currentItemFullName}.${propName} has an invalid 'minValue' attribute. It should be of type 'number'.`);
if (undefined !== jsonObj.maxValue && typeof (jsonObj.maxValue) !== "number")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECProperty ${this._currentItemFullName}.${propName} has an invalid 'maxValue' attribute. It should be of type 'number'.`);
if (undefined !== jsonObj.extendedTypeName && typeof (jsonObj.extendedTypeName) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ECProperty ${this._currentItemFullName}.${propName} has an invalid 'extendedTypeName' attribute. It should be of type 'string'.`);
return (jsonObj as unknown) as PrimitiveOrEnumPropertyBaseProps;
}
/**
* Type checks PrimitiveProperty and returns PrimitivePropertyProps interface
* @param jsonObj
* @returns PrimitivePropertyProps
*/
public parsePrimitiveProperty(jsonObj: UnknownObject): PrimitivePropertyProps {
this.checkPrimitiveOrEnumPropertyBaseProps(jsonObj);
return (jsonObj as unknown) as PrimitivePropertyProps;
}
/**
* Type checks StructProperty and returns StructPropertyProps interface
* @param jsonObj
* @returns StructPropertyProps
*/
public parseStructProperty(jsonObj: UnknownObject): StructPropertyProps {
this.checkPropertyProps(jsonObj);
this.checkPropertyTypename(jsonObj);
return (jsonObj as unknown) as StructPropertyProps;
}
/**
* Type checks PrimitiveArrayProperty and returns PrimitiveArrayPropertyProps interface
* @param jsonObj
* @returns PrimitiveArrayPropertyProps
*/
public parsePrimitiveArrayProperty(jsonObj: UnknownObject): PrimitiveArrayPropertyProps {
this.checkPrimitiveOrEnumPropertyBaseProps(jsonObj);
this.checkPropertyMinAndMaxOccurs(jsonObj);
return (jsonObj as unknown) as PrimitiveArrayPropertyProps;
}
/**
* Type checks StructArrayProperty and returns StructArrayPropertyProps interface
* @param jsonObj
* @returns StructArrayPropertyProps
*/
public parseStructArrayProperty(jsonObj: UnknownObject): StructArrayPropertyProps {
this.checkPropertyProps(jsonObj);
this.checkPropertyTypename(jsonObj);
this.checkPropertyMinAndMaxOccurs(jsonObj);
return (jsonObj as unknown) as StructArrayPropertyProps;
}
/**
* Type checks NavigationProperty and returns NavigationPropertyProps interface
* @param jsonObj
* @returns NavigationPropertyProps
*/
public parseNavigationProperty(jsonObj: UnknownObject): NavigationPropertyProps {
this.checkPropertyProps(jsonObj);
const fullname = `${this._currentItemFullName}.${jsonObj.name}`;
if (undefined === jsonObj.relationshipName)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Navigation Property ${fullname} is missing the required 'relationshipName' property.`);
if (typeof (jsonObj.relationshipName) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Navigation Property ${fullname} has an invalid 'relationshipName' property. It should be of type 'string'.`);
if (undefined === jsonObj.direction)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Navigation Property ${fullname} is missing the required 'direction' property.`);
if (typeof (jsonObj.direction) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Navigation Property ${fullname} has an invalid 'direction' property. It should be of type 'string'.`);
return (jsonObj as unknown) as NavigationPropertyProps;
}
public getSchemaCustomAttributeProviders(): Iterable<CAProviderTuple> {
return this.getCustomAttributeProviders(this._rawSchema, "Schema", this._schemaName);
}
public getClassCustomAttributeProviders(jsonObj: UnknownObject): Iterable<CAProviderTuple> {
return this.getCustomAttributeProviders(jsonObj, "ECClass", this._currentItemFullName);
}
public getPropertyCustomAttributeProviders(jsonObj: UnknownObject): Iterable<CAProviderTuple> {
return this.getCustomAttributeProviders(jsonObj, "ECProperty", `${this._currentItemFullName}.${jsonObj.name}`);
}
public getRelationshipConstraintCustomAttributeProviders(jsonObj: UnknownObject): [Iterable<CAProviderTuple> /* source */, Iterable<CAProviderTuple> /* target */] {
const sourceCustomAttributes = this.getCustomAttributeProviders(jsonObj.source as UnknownObject, "Source Constraint of", this._currentItemFullName);
const targetCustomAttributes = this.getCustomAttributeProviders(jsonObj.target as UnknownObject, "Target Constraint of", this._currentItemFullName);
return [sourceCustomAttributes, targetCustomAttributes];
}
private *getCustomAttributeProviders(jsonObj: UnknownObject, type: string, name?: string): Iterable<CAProviderTuple> {
if (undefined !== jsonObj.customAttributes) {
if (!Array.isArray(jsonObj.customAttributes))
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ${type} ${name} has an invalid 'customAttributes' attribute. It should be of type 'object[]'.`);
for (const instance of jsonObj.customAttributes) {
if (!isObject(instance) || Array.isArray(instance))
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The ${type} ${name} has an invalid 'customAttributes' attribute. It should be of type 'object[]'.`);
if (undefined === instance.className)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `A CustomAttribute in ${name}.customAttributes is missing the required 'className' attribute.`);
if (typeof (instance.className) !== "string")
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `A CustomAttribute in ${name}.customAttributes has an invalid 'className' attribute. It should be of type 'string'.`);
const provider = (_caClass: CustomAttributeClass) => {
return instance as CustomAttribute;
};
const caTuple: CAProviderTuple = [instance.className, provider];
yield caTuple;
}
}
}
} | the_stack |
module android.view.animation {
import RectF = android.graphics.RectF;
import Handler = android.os.Handler;
import TypedValue = android.util.TypedValue;
import Long = java.lang.Long;
import Runnable = java.lang.Runnable;
import AccelerateDecelerateInterpolator = android.view.animation.AccelerateDecelerateInterpolator;
import AnimationUtils = android.view.animation.AnimationUtils;
import DecelerateInterpolator = android.view.animation.DecelerateInterpolator;
import Interpolator = android.view.animation.Interpolator;
import Transformation = android.view.animation.Transformation;
/**
* Abstraction for an Animation that can be applied to Views, Surfaces, or
* other objects. See the {@link android.view.animation animation package
* description file}.
*/
export abstract class Animation {
/**
* Repeat the animation indefinitely.
*/
static INFINITE:number = -1;
/**
* When the animation reaches the end and the repeat count is INFINTE_REPEAT
* or a positive value, the animation restarts from the beginning.
*/
static RESTART:number = 1;
/**
* When the animation reaches the end and the repeat count is INFINTE_REPEAT
* or a positive value, the animation plays backward (and then forward again).
*/
static REVERSE:number = 2;
/**
* Can be used as the start time to indicate the start time should be the current
* time when {@link #getTransformation(long, Transformation)} is invoked for the
* first animation frame. This can is useful for short animations.
*/
static START_ON_FIRST_FRAME:number = -1;
/**
* The specified dimension is an absolute number of pixels.
*/
static ABSOLUTE:number = 0;
/**
* The specified dimension holds a float and should be multiplied by the
* height or width of the object being animated.
*/
static RELATIVE_TO_SELF:number = 1;
/**
* The specified dimension holds a float and should be multiplied by the
* height or width of the parent of the object being animated.
*/
static RELATIVE_TO_PARENT:number = 2;
/**
* Requests that the content being animated be kept in its current Z
* order.
*/
static ZORDER_NORMAL:number = 0;
/**
* Requests that the content being animated be forced on top of all other
* content for the duration of the animation.
*/
static ZORDER_TOP:number = 1;
/**
* Requests that the content being animated be forced under all other
* content for the duration of the animation.
*/
static ZORDER_BOTTOM:number = -1;
private static USE_CLOSEGUARD:boolean = false;//SystemProperties.getBoolean("log.closeguard.Animation", false);
/**
* Set by {@link #getTransformation(long, Transformation)} when the animation ends.
*/
mEnded:boolean = false;
/**
* Set by {@link #getTransformation(long, Transformation)} when the animation starts.
*/
mStarted:boolean = false;
/**
* Set by {@link #getTransformation(long, Transformation)} when the animation repeats
* in REVERSE mode.
*/
mCycleFlip:boolean = false;
/**
* This value must be set to true by {@link #initialize(int, int, int, int)}. It
* indicates the animation was successfully initialized and can be played.
*/
mInitialized:boolean = false;
/**
* Indicates whether the animation transformation should be applied before the
* animation starts. The value of this variable is only relevant if mFillEnabled is true;
* otherwise it is assumed to be true.
*/
mFillBefore:boolean = true;
/**
* Indicates whether the animation transformation should be applied after the
* animation ends.
*/
mFillAfter:boolean = false;
/**
* Indicates whether fillBefore should be taken into account.
*/
mFillEnabled:boolean = false;
/**
* The time in milliseconds at which the animation must start;
*/
mStartTime:number = -1;
/**
* The delay in milliseconds after which the animation must start. When the
* start offset is > 0, the start time of the animation is startTime + startOffset.
*/
mStartOffset:number = 0;
/**
* The duration of one animation cycle in milliseconds.
*/
mDuration:number = 0;
/**
* The number of times the animation must repeat. By default, an animation repeats
* indefinitely.
*/
mRepeatCount:number = 0;
/**
* Indicates how many times the animation was repeated.
*/
mRepeated:number = 0;
/**
* The behavior of the animation when it repeats. The repeat mode is either
* {@link #RESTART} or {@link #REVERSE}.
*
*/
mRepeatMode:number = Animation.RESTART;
/**
* The interpolator used by the animation to smooth the movement.
*/
mInterpolator:Interpolator;
/**
* The animation listener to be notified when the animation starts, ends or repeats.
*/
mListener:Animation.AnimationListener;
/**
* Desired Z order mode during animation.
*/
private mZAdjustment:number = 0;
/**
* Desired background color behind animation.
*/
private mBackgroundColor:number = 0;
/**
* scalefactor to apply to pivot points, etc. during animation. Subclasses retrieve the
* value via getScaleFactor().
*/
private mScaleFactor:number = 1;
/**
* Don't animate the wallpaper.
*/
private mDetachWallpaper:boolean = false;
private mMore:boolean = true;
private mOneMoreTime:boolean = true;
mPreviousRegion:RectF = new RectF();
mRegion:RectF = new RectF();
mTransformation:Transformation = new Transformation();
mPreviousTransformation:Transformation = new Transformation();
//private guard:CloseGuard = CloseGuard.get();
private mListenerHandler:Handler;
private mOnStart:Runnable;
private mOnRepeat:Runnable;
private mOnEnd:Runnable;
/**
* Creates a new animation with a duration of 0ms, the default interpolator, with
* fillBefore set to true and fillAfter set to false
*/
constructor() {
this.ensureInterpolator();
}
//protected clone():Animation {
// const animation:Animation = <Animation> super.clone();
// animation.mPreviousRegion = new RectF();
// animation.mRegion = new RectF();
// animation.mTransformation = new Transformation();
// animation.mPreviousTransformation = new Transformation();
// return animation;
//}
/**
* Reset the initialization state of this animation.
*
* @see #initialize(int, int, int, int)
*/
reset():void {
this.mPreviousRegion.setEmpty();
this.mPreviousTransformation.clear();
this.mInitialized = false;
this.mCycleFlip = false;
this.mRepeated = 0;
this.mMore = true;
this.mOneMoreTime = true;
this.mListenerHandler = null;
}
/**
* Cancel the animation. Cancelling an animation invokes the animation
* listener, if set, to notify the end of the animation.
*
* If you cancel an animation manually, you must call {@link #reset()}
* before starting the animation again.
*
* @see #reset()
* @see #start()
* @see #startNow()
*/
cancel():void {
if (this.mStarted && !this.mEnded) {
this.fireAnimationEnd();
this.mEnded = true;
//this.guard.close();
}
// Make sure we move the animation to the end
this.mStartTime = Long.MIN_VALUE;
this.mMore = this.mOneMoreTime = false;
}
/**
* @hide
*/
detach():void {
if (this.mStarted && !this.mEnded) {
this.mEnded = true;
//this.guard.close();
this.fireAnimationEnd();
}
}
/**
* Whether or not the animation has been initialized.
*
* @return Has this animation been initialized.
* @see #initialize(int, int, int, int)
*/
isInitialized():boolean {
return this.mInitialized;
}
/**
* Initialize this animation with the dimensions of the object being
* animated as well as the objects parents. (This is to support animation
* sizes being specified relative to these dimensions.)
*
* <p>Objects that interpret Animations should call this method when
* the sizes of the object being animated and its parent are known, and
* before calling {@link #getTransformation}.
*
*
* @param width Width of the object being animated
* @param height Height of the object being animated
* @param parentWidth Width of the animated object's parent
* @param parentHeight Height of the animated object's parent
*/
initialize(width:number, height:number, parentWidth:number, parentHeight:number):void {
this.reset();
this.mInitialized = true;
}
/**
* Sets the handler used to invoke listeners.
*
* @hide
*/
setListenerHandler(handler:Handler):void {
if (this.mListenerHandler == null) {
const inner_this=this;
this.mOnStart = {
run():void {
if (inner_this.mListener != null) {
inner_this.mListener.onAnimationStart(inner_this);
}
}
};
this.mOnRepeat = {
run():void {
if (inner_this.mListener != null) {
inner_this.mListener.onAnimationRepeat(inner_this);
}
}
};
this.mOnEnd = {
run():void {
if (inner_this.mListener != null) {
inner_this.mListener.onAnimationEnd(inner_this);
}
}
};
}
this.mListenerHandler = handler;
}
/**
* Sets the acceleration curve for this animation. Defaults to a linear
* interpolation.
*
* @param i The interpolator which defines the acceleration curve
* @attr ref android.R.styleable#Animation_interpolator
*/
setInterpolator(i:Interpolator):void {
this.mInterpolator = i;
}
/**
* When this animation should start relative to the start time. This is most
* useful when composing complex animations using an {@link AnimationSet }
* where some of the animations components start at different times.
*
* @param startOffset When this Animation should start, in milliseconds from
* the start time of the root AnimationSet.
* @attr ref android.R.styleable#Animation_startOffset
*/
setStartOffset(startOffset:number):void {
this.mStartOffset = startOffset;
}
/**
* How long this animation should last. The duration cannot be negative.
*
* @param durationMillis Duration in milliseconds
*
* @throws java.lang.IllegalArgumentException if the duration is < 0
*
* @attr ref android.R.styleable#Animation_duration
*/
setDuration(durationMillis:number):void {
if (durationMillis < 0) {
throw Error(`new IllegalArgumentException("Animation duration cannot be negative")`);
}
this.mDuration = durationMillis;
}
/**
* Ensure that the duration that this animation will run is not longer
* than <var>durationMillis</var>. In addition to adjusting the duration
* itself, this ensures that the repeat count also will not make it run
* longer than the given time.
*
* @param durationMillis The maximum duration the animation is allowed
* to run.
*/
restrictDuration(durationMillis:number):void {
// If we start after the duration, then we just won't run.
if (this.mStartOffset > durationMillis) {
this.mStartOffset = durationMillis;
this.mDuration = 0;
this.mRepeatCount = 0;
return;
}
let dur:number = this.mDuration + this.mStartOffset;
if (dur > durationMillis) {
this.mDuration = durationMillis - this.mStartOffset;
dur = durationMillis;
}
// If the duration is 0 or less, then we won't run.
if (this.mDuration <= 0) {
this.mDuration = 0;
this.mRepeatCount = 0;
return;
}
// overflows after multiplying them.
if (this.mRepeatCount < 0 || this.mRepeatCount > durationMillis || (dur * this.mRepeatCount) > durationMillis) {
// Figure out how many times to do the animation. Subtract 1 since
// repeat count is the number of times to repeat so 0 runs once.
this.mRepeatCount = Math.floor((durationMillis / dur)) - 1;
if (this.mRepeatCount < 0) {
this.mRepeatCount = 0;
}
}
}
/**
* How much to scale the duration by.
*
* @param scale The amount to scale the duration.
*/
scaleCurrentDuration(scale:number):void {
this.mDuration = Math.floor((this.mDuration * scale));
this.mStartOffset = Math.floor((this.mStartOffset * scale));
}
/**
* When this animation should start. When the start time is set to
* {@link #START_ON_FIRST_FRAME}, the animation will start the first time
* {@link #getTransformation(long, Transformation)} is invoked. The time passed
* to this method should be obtained by calling
* {@link AnimationUtils#currentAnimationTimeMillis()} instead of
* {@link System#currentTimeMillis()}.
*
* @param startTimeMillis the start time in milliseconds
*/
setStartTime(startTimeMillis:number):void {
this.mStartTime = startTimeMillis;
this.mStarted = this.mEnded = false;
this.mCycleFlip = false;
this.mRepeated = 0;
this.mMore = true;
}
/**
* Convenience method to start the animation the first time
* {@link #getTransformation(long, Transformation)} is invoked.
*/
start():void {
this.setStartTime(-1);
}
/**
* Convenience method to start the animation at the current time in
* milliseconds.
*/
startNow():void {
this.setStartTime(AnimationUtils.currentAnimationTimeMillis());
}
/**
* Defines what this animation should do when it reaches the end. This
* setting is applied only when the repeat count is either greater than
* 0 or {@link #INFINITE}. Defaults to {@link #RESTART}.
*
* @param repeatMode {@link #RESTART} or {@link #REVERSE}
* @attr ref android.R.styleable#Animation_repeatMode
*/
setRepeatMode(repeatMode:number):void {
this.mRepeatMode = repeatMode;
}
/**
* Sets how many times the animation should be repeated. If the repeat
* count is 0, the animation is never repeated. If the repeat count is
* greater than 0 or {@link #INFINITE}, the repeat mode will be taken
* into account. The repeat count is 0 by default.
*
* @param repeatCount the number of times the animation should be repeated
* @attr ref android.R.styleable#Animation_repeatCount
*/
setRepeatCount(repeatCount:number):void {
if (repeatCount < 0) {
repeatCount = Animation.INFINITE;
}
this.mRepeatCount = repeatCount;
}
/**
* If fillEnabled is true, this animation will apply the value of fillBefore.
*
* @return true if the animation will take fillBefore into account
* @attr ref android.R.styleable#Animation_fillEnabled
*/
isFillEnabled():boolean {
return this.mFillEnabled;
}
/**
* If fillEnabled is true, the animation will apply the value of fillBefore.
* Otherwise, fillBefore is ignored and the animation
* transformation is always applied until the animation ends.
*
* @param fillEnabled true if the animation should take the value of fillBefore into account
* @attr ref android.R.styleable#Animation_fillEnabled
*
* @see #setFillBefore(boolean)
* @see #setFillAfter(boolean)
*/
setFillEnabled(fillEnabled:boolean):void {
this.mFillEnabled = fillEnabled;
}
/**
* If fillBefore is true, this animation will apply its transformation
* before the start time of the animation. Defaults to true if
* {@link #setFillEnabled(boolean)} is not set to true.
* Note that this applies when using an {@link
* android.view.animation.AnimationSet AnimationSet} to chain
* animations. The transformation is not applied before the AnimationSet
* itself starts.
*
* @param fillBefore true if the animation should apply its transformation before it starts
* @attr ref android.R.styleable#Animation_fillBefore
*
* @see #setFillEnabled(boolean)
*/
setFillBefore(fillBefore:boolean):void {
this.mFillBefore = fillBefore;
}
/**
* If fillAfter is true, the transformation that this animation performed
* will persist when it is finished. Defaults to false if not set.
* Note that this applies to individual animations and when using an {@link
* android.view.animation.AnimationSet AnimationSet} to chain
* animations.
*
* @param fillAfter true if the animation should apply its transformation after it ends
* @attr ref android.R.styleable#Animation_fillAfter
*
* @see #setFillEnabled(boolean)
*/
setFillAfter(fillAfter:boolean):void {
this.mFillAfter = fillAfter;
}
/**
* Set the Z ordering mode to use while running the animation.
*
* @param zAdjustment The desired mode, one of {@link #ZORDER_NORMAL},
* {@link #ZORDER_TOP}, or {@link #ZORDER_BOTTOM}.
* @attr ref android.R.styleable#Animation_zAdjustment
*/
setZAdjustment(zAdjustment:number):void {
this.mZAdjustment = zAdjustment;
}
/**
* Set background behind animation.
*
* @param bg The background color. If 0, no background. Currently must
* be black, with any desired alpha level.
*/
setBackgroundColor(bg:number):void {
this.mBackgroundColor = bg;
}
/**
* The scale factor is set by the call to <code>getTransformation</code>. Overrides of
* {@link #getTransformation(long, Transformation, float)} will get this value
* directly. Overrides of {@link #applyTransformation(float, Transformation)} can
* call this method to get the value.
*
* @return float The scale factor that should be applied to pre-scaled values in
* an Animation such as the pivot points in {@link ScaleAnimation} and {@link RotateAnimation}.
*/
protected getScaleFactor():number {
return this.mScaleFactor;
}
/**
* If detachWallpaper is true, and this is a window animation of a window
* that has a wallpaper background, then the window will be detached from
* the wallpaper while it runs. That is, the animation will only be applied
* to the window, and the wallpaper behind it will remain static.
*
* @param detachWallpaper true if the wallpaper should be detached from the animation
* @attr ref android.R.styleable#Animation_detachWallpaper
*/
setDetachWallpaper(detachWallpaper:boolean):void {
this.mDetachWallpaper = detachWallpaper;
}
/**
* Gets the acceleration curve type for this animation.
*
* @return the {@link Interpolator} associated to this animation
* @attr ref android.R.styleable#Animation_interpolator
*/
getInterpolator():Interpolator {
return this.mInterpolator;
}
/**
* When this animation should start. If the animation has not startet yet,
* this method might return {@link #START_ON_FIRST_FRAME}.
*
* @return the time in milliseconds when the animation should start or
* {@link #START_ON_FIRST_FRAME}
*/
getStartTime():number {
return this.mStartTime;
}
/**
* How long this animation should last
*
* @return the duration in milliseconds of the animation
* @attr ref android.R.styleable#Animation_duration
*/
getDuration():number {
return this.mDuration;
}
/**
* When this animation should start, relative to StartTime
*
* @return the start offset in milliseconds
* @attr ref android.R.styleable#Animation_startOffset
*/
getStartOffset():number {
return this.mStartOffset;
}
/**
* Defines what this animation should do when it reaches the end.
*
* @return either one of {@link #REVERSE} or {@link #RESTART}
* @attr ref android.R.styleable#Animation_repeatMode
*/
getRepeatMode():number {
return this.mRepeatMode;
}
/**
* Defines how many times the animation should repeat. The default value
* is 0.
*
* @return the number of times the animation should repeat, or {@link #INFINITE}
* @attr ref android.R.styleable#Animation_repeatCount
*/
getRepeatCount():number {
return this.mRepeatCount;
}
/**
* If fillBefore is true, this animation will apply its transformation
* before the start time of the animation. If fillBefore is false and
* {@link #isFillEnabled() fillEnabled} is true, the transformation will not be applied until
* the start time of the animation.
*
* @return true if the animation applies its transformation before it starts
* @attr ref android.R.styleable#Animation_fillBefore
*/
getFillBefore():boolean {
return this.mFillBefore;
}
/**
* If fillAfter is true, this animation will apply its transformation
* after the end time of the animation.
*
* @return true if the animation applies its transformation after it ends
* @attr ref android.R.styleable#Animation_fillAfter
*/
getFillAfter():boolean {
return this.mFillAfter;
}
/**
* Returns the Z ordering mode to use while running the animation as
* previously set by {@link #setZAdjustment}.
*
* @return Returns one of {@link #ZORDER_NORMAL},
* {@link #ZORDER_TOP}, or {@link #ZORDER_BOTTOM}.
* @attr ref android.R.styleable#Animation_zAdjustment
*/
getZAdjustment():number {
return this.mZAdjustment;
}
/**
* Returns the background color behind the animation.
*/
getBackgroundColor():number {
return this.mBackgroundColor;
}
/**
* Return value of {@link #setDetachWallpaper(boolean)}.
* @attr ref android.R.styleable#Animation_detachWallpaper
*/
getDetachWallpaper():boolean {
return this.mDetachWallpaper;
}
/**
* <p>Indicates whether or not this animation will affect the transformation
* matrix. For instance, a fade animation will not affect the matrix whereas
* a scale animation will.</p>
*
* @return true if this animation will change the transformation matrix
*/
willChangeTransformationMatrix():boolean {
// assume we will change the matrix
return true;
}
/**
* <p>Indicates whether or not this animation will affect the bounds of the
* animated view. For instance, a fade animation will not affect the bounds
* whereas a 200% scale animation will.</p>
*
* @return true if this animation will change the view's bounds
*/
willChangeBounds():boolean {
// assume we will change the bounds
return true;
}
/**
* <p>Binds an animation listener to this animation. The animation listener
* is notified of animation events such as the end of the animation or the
* repetition of the animation.</p>
*
* @param listener the animation listener to be notified
*/
setAnimationListener(listener:Animation.AnimationListener):void {
this.mListener = listener;
}
/**
* Gurantees that this animation has an interpolator. Will use
* a AccelerateDecelerateInterpolator is nothing else was specified.
*/
protected ensureInterpolator():void {
if (this.mInterpolator == null) {
this.mInterpolator = new AccelerateDecelerateInterpolator();
}
}
/**
* Compute a hint at how long the entire animation may last, in milliseconds.
* Animations can be written to cause themselves to run for a different
* duration than what is computed here, but generally this should be
* accurate.
*/
computeDurationHint():number {
return (this.getStartOffset() + this.getDuration()) * (this.getRepeatCount() + 1);
}
/**
* Gets the transformation to apply at a specified point in time. Implementations of this
* method should always replace the specified Transformation or document they are doing
* otherwise.
*
* @param currentTime Where we are in the animation. This is wall clock time.
* @param outTransformation A transformation object that is provided by the
* caller and will be filled in by the animation.
* @param scale Scaling factor to apply to any inputs to the transform operation, such
* pivot points being rotated or scaled around.
* @return True if the animation is still running
*/
getTransformation(currentTime:number, outTransformation:Transformation, scale?:number):boolean {
if(scale!=null) this.mScaleFactor = scale;
if (this.mStartTime == -1) {
this.mStartTime = currentTime;
}
const startOffset:number = this.getStartOffset();
const duration:number = this.mDuration;
let normalizedTime:number;
if (duration != 0) {
normalizedTime = (<number> (currentTime - (this.mStartTime + startOffset))) / <number> duration;
} else {
// time is a step-change with a zero duration
normalizedTime = currentTime < this.mStartTime ? 0.0 : 1.0;
}
const expired:boolean = normalizedTime >= 1.0;
this.mMore = !expired;
if (!this.mFillEnabled)
normalizedTime = Math.max(Math.min(normalizedTime, 1.0), 0.0);
if ((normalizedTime >= 0.0 || this.mFillBefore) && (normalizedTime <= 1.0 || this.mFillAfter)) {
if (!this.mStarted) {
this.fireAnimationStart();
this.mStarted = true;
//if (Animation.USE_CLOSEGUARD) {
// this.guard.open("cancel or detach or getTransformation");
//}
}
if (this.mFillEnabled)
normalizedTime = Math.max(Math.min(normalizedTime, 1.0), 0.0);
if (this.mCycleFlip) {
normalizedTime = 1.0 - normalizedTime;
}
const interpolatedTime:number = this.mInterpolator.getInterpolation(normalizedTime);
this.applyTransformation(interpolatedTime, outTransformation);
}
if (expired) {
if (this.mRepeatCount == this.mRepeated) {
if (!this.mEnded) {
this.mEnded = true;
//this.guard.close();
this.fireAnimationEnd();
}
} else {
if (this.mRepeatCount > 0) {
this.mRepeated++;
}
if (this.mRepeatMode == Animation.REVERSE) {
this.mCycleFlip = !this.mCycleFlip;
}
this.mStartTime = -1;
this.mMore = true;
this.fireAnimationRepeat();
}
}
if (!this.mMore && this.mOneMoreTime) {
this.mOneMoreTime = false;
return true;
}
return this.mMore;
}
private fireAnimationStart():void {
if (this.mListener != null) {
if (this.mListenerHandler == null)
this.mListener.onAnimationStart(this);
else
this.mListenerHandler.postAtFrontOfQueue(this.mOnStart);
}
}
private fireAnimationRepeat():void {
if (this.mListener != null) {
if (this.mListenerHandler == null)
this.mListener.onAnimationRepeat(this);
else
this.mListenerHandler.postAtFrontOfQueue(this.mOnRepeat);
}
}
private fireAnimationEnd():void {
if (this.mListener != null) {
if (this.mListenerHandler == null)
this.mListener.onAnimationEnd(this);
else
this.mListenerHandler.postAtFrontOfQueue(this.mOnEnd);
}
}
/**
* <p>Indicates whether this animation has started or not.</p>
*
* @return true if the animation has started, false otherwise
*/
hasStarted():boolean {
return this.mStarted;
}
/**
* <p>Indicates whether this animation has ended or not.</p>
*
* @return true if the animation has ended, false otherwise
*/
hasEnded():boolean {
return this.mEnded;
}
/**
* Helper for getTransformation. Subclasses should implement this to apply
* their transforms given an interpolation value. Implementations of this
* method should always replace the specified Transformation or document
* they are doing otherwise.
*
* @param interpolatedTime The value of the normalized time (0.0 to 1.0)
* after it has been run through the interpolation function.
* @param t The Transformation object to fill in with the current
* transforms.
*/
protected applyTransformation(interpolatedTime:number, t:Transformation):void {
}
/**
* Convert the information in the description of a size to an actual
* dimension
*
* @param type One of Animation.ABSOLUTE, Animation.RELATIVE_TO_SELF, or
* Animation.RELATIVE_TO_PARENT.
* @param value The dimension associated with the type parameter
* @param size The size of the object being animated
* @param parentSize The size of the parent of the object being animated
* @return The dimension to use for the animation
*/
protected resolveSize(type:number, value:number, size:number, parentSize:number):number {
switch(type) {
case Animation.ABSOLUTE:
return value;
case Animation.RELATIVE_TO_SELF:
return size * value;
case Animation.RELATIVE_TO_PARENT:
return parentSize * value;
default:
return value;
}
}
/**
* @param left
* @param top
* @param right
* @param bottom
* @param invalidate
* @param transformation
*
* @hide
*/
getInvalidateRegion(left:number, top:number, right:number, bottom:number, invalidate:RectF, transformation:Transformation):void {
const tempRegion:RectF = this.mRegion;
const previousRegion:RectF = this.mPreviousRegion;
invalidate.set(left, top, right, bottom);
transformation.getMatrix().mapRect(invalidate);
// Enlarge the invalidate region to account for rounding errors
invalidate.inset(-1.0, -1.0);
tempRegion.set(invalidate);
invalidate.union(previousRegion);
previousRegion.set(tempRegion);
const tempTransformation:Transformation = this.mTransformation;
const previousTransformation:Transformation = this.mPreviousTransformation;
tempTransformation.set(transformation);
transformation.set(previousTransformation);
previousTransformation.set(tempTransformation);
}
/**
* @param left
* @param top
* @param right
* @param bottom
*
* @hide
*/
initializeInvalidateRegion(left:number, top:number, right:number, bottom:number):void {
const region:RectF = this.mPreviousRegion;
region.set(left, top, right, bottom);
// Enlarge the invalidate region to account for rounding errors
region.inset(-1.0, -1.0);
if (this.mFillBefore) {
const previousTransformation:Transformation = this.mPreviousTransformation;
this.applyTransformation(this.mInterpolator.getInterpolation(0.0), previousTransformation);
}
}
//protected finalize():void {
// try {
// if (this.guard != null) {
// this.guard.warnIfOpen();
// }
// } finally {
// super.finalize();
// }
//}
/**
* Return true if this animation changes the view's alpha property.
*
* @hide
*/
hasAlpha():boolean {
return false;
}
}
export module Animation{
/**
* Utility class to parse a string description of a size.
*/
export class Description {
/**
* One of Animation.ABSOLUTE, Animation.RELATIVE_TO_SELF, or
* Animation.RELATIVE_TO_PARENT.
*/
type:number = 0;
/**
* The absolute or relative dimension for this Description.
*/
value:number = 0;
/**
* Size descriptions can appear inthree forms:
* <ol>
* <li>An absolute size. This is represented by a number.</li>
* <li>A size relative to the size of the object being animated. This
* is represented by a number followed by "%".</li> *
* <li>A size relative to the size of the parent of object being
* animated. This is represented by a number followed by "%p".</li>
* </ol>
* @param value The typed value to parse
* @return The parsed version of the description
*/
static parseValue(value:string):Description {
let d:Description = new Description();
if (value == null) {
d.type = Animation.ABSOLUTE;
d.value = 0;
} else {
if(value.endsWith('%p')){
d.type = Animation.RELATIVE_TO_PARENT;
d.value = Number.parseFloat(value.substring(0, value.length-2));
}else if(value.endsWith('%')){
d.type = Animation.RELATIVE_TO_SELF;
d.value = Number.parseFloat(value.substring(0, value.length-1));
}else{
d.type = Animation.ABSOLUTE;
d.value = TypedValue.complexToDimensionPixelSize(value);
}
}
d.type = Animation.ABSOLUTE;
d.value = 0.0;
return d;
}
}
/**
* <p>An animation listener receives notifications from an animation.
* Notifications indicate animation related events, such as the end or the
* repetition of the animation.</p>
*/
export interface AnimationListener {
/**
* <p>Notifies the start of the animation.</p>
*
* @param animation The started animation.
*/
onAnimationStart(animation:Animation):void ;
/**
* <p>Notifies the end of the animation. This callback is not invoked
* for animations with repeat count set to INFINITE.</p>
*
* @param animation The animation which reached its end.
*/
onAnimationEnd(animation:Animation):void ;
/**
* <p>Notifies the repetition of the animation.</p>
*
* @param animation The animation which was repeated.
*/
onAnimationRepeat(animation:Animation):void ;
}
}
} | the_stack |
import { ensureDir, pathExists } from "fs-extra";
import globby = require("globby");
import * as _ from "lodash";
import { basename, dirname, extname, isAbsolute, join, normalize, relative } from "path";
import { Disposable, ProgressLocation, QuickInputButtons, QuickPickItem, Uri, window, WorkspaceFolder } from "vscode";
import { sendInfo } from "vscode-extension-telemetry-wrapper";
import { Jdtls } from "../java/jdtls";
import { INodeData } from "../java/nodeData";
import { IExportJarStepExecutor } from "./IExportJarStepExecutor";
import { IClasspath, IStepMetadata } from "./IStepMetadata";
import { createPickBox, ExportJarMessages, ExportJarStep, ExportJarTargets, getExtensionApi, toPosixPath } from "./utility";
export class GenerateJarExecutor implements IExportJarStepExecutor {
private readonly currentStep: ExportJarStep = ExportJarStep.GenerateJar;
public async execute(stepMetadata: IStepMetadata): Promise<boolean> {
return this.generateJar(stepMetadata);
}
private async generateJar(stepMetadata: IStepMetadata): Promise<boolean> {
if (_.isEmpty(stepMetadata.elements)) {
// If the user uses wizard or custom task with a empty list of elements,
// the classpaths should be specified manually.
if (!(await this.generateClasspaths(stepMetadata))) {
return false;
}
}
const folder: WorkspaceFolder | undefined = stepMetadata.workspaceFolder;
if (!folder) {
throw new Error(ExportJarMessages.fieldUndefinedMessage(ExportJarMessages.Field.WORKSPACEFOLDER, this.currentStep));
}
let destPath = "";
if (stepMetadata.outputPath === ExportJarTargets.SETTING_ASKUSER || stepMetadata.outputPath === "") {
if (stepMetadata.outputPath === ExportJarTargets.SETTING_ASKUSER) {
sendInfo("", { exportJarPath: stepMetadata.outputPath });
}
const outputUri: Uri | undefined = await window.showSaveDialog({
defaultUri: Uri.file(join(folder.uri.fsPath, `${folder.name}.jar`)),
filters: {
"Java Archive": ["jar"],
},
});
if (!outputUri) {
return Promise.reject();
}
destPath = outputUri.fsPath;
} else {
const outputPath: string | undefined = stepMetadata.outputPath;
if (!outputPath) {
throw new Error(ExportJarMessages.fieldUndefinedMessage(ExportJarMessages.Field.OUTPUTPATH, this.currentStep));
}
// Both the absolute path and the relative path (to workspace folder) are supported.
destPath = (isAbsolute(outputPath)) ? outputPath : join(folder.uri.fsPath, outputPath);
// Since both the specific target folder and the specific target file are supported,
// we regard a path as a file if it ends with ".jar". Otherwise, it was regarded as a folder.
if (extname(outputPath) !== ".jar") {
destPath = join(destPath, folder.name + ".jar");
}
await ensureDir(dirname(destPath));
}
destPath = normalize(destPath);
return window.withProgress({
location: ProgressLocation.Window,
title: "Exporting Jar : Generating jar...",
cancellable: true,
}, (_progress, token) => {
return new Promise<boolean>(async (resolve, reject) => {
token.onCancellationRequested(() => {
return reject();
});
const mainClass: string | undefined = stepMetadata.mainClass;
// For "no main class" option, we get an empty string in stepMetadata.mainClass,
// so this condition would be (mainClass === undefined)
if (mainClass === undefined) {
return reject(new Error(ExportJarMessages.fieldUndefinedMessage(ExportJarMessages.Field.MAINCLASS, this.currentStep)));
}
const classpaths: IClasspath[] = stepMetadata.classpaths;
if (_.isEmpty(classpaths)) {
return reject(new Error(ExportJarMessages.CLASSPATHS_EMPTY));
}
if (!stepMetadata.terminalId) {
return reject(new Error("Can't find related terminal."));
}
const exportResult: boolean | undefined = await Jdtls.exportJar(basename(mainClass),
classpaths, destPath, stepMetadata.terminalId, token);
if (exportResult === true) {
stepMetadata.outputPath = destPath;
return resolve(true);
} else {
return reject(new Error("Export jar failed."));
}
});
});
}
private async generateClasspaths(stepMetadata: IStepMetadata): Promise<boolean> {
const extensionApi: any = await getExtensionApi();
const dependencyItems: IJarQuickPickItem[] = await window.withProgress({
location: ProgressLocation.Window,
title: "Exporting Jar : Resolving classpaths...",
cancellable: true,
}, (_progress, token) => {
return new Promise<IJarQuickPickItem[]>(async (resolve, reject) => {
token.onCancellationRequested(() => {
return reject();
});
const pickItems: IJarQuickPickItem[] = [];
const uriSet: Set<string> = new Set<string>();
const projectList: INodeData[] = stepMetadata.projectList;
if (_.isEmpty(projectList)) {
return reject(new Error(ExportJarMessages.WORKSPACE_EMPTY));
}
const workspaceFolder: WorkspaceFolder | undefined = stepMetadata.workspaceFolder;
if (!workspaceFolder) {
return reject(new Error(ExportJarMessages.fieldUndefinedMessage(ExportJarMessages.Field.WORKSPACEFOLDER, this.currentStep)));
}
for (const project of projectList) {
const projectUri: string = project.metaData?.UnmanagedFolderInnerPath || project.uri;
let classpaths: IClasspathResult;
let testClasspaths: IClasspathResult;
try {
classpaths = await extensionApi.getClasspaths(projectUri, { scope: "runtime" });
testClasspaths = await extensionApi.getClasspaths(projectUri, { scope: "test" });
} catch (e) {
return reject(new Error(e));
}
pickItems.push(
...await this.parseDependencyItems(classpaths.classpaths, uriSet, workspaceFolder.uri.fsPath, "runtime"),
...await this.parseDependencyItems(classpaths.modulepaths, uriSet, workspaceFolder.uri.fsPath, "runtime"));
pickItems.push(
...await this.parseDependencyItems(testClasspaths.classpaths, uriSet, workspaceFolder.uri.fsPath, "test"),
...await this.parseDependencyItems(testClasspaths.modulepaths, uriSet, workspaceFolder.uri.fsPath, "test"));
}
return resolve(pickItems);
});
});
if (_.isEmpty(dependencyItems)) {
throw new Error(ExportJarMessages.PROJECT_EMPTY);
} else if (dependencyItems.length === 1) {
await this.setStepMetadataFromOutputFolder(dependencyItems[0].path, stepMetadata.classpaths);
return true;
}
dependencyItems.sort((node1, node2) => {
if (node1.description !== node2.description) {
return (node1.description || "").localeCompare(node2.description || "");
}
if (node1.type !== node2.type) {
return node2.type.localeCompare(node1.type);
}
return node1.label.localeCompare(node2.label);
});
const pickedDependencyItems: IJarQuickPickItem[] = [];
for (const item of dependencyItems) {
if (item.picked) {
pickedDependencyItems.push(item);
}
}
const disposables: Disposable[] = [];
let result: boolean = false;
try {
result = await new Promise<boolean>(async (resolve, reject) => {
const pickBox = createPickBox<IJarQuickPickItem>("Export Jar : Determine elements", "Select the elements",
dependencyItems, stepMetadata.steps.length > 0, true);
pickBox.selectedItems = pickedDependencyItems;
disposables.push(
pickBox.onDidTriggerButton((item) => {
if (item === QuickInputButtons.Back) {
return resolve(false);
}
}),
pickBox.onDidAccept(async () => {
if (_.isEmpty(pickBox.selectedItems)) {
return;
}
for (const item of pickBox.selectedItems) {
if (item.type === "artifact") {
const classpath: IClasspath = {
source: item.path,
destination: undefined,
isArtifact: true,
};
stepMetadata.classpaths.push(classpath);
} else {
await this.setStepMetadataFromOutputFolder(item.path, stepMetadata.classpaths);
}
}
return resolve(true);
}),
pickBox.onDidHide(() => {
return reject();
}),
);
disposables.push(pickBox);
pickBox.show();
});
} finally {
for (const d of disposables) {
d.dispose();
}
}
return result;
}
private async setStepMetadataFromOutputFolder(folderPath: string, classpaths: IClasspath[]): Promise<void> {
const posixPath: string = toPosixPath(folderPath);
for (const path of await globby(posixPath)) {
const classpath: IClasspath = {
source: path,
destination: relative(posixPath, path),
isArtifact: false,
};
classpaths.push(classpath);
}
}
private async parseDependencyItems(paths: string[], uriSet: Set<string>, projectPath: string, scope: string): Promise<IJarQuickPickItem[]> {
const dependencyItems: IJarQuickPickItem[] = [];
for (const classpath of paths) {
if (await pathExists(classpath) === false) {
continue;
}
const extName = extname(classpath);
const baseName = Uri.parse(classpath).fsPath.startsWith(Uri.parse(projectPath).fsPath) ?
relative(projectPath, classpath) : basename(classpath);
const typeValue = (extName === ".jar") ? "artifact" : "outputFolder";
if (!uriSet.has(classpath)) {
uriSet.add(classpath);
dependencyItems.push({
label: baseName,
description: scope,
path: classpath,
type: typeValue,
picked: scope === "runtime",
});
}
}
return dependencyItems;
}
}
export interface IClasspathResult {
projectRoot: string;
classpaths: string[];
modulepaths: string[];
}
interface IJarQuickPickItem extends QuickPickItem {
path: string;
type: string;
} | the_stack |
import isEmpty from 'lodash/isEmpty';
import union from 'lodash/union';
import {
DispatchCell,
JsonFormsStateContext,
useJsonForms
} from '@jsonforms/react';
import startCase from 'lodash/startCase';
import range from 'lodash/range';
import React, { Fragment, useMemo } from 'react';
import {
FormHelperText,
Grid,
Hidden,
IconButton,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Typography
} from '@mui/material';
import {
ArrayLayoutProps,
ControlElement,
errorsAt,
formatErrorMessage,
JsonSchema,
Paths,
Resolve,
JsonFormsRendererRegistryEntry,
JsonFormsCellRendererRegistryEntry
} from '@jsonforms/core';
import DeleteIcon from '@mui/icons-material/Delete';
import ArrowDownward from '@mui/icons-material/ArrowDownward';
import ArrowUpward from '@mui/icons-material/ArrowUpward';
import { WithDeleteDialogSupport } from './DeleteDialog';
import NoBorderTableCell from './NoBorderTableCell';
import TableToolbar from './TableToolbar';
import { ErrorObject } from 'ajv';
import merge from 'lodash/merge';
// we want a cell that doesn't automatically span
const styles = {
fixedCell: {
width: '150px',
height: '50px',
paddingLeft: 0,
paddingRight: 0,
textAlign: 'center'
},
fixedCellSmall: {
width: '50px',
height: '50px',
paddingLeft: 0,
paddingRight: 0,
textAlign: 'center'
}
};
const generateCells = (
Cell: React.ComponentType<OwnPropsOfNonEmptyCell | TableHeaderCellProps>,
schema: JsonSchema,
rowPath: string,
enabled: boolean,
cells?: JsonFormsCellRendererRegistryEntry[]
) => {
if (schema.type === 'object') {
return getValidColumnProps(schema).map(prop => {
const cellPath = Paths.compose(rowPath, prop);
const props = {
propName: prop,
schema,
title: schema.properties?.[prop]?.title ?? startCase(prop),
rowPath,
cellPath,
enabled,
cells
};
return <Cell key={cellPath} {...props} />;
});
} else {
// primitives
const props = {
schema,
rowPath,
cellPath: rowPath,
enabled
};
return <Cell key={rowPath} {...props} />;
}
};
const getValidColumnProps = (scopedSchema: JsonSchema) => {
if (scopedSchema.type === 'object' && typeof scopedSchema.properties === 'object') {
return Object.keys(scopedSchema.properties).filter(
prop => scopedSchema.properties[prop].type !== 'array'
);
}
// primitives
return [''];
};
export interface EmptyTableProps {
numColumns: number;
}
const EmptyTable = ({ numColumns }: EmptyTableProps) => (
<TableRow>
<NoBorderTableCell colSpan={numColumns}>
<Typography align='center'>No data</Typography>
</NoBorderTableCell>
</TableRow>
);
interface TableHeaderCellProps {
title: string;
}
const TableHeaderCell = React.memo(({ title }: TableHeaderCellProps) => (
<TableCell>{title}</TableCell>
));
interface NonEmptyCellProps extends OwnPropsOfNonEmptyCell {
rootSchema: JsonSchema;
errors: string;
path: string;
enabled: boolean;
}
interface OwnPropsOfNonEmptyCell {
rowPath: string;
propName?: string;
schema: JsonSchema;
enabled: boolean;
renderers?: JsonFormsRendererRegistryEntry[];
cells?: JsonFormsCellRendererRegistryEntry[];
}
const ctxToNonEmptyCellProps = (
ctx: JsonFormsStateContext,
ownProps: OwnPropsOfNonEmptyCell
): NonEmptyCellProps => {
const path =
ownProps.rowPath +
(ownProps.schema.type === 'object' ? '.' + ownProps.propName : '');
const errors = formatErrorMessage(
union(
errorsAt(
path,
ownProps.schema,
p => p === path
)(ctx.core.errors).map((error: ErrorObject) => error.message)
)
);
return {
rowPath: ownProps.rowPath,
propName: ownProps.propName,
schema: ownProps.schema,
rootSchema: ctx.core.schema,
errors,
path,
enabled: ownProps.enabled,
cells: ownProps.cells || ctx.cells,
renderers: ownProps.renderers || ctx.renderers
};
};
const controlWithoutLabel = (scope: string): ControlElement => ({
type: 'Control',
scope: scope,
label: false
});
interface NonEmptyCellComponentProps {
path: string,
propName?: string,
schema: JsonSchema,
rootSchema: JsonSchema,
errors: string,
enabled: boolean,
renderers?: JsonFormsRendererRegistryEntry[],
cells?: JsonFormsCellRendererRegistryEntry[],
isValid: boolean
}
const NonEmptyCellComponent = React.memo(({path, propName, schema,rootSchema, errors, enabled, renderers, cells, isValid}:NonEmptyCellComponentProps) => {
return (
<NoBorderTableCell>
{schema.properties ? (
<DispatchCell
schema={Resolve.schema(
schema,
`#/properties/${propName}`,
rootSchema
)}
uischema={controlWithoutLabel(`#/properties/${propName}`)}
path={path}
enabled={enabled}
renderers={renderers}
cells={cells}
/>
) : (
<DispatchCell
schema={schema}
uischema={controlWithoutLabel('#')}
path={path}
enabled={enabled}
renderers={renderers}
cells={cells}
/>
)}
<FormHelperText error={!isValid}>{!isValid && errors}</FormHelperText>
</NoBorderTableCell>
);
});
const NonEmptyCell = (ownProps: OwnPropsOfNonEmptyCell) => {
const ctx = useJsonForms();
const emptyCellProps = ctxToNonEmptyCellProps(ctx, ownProps);
const isValid = isEmpty(emptyCellProps.errors);
return <NonEmptyCellComponent {...emptyCellProps} isValid={isValid}/>
};
interface NonEmptyRowProps {
childPath: string;
schema: JsonSchema;
rowIndex: number;
moveUpCreator: (path:string, position: number)=> ()=> void;
moveDownCreator: (path:string, position: number)=> ()=> void;
enableUp: boolean;
enableDown: boolean;
showSortButtons: boolean;
enabled: boolean;
cells?: JsonFormsCellRendererRegistryEntry[];
path: string;
}
const NonEmptyRowComponent =
({
childPath,
schema,
rowIndex,
openDeleteDialog,
moveUpCreator,
moveDownCreator,
enableUp,
enableDown,
showSortButtons,
enabled,
cells,
path
}: NonEmptyRowProps & WithDeleteDialogSupport) => {
const moveUp = useMemo(() => moveUpCreator(path, rowIndex),[moveUpCreator, path, rowIndex]);
const moveDown = useMemo(() => moveDownCreator(path, rowIndex),[moveDownCreator, path, rowIndex]);
return (
<TableRow key={childPath} hover>
{generateCells(NonEmptyCell, schema, childPath, enabled, cells)}
{enabled ? (
<NoBorderTableCell
style={showSortButtons ? styles.fixedCell : styles.fixedCellSmall}
>
<Grid
container
direction='row'
justifyContent='flex-end'
alignItems='center'
>
{showSortButtons ? (
<Fragment>
<Grid item>
<IconButton aria-label={`Move up`} onClick={moveUp} disabled={!enableUp} size='large'>
<ArrowUpward />
</IconButton>
</Grid>
<Grid item>
<IconButton
aria-label={`Move down`}
onClick={moveDown}
disabled={!enableDown}
size='large'>
<ArrowDownward />
</IconButton>
</Grid>
</Fragment>
) : null}
<Grid item>
<IconButton
aria-label={`Delete`}
onClick={() => openDeleteDialog(childPath, rowIndex)}
size='large'>
<DeleteIcon />
</IconButton>
</Grid>
</Grid>
</NoBorderTableCell>
) : null}
</TableRow>
);
};
export const NonEmptyRow = React.memo(NonEmptyRowComponent);
interface TableRowsProp {
data: number;
path: string;
schema: JsonSchema;
uischema: ControlElement;
config?: any;
enabled: boolean;
cells?: JsonFormsCellRendererRegistryEntry[];
moveUp?(path: string, toMove: number): () => void;
moveDown?(path: string, toMove: number): () => void;
}
const TableRows = ({
data,
path,
schema,
openDeleteDialog,
moveUp,
moveDown,
uischema,
config,
enabled,
cells
}: TableRowsProp & WithDeleteDialogSupport) => {
const isEmptyTable = data === 0;
if (isEmptyTable) {
return <EmptyTable numColumns={getValidColumnProps(schema).length + 1} />;
}
const appliedUiSchemaOptions = merge({}, config, uischema.options);
return (
<React.Fragment>
{range(data).map((index: number) => {
const childPath = Paths.compose(path, `${index}`);
return (
<NonEmptyRow
key={childPath}
childPath={childPath}
rowIndex={index}
schema={schema}
openDeleteDialog={openDeleteDialog}
moveUpCreator={moveUp}
moveDownCreator={moveDown}
enableUp={index !== 0}
enableDown={index !== data - 1}
showSortButtons={appliedUiSchemaOptions.showSortButtons}
enabled={enabled}
cells={cells}
path={path}
/>
);
})}
</React.Fragment>
);
};
export class MaterialTableControl extends React.Component<
ArrayLayoutProps & WithDeleteDialogSupport,
any
> {
addItem = (path: string, value: any) => this.props.addItem(path, value);
render() {
const {
label,
path,
schema,
rootSchema,
uischema,
errors,
openDeleteDialog,
visible,
enabled,
cells
} = this.props;
const controlElement = uischema as ControlElement;
const isObjectSchema = schema.type === 'object';
const headerCells: any = isObjectSchema
? generateCells(TableHeaderCell, schema, path, enabled, cells)
: undefined;
return (
<Hidden xsUp={!visible}>
<Table>
<TableHead>
<TableToolbar
errors={errors}
label={label}
addItem={this.addItem}
numColumns={isObjectSchema ? headerCells.length : 1}
path={path}
uischema={controlElement}
schema={schema}
rootSchema={rootSchema}
enabled={enabled}
/>
{isObjectSchema && (
<TableRow>
{headerCells}
{enabled ? <TableCell /> : null}
</TableRow>
)}
</TableHead>
<TableBody>
<TableRows openDeleteDialog={openDeleteDialog} {...this.props} />
</TableBody>
</Table>
</Hidden>
);
}
} | the_stack |
import { commands, ExtensionContext, window } from 'vscode';
import fundSuggestList from './data/fundSuggestData';
import { BinanceProvider } from './explorer/binanceProvider';
import BinanceService from './explorer/binanceService';
import { FundProvider } from './explorer/fundProvider';
import FundService from './explorer/fundService';
import { NewsProvider } from './explorer/newsProvider';
import { NewsService } from './explorer/newsService';
import { StockProvider } from './explorer/stockProvider';
import StockService from './explorer/stockService';
import globalState from './globalState';
import FlashNewsDaemon from './output/flash-news/FlashNewsDaemon';
import FlashNewsOutputServer from './output/flash-news/FlashNewsOutputServer';
import { LeekFundConfig } from './shared/leekConfig';
import { LeekTreeItem } from './shared/leekTreeItem';
import checkForUpdate from './shared/update';
import { colorOptionList, randomColor } from './shared/utils';
import allFundTrend from './webview/allFundTrend';
import donate from './webview/donate';
import fundFlow, { mainFundFlow } from './webview/fundFlow';
import fundHistory from './webview/fundHistory';
import fundPosition from './webview/fundPosition';
import fundRank from './webview/fundRank';
import fundTrend from './webview/fundTrend';
import leekCenterView from './webview/leekCenterView';
import openNews from './webview/news';
import setAmount from './webview/setAmount';
import stockTrend from './webview/stockTrend';
import stockTrendPic from './webview/stockTrendPic';
import tucaoForum from './webview/tucaoForum';
export function registerViewEvent(
context: ExtensionContext,
fundService: FundService,
stockService: StockService,
fundProvider: FundProvider,
stockProvider: StockProvider,
newsProvider: NewsProvider,
flashNewsOutputServer: FlashNewsOutputServer,
binanceProvider?: BinanceProvider
) {
const leekModel = new LeekFundConfig();
const newsService = new NewsService();
const binanceService = new BinanceService(context);
commands.registerCommand('leek-fund.toggleFlashNews', () => {
const isEnable = LeekFundConfig.getConfig('leek-fund.flash-news');
LeekFundConfig.setConfig('leek-fund.flash-news', !isEnable).then(() => {
window.showInformationMessage(`已${isEnable ? '启用' : '关闭'} OUTPUT 的 Flash News!`);
});
});
commands.registerCommand('leek-fund.refreshFollow', () => {
newsProvider.refresh();
window.showInformationMessage(`刷新成功`);
});
commands.registerCommand('leek-fund.flash-news-show', () => {
flashNewsOutputServer.showOutput();
});
// Fund operation
commands.registerCommand('leek-fund.refreshFund', () => {
fundProvider.refresh();
const handler = window.setStatusBarMessage(`基金数据已刷新`);
setTimeout(() => {
handler.dispose();
}, 1000);
});
commands.registerCommand('leek-fund.deleteFund', (target) => {
LeekFundConfig.removeFundCfg(target.id, () => {
fundProvider.refresh();
});
});
commands.registerCommand('leek-fund.addFund', () => {
/* if (!service.fundSuggestList.length) {
service.getFundSuggestList();
window.showInformationMessage(`获取基金数据中,请稍后再试`);
return;
} */
window.showQuickPick(fundSuggestList, { placeHolder: '请输入基金代码' }).then((code) => {
if (!code) {
return;
}
LeekFundConfig.updateFundCfg(code.split('|')[0], () => {
fundProvider.refresh();
});
});
});
commands.registerCommand('leek-fund.sortFund', () => {
fundProvider.changeOrder();
fundProvider.refresh();
});
commands.registerCommand('leek-fund.sortAmountFund', () => {
fundProvider.changeAmountOrder();
fundProvider.refresh();
});
// Stock operation
commands.registerCommand('leek-fund.refreshStock', () => {
stockProvider.refresh();
const handler = window.setStatusBarMessage(`股票数据已刷新`);
setTimeout(() => {
handler.dispose();
}, 1000);
});
commands.registerCommand('leek-fund.deleteStock', (target) => {
LeekFundConfig.removeStockCfg(target.id, () => {
stockProvider.refresh();
});
});
commands.registerCommand('leek-fund.leekCenterView', () => {
if (stockService.stockList.length === 0 && fundService.fundList.length === 0) {
window.showWarningMessage('数据刷新中,请稍候!');
return;
}
leekCenterView(stockService, fundService);
});
commands.registerCommand('leek-fund.addStock', () => {
// vscode QuickPick 不支持动态查询,只能用此方式解决
// https://github.com/microsoft/vscode/issues/23633
const qp = window.createQuickPick();
qp.items = [{ label: '请输入关键词查询,如:0000001 或 上证指数' }];
let code: string | undefined;
let timer: NodeJS.Timer | null = null;
qp.onDidChangeValue((value) => {
qp.busy = true;
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(async () => {
const res = await stockService.getStockSuggestList(value);
qp.items = res;
qp.busy = false;
}, 100); // 简单防抖
});
qp.onDidChangeSelection((e) => {
if (e[0].description) {
code = e[0].label && e[0].label.split(' | ')[0];
}
});
qp.show();
qp.onDidAccept(() => {
if (!code) {
return;
}
// 存储到配置的时候是接口的参数格式,接口请求时不需要再转换
const newCode = code.replace('gb', 'gb_').replace('us', 'usr_');
LeekFundConfig.updateStockCfg(newCode, () => {
stockProvider.refresh();
});
qp.hide();
qp.dispose();
});
});
commands.registerCommand('leek-fund.sortStock', () => {
stockProvider.changeOrder();
stockProvider.refresh();
});
/**
* WebView
*/
// 股票点击
context.subscriptions.push(
commands.registerCommand('leek-fund.stockItemClick', (code, name, text, stockCode) =>
stockTrend(code, name, stockCode)
)
);
// 基金点击
context.subscriptions.push(
commands.registerCommand('leek-fund.fundItemClick', (code, name) => fundTrend(code, name))
);
// 基金右键历史信息点击
commands.registerCommand('leek-fund.viewFundHistory', (item) => fundHistory(item));
// 基金持仓
commands.registerCommand('leek-fund.viewFundPosition', (item) => fundPosition(item));
// 基金排行
commands.registerCommand('leek-fund.viewFundRank', () => fundRank());
// 基金走势图
commands.registerCommand('leek-fund.viewFundTrend', () => allFundTrend(fundService));
// 资金流向
commands.registerCommand('leek-fund.viewFundFlow', () => fundFlow());
commands.registerCommand('leek-fund.viewMainFundFlow', () => mainFundFlow());
// 基金置顶
commands.registerCommand('leek-fund.setFundTop', (target) => {
LeekFundConfig.setFundTopCfg(target.id, () => {
fundProvider.refresh();
});
});
// 股票置顶
commands.registerCommand('leek-fund.setStockTop', (target) => {
LeekFundConfig.setStockTopCfg(target.id, () => {
fundProvider.refresh();
});
});
// 设置基金持仓金额
commands.registerCommand('leek-fund.setFundAmount', () => {
if (fundService.fundList.length === 0) {
window.showWarningMessage('数据刷新中,请重试!');
return;
}
setAmount(fundService);
});
commands.registerCommand('leek-fund.stockTrendPic', (target) => {
const { code, name, type, symbol } = target.info;
stockTrendPic(code, name, `${type}${symbol}`);
});
/**
* News command
*/
commands.registerCommand('leek-fund.newItemClick', (userName, userId) => {
openNews(newsService, userId, userName);
});
commands.registerCommand('leek-fund.viewUserTimeline', (target) => {
const userName = target.label;
const userId = target.id;
openNews(newsService, userId, userName, true);
});
commands.registerCommand('leek-fund.addNews', () => {
window
.showInputBox({ placeHolder: '请输入雪球用户ID(进入用户首页复制最后的数字串)' })
.then(async (id) => {
if (!id) {
return;
}
const newsUserIds = LeekFundConfig.getConfig('leek-fund.newsUserIds') || [];
if (newsUserIds.includes(id)) {
window.showInformationMessage(`ID为 ${id} 的用户已存在,无需添加`);
return;
}
try {
const list = await newsService.getNewsUserList([id]);
if (list.length === 1) {
newsUserIds.push(id);
LeekFundConfig.setConfig('leek-fund.newsUserIds', newsUserIds).then(() => {
newsProvider.refresh();
});
}
} catch (e) {
window.showErrorMessage(`获取用户(${id})信息失败`);
}
});
});
commands.registerCommand('leek-fund.deleteUser', (target) => {
const newsUserIds = LeekFundConfig.getConfig('leek-fund.newsUserIds') || [];
const newIds = newsUserIds.filter((id: string) => id !== target.id);
LeekFundConfig.setConfig('leek-fund.newsUserIds', newIds).then(() => {
newsProvider.refresh();
});
});
commands.registerCommand('leek-fund.setXueqiuCookie', (target) => {
window
.showInputBox({
placeHolder:
'由于防爬虫机制,需要用户设置雪球网站 Cookie(进入雪球网站按F12——>NetWork 复制请求头的 Cookie 值)',
})
.then(async (cookieString = '') => {
const cookie = cookieString.trim();
if (!cookie) {
return;
}
console.log(cookie);
LeekFundConfig.setConfig('leek-fund.xueqiuCookie', cookie).then(() => {
newsProvider.refresh();
});
});
});
/**
* Binance command
*/
commands.registerCommand('leek-fund.refreshBinance', () => {
binanceProvider?.refresh();
});
/* 添加交易对 */
commands.registerCommand('leek-fund.addBinancePair', async () => {
const pairsList = await binanceService.getParis();
window.showQuickPick(pairsList, { placeHolder: '请输入交易对' }).then((pair) => {
if (!pair) return;
LeekFundConfig.updateBinanceCfg(pair, () => binanceProvider?.refresh());
});
});
/* 删除交易对 */
commands.registerCommand('leek-fund.deletePair', (target) => {
LeekFundConfig.removeBinanceCfg(target.id, () => {
binanceProvider?.refresh();
});
});
/* 交易对置顶 */
commands.registerCommand('leek-fund.setPairTop', (target) => {
LeekFundConfig.setBinanceTopCfg(target.id, () => {
binanceProvider?.refresh();
});
});
/**
* Settings command
*/
context.subscriptions.push(
commands.registerCommand('leek-fund.hideText', () => {
fundService.toggleLabel();
stockService.toggleLabel();
fundProvider.refresh();
stockProvider.refresh();
})
);
context.subscriptions.push(
commands.registerCommand('leek-fund.setStockStatusBar', () => {
const stockList = stockService.stockList;
const stockNameList = stockList.map((item: LeekTreeItem) => {
return {
label: `${item.info.name}`,
description: `${item.info.code}`,
};
});
window
.showQuickPick(stockNameList, {
placeHolder: '输入过滤选择,支持多选(限4个)',
canPickMany: true,
})
.then((res) => {
if (!res) {
res = [];
}
let codes = res.map((item) => item.description);
if (codes.length > 4) {
codes = codes.slice(0, 4);
}
LeekFundConfig.updateStatusBarStockCfg(codes, () => {
const handler = window.setStatusBarMessage(`下次数据刷新见效`);
setTimeout(() => {
handler.dispose();
}, 1500);
});
});
})
);
context.subscriptions.push(
commands.registerCommand('leek-fund.customSetting', () => {
const colorList = colorOptionList();
window
.showQuickPick(
[
{ label: '状态栏股票设置', description: 'statusbar-stock' },
{ label: '状态栏股票涨📈的文字颜色', description: 'statusbar-rise' },
{ label: '状态栏股票跌📉的文字颜色', description: 'statusbar-fall' },
{ label: '基金&股票涨跌图标更换', description: 'icontype' },
{ label: '👀显示/隐藏文本', description: 'hideText' },
{
label: globalState.showEarnings ? '隐藏盈亏' : '👀显示盈亏',
description: 'earnings',
},
{
label: globalState.remindSwitch ? '关闭提醒' : '🔔️打开提醒',
description: 'remindSwitch',
},
],
{
placeHolder: '第一步:选择设置项',
}
)
.then((item: any) => {
if (!item) {
return;
}
const type = item.description;
// 状态栏颜色设置
if (type === 'statusbar-rise' || type === 'statusbar-fall') {
window
.showQuickPick(colorList, {
placeHolder: `第二步:设置颜色(${item.label})`,
})
.then((colorItem: any) => {
if (!colorItem) {
return;
}
let color = colorItem.description;
if (color === 'random') {
color = randomColor();
}
LeekFundConfig.setConfig(
type === 'statusbar-rise' ? 'leek-fund.riseColor' : 'leek-fund.fallColor',
color
);
});
} else if (type === 'statusbar-stock') {
// 状态栏股票设置
commands.executeCommand('leek-fund.setStockStatusBar');
} else if (type === 'icontype') {
// 基金&股票涨跌图标
window
.showQuickPick(
[
{
label: '箭头图标',
description: 'arrow',
},
{
label: '食物图标1(吃面、吃鸡腿)',
description: 'food1',
},
{
label: '食物图标2(烤韭菜、烤肉)',
description: 'food2',
},
{
label: '食物图标3(吃面、喝酒)',
description: 'food3',
},
{
label: '食物字体图标(吃面、吃鸡腿)',
description: 'iconfood',
},
],
{
placeHolder: `第二步:选择基金&股票涨跌图标`,
}
)
.then((iconItem: any) => {
if (!iconItem) {
return;
}
if (globalState.iconType !== iconItem.description) {
LeekFundConfig.setConfig('leek-fund.iconType', iconItem.description);
globalState.iconType = iconItem.description;
}
});
} else if (type === 'earnings') {
const newValue = globalState.showEarnings === 1 ? 0 : 1;
LeekFundConfig.setConfig('leek-fund.showEarnings', newValue);
globalState.showEarnings = newValue;
} else if (type === 'hideText') {
commands.executeCommand('leek-fund.hideText');
} else if (type === 'remindSwitch') {
commands.executeCommand('leek-fund.toggleRemindSwitch');
}
});
})
);
context.subscriptions.push(
commands.registerCommand('leek-fund.openConfigPage', () => {
commands.executeCommand('workbench.action.openSettings', '@ext:giscafer.leek-fund');
})
);
context.subscriptions.push(commands.registerCommand('leek-fund.donate', () => donate(context)));
context.subscriptions.push(commands.registerCommand('leek-fund.tucaoForum', () => tucaoForum()));
context.subscriptions.push(
commands.registerCommand('leek-fund.toggleRemindSwitch', (on?: number) => {
const newValue = on !== undefined ? (on ? 1 : 0) : globalState.remindSwitch === 1 ? 0 : 1;
LeekFundConfig.setConfig('leek-fund.stockRemindSwitch', newValue);
globalState.remindSwitch = newValue;
})
);
context.subscriptions.push(
commands.registerCommand('leek-fund.changeStatusBarItem', (stockId) => {
const stockList = stockService.stockList;
const stockNameList = stockList
.filter((stock) => stock.id !== stockId)
.map((item: LeekTreeItem) => {
return {
label: `${item.info.name}`,
description: `${item.info.code}`,
};
});
window
.showQuickPick(stockNameList, {
placeHolder: '更换状态栏个股',
})
.then((res) => {
if (!res) return;
const statusBarStocks = LeekFundConfig.getConfig('leek-fund.statusBarStock');
const newCfg = [...statusBarStocks];
const newStockId = res.description;
const index = newCfg.indexOf(stockId);
if (statusBarStocks.includes(newStockId)) {
window.showWarningMessage(`「${res.label}」已在状态栏`);
return;
}
if (index > -1) {
newCfg[newCfg.indexOf(stockId)] = res.description;
}
LeekFundConfig.updateStatusBarStockCfg(newCfg, () => {
const handler = window.setStatusBarMessage(`下次数据刷新见效`);
setTimeout(() => {
handler.dispose();
}, 1500);
});
});
})
);
context.subscriptions.push(
commands.registerCommand('leek-fund.immersiveBackground', (isChecked: boolean) => {
LeekFundConfig.setConfig('leek-fund.immersiveBackground', isChecked);
globalState.immersiveBackground = isChecked;
})
);
context.subscriptions.push(
commands.registerCommand('leek-fund.switchStatusBarVisible', () => {
LeekFundConfig.setConfig(
'leek-fund.hideStatusBar',
!LeekFundConfig.getConfig('leek-fund.hideStatusBar')
);
})
);
checkForUpdate();
} | the_stack |
import React, { RefObject } from 'react';
import { Row, Col } from 'antd/lib/grid';
import Icon, { CloseCircleOutlined, PlusOutlined } from '@ant-design/icons';
import Input from 'antd/lib/input';
import Button from 'antd/lib/button';
import Checkbox from 'antd/lib/checkbox';
import Select from 'antd/lib/select';
import Form, { FormInstance } from 'antd/lib/form';
import Badge from 'antd/lib/badge';
import { Store } from 'antd/lib/form/interface';
import CVATTooltip from 'components/common/cvat-tooltip';
import ColorPicker from 'components/annotation-page/standard-workspace/objects-side-bar/color-picker';
import { ColorizeIcon } from 'icons';
import patterns from 'utils/validation-patterns';
import consts from 'consts';
import {
equalArrayHead, idGenerator, Label, Attribute,
} from './common';
export enum AttributeType {
SELECT = 'SELECT',
RADIO = 'RADIO',
CHECKBOX = 'CHECKBOX',
TEXT = 'TEXT',
NUMBER = 'NUMBER',
}
interface Props {
label: Label | null;
labelNames?: string[];
onSubmit: (label: Label | null) => void;
}
export default class LabelForm extends React.Component<Props> {
private continueAfterSubmit: boolean;
private formRef: RefObject<FormInstance>;
constructor(props: Props) {
super(props);
this.continueAfterSubmit = false;
this.formRef = React.createRef<FormInstance>();
}
private handleSubmit = (values: Store): void => {
const { label, onSubmit } = this.props;
onSubmit({
name: values.name,
id: label ? label.id : idGenerator(),
color: values.color,
attributes: (values.attributes || []).map((attribute: Store) => {
let attrValues: string | string[] = attribute.values;
if (!Array.isArray(attrValues)) {
if (attribute.type === AttributeType.NUMBER) {
attrValues = attrValues.split(';');
} else {
attrValues = [attrValues];
}
}
attrValues = attrValues.map((value: string) => value.trim());
return {
...attribute,
values: attrValues,
input_type: attribute.type.toLowerCase(),
};
}),
});
if (this.formRef.current) {
// resetFields does not remove existed attributes
this.formRef.current.setFieldsValue({ attributes: undefined });
this.formRef.current.resetFields();
}
if (!this.continueAfterSubmit) {
onSubmit(null);
}
};
private addAttribute = (): void => {
if (this.formRef.current) {
const attributes = this.formRef.current.getFieldValue('attributes');
this.formRef.current.setFieldsValue({ attributes: [...(attributes || []), { id: idGenerator() }] });
}
};
private removeAttribute = (key: number): void => {
if (this.formRef.current) {
const attributes = this.formRef.current.getFieldValue('attributes');
this.formRef.current.setFieldsValue({
attributes: attributes.filter((_: any, id: number) => id !== key),
});
}
};
/* eslint-disable class-methods-use-this */
private renderAttributeNameInput(fieldInstance: any, attr: Attribute | null): JSX.Element {
const { key } = fieldInstance;
const locked = attr ? attr.id >= 0 : false;
const value = attr ? attr.name : '';
return (
<Form.Item
hasFeedback
name={[key, 'name']}
fieldKey={[fieldInstance.fieldKey, 'name']}
initialValue={value}
rules={[
{
required: true,
message: 'Please specify a name',
},
{
pattern: patterns.validateAttributeName.pattern,
message: patterns.validateAttributeName.message,
},
]}
>
<Input className='cvat-attribute-name-input' disabled={locked} placeholder='Name' />
</Form.Item>
);
}
private renderAttributeTypeInput(fieldInstance: any, attr: Attribute | null): JSX.Element {
const { key } = fieldInstance;
const locked = attr ? attr.id >= 0 : false;
const type = attr ? attr.input_type.toUpperCase() : AttributeType.SELECT;
return (
<CVATTooltip title='An HTML element representing the attribute'>
<Form.Item name={[key, 'type']} fieldKey={[fieldInstance.fieldKey, 'type']} initialValue={type}>
<Select className='cvat-attribute-type-input' disabled={locked}>
<Select.Option value={AttributeType.SELECT} className='cvat-attribute-type-input-select'>
Select
</Select.Option>
<Select.Option value={AttributeType.RADIO} className='cvat-attribute-type-input-radio'>
Radio
</Select.Option>
<Select.Option value={AttributeType.CHECKBOX} className='cvat-attribute-type-input-checkbox'>
Checkbox
</Select.Option>
<Select.Option value={AttributeType.TEXT} className='cvat-attribute-type-input-text'>
Text
</Select.Option>
<Select.Option value={AttributeType.NUMBER} className='cvat-attribute-type-input-number'>
Number
</Select.Option>
</Select>
</Form.Item>
</CVATTooltip>
);
}
private renderAttributeValuesInput(fieldInstance: any, attr: Attribute | null): JSX.Element {
const { key } = fieldInstance;
const locked = attr ? attr.id >= 0 : false;
const existingValues = attr ? attr.values : [];
const validator = (_: any, values: string[]): Promise<void> => {
if (locked && existingValues) {
if (!equalArrayHead(existingValues, values)) {
return Promise.reject(new Error('You can only append new values'));
}
}
for (const value of values) {
if (!patterns.validateAttributeValue.pattern.test(value)) {
return Promise.reject(new Error(`Invalid attribute value: "${value}"`));
}
}
return Promise.resolve();
};
return (
<CVATTooltip title='Press enter to add a new value'>
<Form.Item
name={[key, 'values']}
fieldKey={[fieldInstance.fieldKey, 'values']}
initialValue={existingValues}
rules={[
{
required: true,
message: 'Please specify values',
},
{
validator,
},
]}
>
<Select
className='cvat-attribute-values-input'
mode='tags'
placeholder='Attribute values'
dropdownStyle={{ display: 'none' }}
/>
</Form.Item>
</CVATTooltip>
);
}
private renderBooleanValueInput(fieldInstance: any, attr: Attribute | null): JSX.Element {
const { key } = fieldInstance;
const value = attr ? attr.values[0] : 'false';
return (
<CVATTooltip title='Specify a default value'>
<Form.Item name={[key, 'values']} fieldKey={[fieldInstance.fieldKey, 'values']} initialValue={value}>
<Select className='cvat-attribute-values-input'>
<Select.Option value='false'>False</Select.Option>
<Select.Option value='true'>True</Select.Option>
</Select>
</Form.Item>
</CVATTooltip>
);
}
private renderNumberRangeInput(fieldInstance: any, attr: Attribute | null): JSX.Element {
const { key } = fieldInstance;
const locked = attr ? attr.id >= 0 : false;
const value = attr ? attr.values : '';
const validator = (_: any, strNumbers: string): Promise<void> => {
const numbers = strNumbers.split(';').map((number): number => Number.parseFloat(number));
if (numbers.length !== 3) {
return Promise.reject(new Error('Three numbers are expected'));
}
for (const number of numbers) {
if (Number.isNaN(number)) {
return Promise.reject(new Error(`"${number}" is not a number`));
}
}
const [min, max, step] = numbers;
if (min >= max) {
return Promise.reject(new Error('Minimum must be less than maximum'));
}
if (max - min < step) {
return Promise.reject(new Error('Step must be less than minmax difference'));
}
if (step <= 0) {
return Promise.reject(new Error('Step must be a positive number'));
}
return Promise.resolve();
};
return (
<Form.Item
name={[key, 'values']}
fieldKey={[fieldInstance.fieldKey, 'values']}
initialValue={value}
rules={[
{
required: true,
message: 'Please set a range',
},
{
validator,
},
]}
>
<Input className='cvat-attribute-values-input' disabled={locked} placeholder='min;max;step' />
</Form.Item>
);
}
private renderDefaultValueInput(fieldInstance: any, attr: Attribute | null): JSX.Element {
const { key } = fieldInstance;
const value = attr ? attr.values[0] : '';
return (
<Form.Item name={[key, 'values']} fieldKey={[fieldInstance.fieldKey, 'values']} initialValue={value}>
<Input className='cvat-attribute-values-input' placeholder='Default value' />
</Form.Item>
);
}
private renderMutableAttributeInput(fieldInstance: any, attr: Attribute | null): JSX.Element {
const { key } = fieldInstance;
const locked = attr ? attr.id >= 0 : false;
const value = attr ? attr.mutable : false;
return (
<CVATTooltip title='Can this attribute be changed frame to frame?'>
<Form.Item
name={[key, 'mutable']}
fieldKey={[fieldInstance.fieldKey, 'mutable']}
initialValue={value}
valuePropName='checked'
>
<Checkbox className='cvat-attribute-mutable-checkbox' disabled={locked}>
Mutable
</Checkbox>
</Form.Item>
</CVATTooltip>
);
}
private renderDeleteAttributeButton(fieldInstance: any, attr: Attribute | null): JSX.Element {
const { key } = fieldInstance;
const locked = attr ? attr.id >= 0 : false;
return (
<CVATTooltip title='Delete the attribute'>
<Form.Item>
<Button
type='link'
className='cvat-delete-attribute-button'
disabled={locked}
onClick={(): void => {
this.removeAttribute(key);
}}
>
<CloseCircleOutlined />
</Button>
</Form.Item>
</CVATTooltip>
);
}
private renderAttribute = (fieldInstance: any): JSX.Element => {
const { label } = this.props;
const { key } = fieldInstance;
const fieldValue = this.formRef.current?.getFieldValue('attributes')[key];
const attr = label ? label.attributes.filter((_attr: any): boolean => _attr.id === fieldValue.id)[0] : null;
return (
<Form.Item noStyle key={key} shouldUpdate>
{() => (
<Row
justify='space-between'
align='top'
cvat-attribute-id={fieldValue.id}
className='cvat-attribute-inputs-wrapper'
>
<Col span={5}>{this.renderAttributeNameInput(fieldInstance, attr)}</Col>
<Col span={4}>{this.renderAttributeTypeInput(fieldInstance, attr)}</Col>
<Col span={6}>
{((): JSX.Element => {
const currentFieldValue = this.formRef.current?.getFieldValue('attributes')[key];
const type = currentFieldValue.type || AttributeType.SELECT;
let element = null;
if ([AttributeType.SELECT, AttributeType.RADIO].includes(type)) {
element = this.renderAttributeValuesInput(fieldInstance, attr);
} else if (type === AttributeType.CHECKBOX) {
element = this.renderBooleanValueInput(fieldInstance, attr);
} else if (type === AttributeType.NUMBER) {
element = this.renderNumberRangeInput(fieldInstance, attr);
} else {
element = this.renderDefaultValueInput(fieldInstance, attr);
}
return element;
})()}
</Col>
<Col span={5}>{this.renderMutableAttributeInput(fieldInstance, attr)}</Col>
<Col span={2}>{this.renderDeleteAttributeButton(fieldInstance, attr)}</Col>
</Row>
)}
</Form.Item>
);
};
private renderLabelNameInput(): JSX.Element {
const { label, labelNames } = this.props;
const value = label ? label.name : '';
return (
<Form.Item
hasFeedback
name='name'
initialValue={value}
rules={[
{
required: true,
message: 'Please specify a name',
},
{
pattern: patterns.validateAttributeName.pattern,
message: patterns.validateAttributeName.message,
},
{
validator: (_rule: any, labelName: string) => {
if (labelNames && labelNames.includes(labelName)) {
return Promise.reject(new Error('Label name must be unique for the task'));
}
return Promise.resolve();
},
},
]}
>
<Input placeholder='Label name' />
</Form.Item>
);
}
private renderNewAttributeButton(): JSX.Element {
return (
<Form.Item>
<Button type='ghost' onClick={this.addAttribute} className='cvat-new-attribute-button'>
Add an attribute
<PlusOutlined />
</Button>
</Form.Item>
);
}
private renderDoneButton(): JSX.Element {
return (
<CVATTooltip title='Save the label and return'>
<Button
style={{ width: '150px' }}
type='primary'
htmlType='submit'
onClick={(): void => {
this.continueAfterSubmit = false;
}}
>
Done
</Button>
</CVATTooltip>
);
}
private renderContinueButton(): JSX.Element | null {
const { label } = this.props;
if (label) return null;
return (
<CVATTooltip title='Save the label and create one more'>
<Button
style={{ width: '150px' }}
type='primary'
htmlType='submit'
onClick={(): void => {
this.continueAfterSubmit = true;
}}
>
Continue
</Button>
</CVATTooltip>
);
}
private renderCancelButton(): JSX.Element {
const { onSubmit } = this.props;
return (
<CVATTooltip title='Do not save the label and return'>
<Button
type='primary'
danger
style={{ width: '150px' }}
onClick={(): void => {
onSubmit(null);
}}
>
Cancel
</Button>
</CVATTooltip>
);
}
private renderChangeColorButton(): JSX.Element {
const { label } = this.props;
return (
<Form.Item noStyle shouldUpdate>
{() => (
<Form.Item name='color' initialValue={label ? label?.color : undefined}>
<ColorPicker placement='bottom'>
<CVATTooltip title='Change color of the label'>
<Button type='default' className='cvat-change-task-label-color-button'>
<Badge
className='cvat-change-task-label-color-badge'
color={this.formRef.current?.getFieldValue('color') || consts.NEW_LABEL_COLOR}
text={<Icon component={ColorizeIcon} />}
/>
</Button>
</CVATTooltip>
</ColorPicker>
</Form.Item>
)}
</Form.Item>
);
}
private renderAttributes() {
return (fieldInstances: any[]): JSX.Element[] => fieldInstances.map(this.renderAttribute);
}
// eslint-disable-next-line react/sort-comp
public componentDidMount(): void {
const { label } = this.props;
if (this.formRef.current && label && label.attributes.length) {
const convertedAttributes = label.attributes.map(
(attribute: Attribute): Store => ({
...attribute,
values:
attribute.input_type.toUpperCase() === 'NUMBER' ? attribute.values.join(';') : attribute.values,
type: attribute.input_type.toUpperCase(),
}),
);
for (const attr of convertedAttributes) {
delete attr.input_type;
}
this.formRef.current.setFieldsValue({ attributes: convertedAttributes });
}
}
public render(): JSX.Element {
return (
<Form onFinish={this.handleSubmit} layout='vertical' ref={this.formRef}>
<Row justify='start' align='top'>
<Col span={10}>{this.renderLabelNameInput()}</Col>
<Col span={3} offset={1}>
{this.renderChangeColorButton()}
</Col>
<Col span={6} offset={1}>
{this.renderNewAttributeButton()}
</Col>
</Row>
<Row justify='start' align='top'>
<Col span={24}>
<Form.List name='attributes'>{this.renderAttributes()}</Form.List>
</Col>
</Row>
<Row justify='start' align='middle'>
<Col>{this.renderDoneButton()}</Col>
<Col offset={1}>{this.renderContinueButton()}</Col>
<Col offset={1}>{this.renderCancelButton()}</Col>
</Row>
</Form>
);
}
} | the_stack |
import { GraphQLResolveInfo, GraphQLScalarType, GraphQLScalarTypeConfig } from 'graphql';
export type Maybe<T> = T | null;
export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };
export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> };
export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> };
export type RequireFields<T, K extends keyof T> = { [X in Exclude<keyof T, K>]?: T[X] } & { [P in K]-?: NonNullable<T[P]> };
/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
ID: string;
String: string;
Boolean: boolean;
Int: number;
Float: number;
/** A date-time string at UTC, such as 2007-12-03T10:15:30Z, compliant with the `date-time` format outlined in section 5.6 of the RFC 3339 profile of the ISO 8601 standard for representation of dates and times using the Gregorian calendar. */
DateTime: Date;
/** The `Upload` scalar type represents a file upload. */
Upload: any;
};
export type App = {
__typename?: 'App';
id: Scalars['ID'];
name: Scalars['String'];
createdAt: Scalars['DateTime'];
type: AppTypes;
databases?: Maybe<Array<Database>>;
appMetaGithub?: Maybe<AppMetaGithub>;
};
export type User = {
__typename?: 'User';
userName: Scalars['String'];
};
export type GithubAppInstallationId = {
__typename?: 'GithubAppInstallationId';
id: Scalars['String'];
};
export type AppMetaGithub = {
__typename?: 'AppMetaGithub';
repoId: Scalars['String'];
repoName: Scalars['String'];
repoOwner: Scalars['String'];
branch: Scalars['String'];
githubAppInstallationId: Scalars['String'];
};
export type Repository = {
__typename?: 'Repository';
id: Scalars['String'];
name: Scalars['String'];
fullName: Scalars['String'];
private: Scalars['Boolean'];
};
export type Branch = {
__typename?: 'Branch';
name: Scalars['String'];
};
export type AppTypes =
| 'DOKKU'
| 'GITHUB'
| 'GITLAB'
| 'DOCKER';
export type AppBuild = {
__typename?: 'AppBuild';
id: Scalars['ID'];
status: AppBuildStatus;
};
export type AppBuildStatus =
| 'PENDING'
| 'IN_PROGRESS'
| 'COMPLETED'
| 'ERRORED';
export type Database = {
__typename?: 'Database';
id: Scalars['ID'];
name: Scalars['String'];
type: DatabaseTypes;
version?: Maybe<Scalars['String']>;
createdAt: Scalars['DateTime'];
apps?: Maybe<Array<App>>;
};
export type DatabaseTypes =
| 'REDIS'
| 'POSTGRESQL'
| 'MONGODB'
| 'MYSQL';
export type Domains = {
__typename?: 'Domains';
domains: Array<Scalars['String']>;
};
export type RealTimeLog = {
__typename?: 'RealTimeLog';
message?: Maybe<Scalars['String']>;
type?: Maybe<Scalars['String']>;
};
export type LoginResult = {
__typename?: 'LoginResult';
token: Scalars['String'];
};
export type RegisterGithubAppResult = {
__typename?: 'RegisterGithubAppResult';
githubAppClientId: Scalars['String'];
};
export type CreateAppDokkuResult = {
__typename?: 'CreateAppDokkuResult';
appId: Scalars['String'];
};
export type CreateAppGithubResult = {
__typename?: 'CreateAppGithubResult';
result: Scalars['Boolean'];
};
export type DestroyAppResult = {
__typename?: 'DestroyAppResult';
result: Scalars['Boolean'];
};
export type RestartAppResult = {
__typename?: 'RestartAppResult';
result: Scalars['Boolean'];
};
export type RebuildAppResult = {
__typename?: 'RebuildAppResult';
result: Scalars['Boolean'];
};
export type DestroyDatabaseResult = {
__typename?: 'DestroyDatabaseResult';
result: Scalars['Boolean'];
};
export type LinkDatabaseResult = {
__typename?: 'LinkDatabaseResult';
result: Scalars['Boolean'];
};
export type UnlinkDatabaseResult = {
__typename?: 'UnlinkDatabaseResult';
result: Scalars['Boolean'];
};
export type DokkuPlugin = {
__typename?: 'DokkuPlugin';
name: Scalars['String'];
version: Scalars['String'];
};
export type DokkuPluginResult = {
__typename?: 'DokkuPluginResult';
version: Scalars['String'];
plugins: Array<DokkuPlugin>;
};
export type SetEnvVarResult = {
__typename?: 'SetEnvVarResult';
result: Scalars['Boolean'];
};
export type UnsetEnvVarResult = {
__typename?: 'UnsetEnvVarResult';
result: Scalars['Boolean'];
};
export type CreateDatabaseResult = {
__typename?: 'CreateDatabaseResult';
result: Scalars['Boolean'];
};
export type AppLogsResult = {
__typename?: 'AppLogsResult';
logs: Array<Scalars['String']>;
};
export type DatabaseInfoResult = {
__typename?: 'DatabaseInfoResult';
info: Array<Scalars['String']>;
};
export type DatabaseLogsResult = {
__typename?: 'DatabaseLogsResult';
logs: Array<Maybe<Scalars['String']>>;
};
export type IsDatabaseLinkedResult = {
__typename?: 'IsDatabaseLinkedResult';
isLinked: Scalars['Boolean'];
};
export type EnvVar = {
__typename?: 'EnvVar';
key: Scalars['String'];
value: Scalars['String'];
};
export type EnvVarsResult = {
__typename?: 'EnvVarsResult';
envVars: Array<EnvVar>;
};
export type SetDomainResult = {
__typename?: 'SetDomainResult';
result: Scalars['Boolean'];
};
export type AddDomainResult = {
__typename?: 'AddDomainResult';
result: Scalars['Boolean'];
};
export type RemoveDomainResult = {
__typename?: 'RemoveDomainResult';
result: Scalars['Boolean'];
};
export type SetupResult = {
__typename?: 'SetupResult';
canConnectSsh: Scalars['Boolean'];
sshPublicKey: Scalars['String'];
isGithubAppSetup: Scalars['Boolean'];
githubAppManifest: Scalars['String'];
};
export type IsPluginInstalledResult = {
__typename?: 'IsPluginInstalledResult';
isPluginInstalled: Scalars['Boolean'];
};
export type AppProxyPort = {
__typename?: 'AppProxyPort';
scheme: Scalars['String'];
host: Scalars['String'];
container: Scalars['String'];
};
export type CreateAppDokkuInput = {
name: Scalars['String'];
};
export type CreateAppGithubInput = {
name: Scalars['String'];
gitRepoFullName: Scalars['String'];
branchName: Scalars['String'];
gitRepoId: Scalars['String'];
githubInstallationId: Scalars['String'];
};
export type RestartAppInput = {
appId: Scalars['String'];
};
export type RebuildAppInput = {
appId: Scalars['String'];
};
export type CreateDatabaseInput = {
name: Scalars['String'];
type: DatabaseTypes;
};
export type UnlinkDatabaseInput = {
appId: Scalars['String'];
databaseId: Scalars['String'];
};
export type SetEnvVarInput = {
appId: Scalars['String'];
key: Scalars['String'];
value: Scalars['String'];
};
export type UnsetEnvVarInput = {
appId: Scalars['String'];
key: Scalars['String'];
};
export type DestroyAppInput = {
appId: Scalars['String'];
};
export type AddDomainInput = {
appId: Scalars['String'];
domainName: Scalars['String'];
};
export type RemoveDomainInput = {
appId: Scalars['String'];
domainName: Scalars['String'];
};
export type SetDomainInput = {
appId: Scalars['String'];
domainName: Scalars['String'];
};
export type LinkDatabaseInput = {
appId: Scalars['String'];
databaseId: Scalars['String'];
};
export type DestroyDatabaseInput = {
databaseId: Scalars['String'];
};
export type AddAppProxyPortInput = {
appId: Scalars['String'];
host: Scalars['String'];
container: Scalars['String'];
};
export type RemoveAppProxyPortInput = {
appId: Scalars['String'];
scheme: Scalars['String'];
host: Scalars['String'];
container: Scalars['String'];
};
export type Query = {
__typename?: 'Query';
githubInstallationId: GithubAppInstallationId;
setup: SetupResult;
apps: Array<App>;
user: User;
repositories: Array<Repository>;
branches: Array<Branch>;
appMetaGithub?: Maybe<AppMetaGithub>;
app?: Maybe<App>;
domains: Domains;
database?: Maybe<Database>;
databases: Array<Database>;
isPluginInstalled: IsPluginInstalledResult;
dokkuPlugins: DokkuPluginResult;
appLogs: AppLogsResult;
databaseInfo: DatabaseInfoResult;
databaseLogs: DatabaseLogsResult;
isDatabaseLinked: IsDatabaseLinkedResult;
envVars: EnvVarsResult;
appProxyPorts: Array<AppProxyPort>;
};
export type QueryRepositoriesArgs = {
installationId: Scalars['String'];
};
export type QueryBranchesArgs = {
repositoryName: Scalars['String'];
installationId: Scalars['String'];
};
export type QueryAppMetaGithubArgs = {
appId: Scalars['String'];
};
export type QueryAppArgs = {
appId: Scalars['String'];
};
export type QueryDomainsArgs = {
appId: Scalars['String'];
};
export type QueryDatabaseArgs = {
databaseId: Scalars['String'];
};
export type QueryIsPluginInstalledArgs = {
pluginName: Scalars['String'];
};
export type QueryAppLogsArgs = {
appId: Scalars['String'];
};
export type QueryDatabaseInfoArgs = {
databaseId: Scalars['String'];
};
export type QueryDatabaseLogsArgs = {
databaseId: Scalars['String'];
};
export type QueryIsDatabaseLinkedArgs = {
databaseId: Scalars['String'];
appId: Scalars['String'];
};
export type QueryEnvVarsArgs = {
appId: Scalars['String'];
};
export type QueryAppProxyPortsArgs = {
appId: Scalars['String'];
};
export type Subscription = {
__typename?: 'Subscription';
unlinkDatabaseLogs: RealTimeLog;
linkDatabaseLogs: RealTimeLog;
createDatabaseLogs: RealTimeLog;
appRestartLogs: RealTimeLog;
appRebuildLogs: RealTimeLog;
appCreateLogs: RealTimeLog;
};
export type Mutation = {
__typename?: 'Mutation';
loginWithGithub?: Maybe<LoginResult>;
registerGithubApp?: Maybe<RegisterGithubAppResult>;
addDomain: AddDomainResult;
removeDomain: RemoveDomainResult;
setDomain: SetDomainResult;
createAppDokku: CreateAppDokkuResult;
createDatabase: CreateDatabaseResult;
setEnvVar: SetEnvVarResult;
unsetEnvVar: UnsetEnvVarResult;
destroyApp: DestroyAppResult;
restartApp: RestartAppResult;
rebuildApp: RebuildAppResult;
destroyDatabase: DestroyDatabaseResult;
linkDatabase: LinkDatabaseResult;
unlinkDatabase: UnlinkDatabaseResult;
addAppProxyPort?: Maybe<Scalars['Boolean']>;
removeAppProxyPort?: Maybe<Scalars['Boolean']>;
createAppGithub: CreateAppGithubResult;
};
export type MutationLoginWithGithubArgs = {
code: Scalars['String'];
};
export type MutationRegisterGithubAppArgs = {
code: Scalars['String'];
};
export type MutationAddDomainArgs = {
input: AddDomainInput;
};
export type MutationRemoveDomainArgs = {
input: RemoveDomainInput;
};
export type MutationSetDomainArgs = {
input: SetDomainInput;
};
export type MutationCreateAppDokkuArgs = {
input: CreateAppDokkuInput;
};
export type MutationCreateDatabaseArgs = {
input: CreateDatabaseInput;
};
export type MutationSetEnvVarArgs = {
input: SetEnvVarInput;
};
export type MutationUnsetEnvVarArgs = {
input: UnsetEnvVarInput;
};
export type MutationDestroyAppArgs = {
input: DestroyAppInput;
};
export type MutationRestartAppArgs = {
input: RestartAppInput;
};
export type MutationRebuildAppArgs = {
input: RebuildAppInput;
};
export type MutationDestroyDatabaseArgs = {
input: DestroyDatabaseInput;
};
export type MutationLinkDatabaseArgs = {
input: LinkDatabaseInput;
};
export type MutationUnlinkDatabaseArgs = {
input: UnlinkDatabaseInput;
};
export type MutationAddAppProxyPortArgs = {
input: AddAppProxyPortInput;
};
export type MutationRemoveAppProxyPortArgs = {
input: RemoveAppProxyPortInput;
};
export type MutationCreateAppGithubArgs = {
input: CreateAppGithubInput;
};
export type CacheControlScope =
| 'PUBLIC'
| 'PRIVATE';
export type ResolverTypeWrapper<T> = Promise<T> | T;
export type LegacyStitchingResolver<TResult, TParent, TContext, TArgs> = {
fragment: string;
resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
};
export type NewStitchingResolver<TResult, TParent, TContext, TArgs> = {
selectionSet: string;
resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
};
export type StitchingResolver<TResult, TParent, TContext, TArgs> = LegacyStitchingResolver<TResult, TParent, TContext, TArgs> | NewStitchingResolver<TResult, TParent, TContext, TArgs>;
export type Resolver<TResult, TParent = {}, TContext = {}, TArgs = {}> =
| ResolverFn<TResult, TParent, TContext, TArgs>
| StitchingResolver<TResult, TParent, TContext, TArgs>;
export type ResolverFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => Promise<TResult> | TResult;
export type SubscriptionSubscribeFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => AsyncIterator<TResult> | Promise<AsyncIterator<TResult>>;
export type SubscriptionResolveFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => TResult | Promise<TResult>;
export interface SubscriptionSubscriberObject<TResult, TKey extends string, TParent, TContext, TArgs> {
subscribe: SubscriptionSubscribeFn<{ [key in TKey]: TResult }, TParent, TContext, TArgs>;
resolve?: SubscriptionResolveFn<TResult, { [key in TKey]: TResult }, TContext, TArgs>;
}
export interface SubscriptionResolverObject<TResult, TParent, TContext, TArgs> {
subscribe: SubscriptionSubscribeFn<any, TParent, TContext, TArgs>;
resolve: SubscriptionResolveFn<TResult, any, TContext, TArgs>;
}
export type SubscriptionObject<TResult, TKey extends string, TParent, TContext, TArgs> =
| SubscriptionSubscriberObject<TResult, TKey, TParent, TContext, TArgs>
| SubscriptionResolverObject<TResult, TParent, TContext, TArgs>;
export type SubscriptionResolver<TResult, TKey extends string, TParent = {}, TContext = {}, TArgs = {}> =
| ((...args: any[]) => SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>)
| SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>;
export type TypeResolveFn<TTypes, TParent = {}, TContext = {}> = (
parent: TParent,
context: TContext,
info: GraphQLResolveInfo
) => Maybe<TTypes> | Promise<Maybe<TTypes>>;
export type IsTypeOfResolverFn<T = {}, TContext = {}> = (obj: T, context: TContext, info: GraphQLResolveInfo) => boolean | Promise<boolean>;
export type NextResolverFn<T> = () => Promise<T>;
export type DirectiveResolverFn<TResult = {}, TParent = {}, TContext = {}, TArgs = {}> = (
next: NextResolverFn<TResult>,
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => TResult | Promise<TResult>;
/** Mapping between all available schema types and the resolvers types */
export type ResolversTypes = {
DateTime: ResolverTypeWrapper<Scalars['DateTime']>;
App: ResolverTypeWrapper<App>;
ID: ResolverTypeWrapper<Scalars['ID']>;
String: ResolverTypeWrapper<Scalars['String']>;
User: ResolverTypeWrapper<User>;
GithubAppInstallationId: ResolverTypeWrapper<GithubAppInstallationId>;
AppMetaGithub: ResolverTypeWrapper<AppMetaGithub>;
Repository: ResolverTypeWrapper<Repository>;
Boolean: ResolverTypeWrapper<Scalars['Boolean']>;
Branch: ResolverTypeWrapper<Branch>;
AppTypes: AppTypes;
AppBuild: ResolverTypeWrapper<AppBuild>;
AppBuildStatus: AppBuildStatus;
Database: ResolverTypeWrapper<Database>;
DatabaseTypes: DatabaseTypes;
Domains: ResolverTypeWrapper<Domains>;
RealTimeLog: ResolverTypeWrapper<RealTimeLog>;
LoginResult: ResolverTypeWrapper<LoginResult>;
RegisterGithubAppResult: ResolverTypeWrapper<RegisterGithubAppResult>;
CreateAppDokkuResult: ResolverTypeWrapper<CreateAppDokkuResult>;
CreateAppGithubResult: ResolverTypeWrapper<CreateAppGithubResult>;
DestroyAppResult: ResolverTypeWrapper<DestroyAppResult>;
RestartAppResult: ResolverTypeWrapper<RestartAppResult>;
RebuildAppResult: ResolverTypeWrapper<RebuildAppResult>;
DestroyDatabaseResult: ResolverTypeWrapper<DestroyDatabaseResult>;
LinkDatabaseResult: ResolverTypeWrapper<LinkDatabaseResult>;
UnlinkDatabaseResult: ResolverTypeWrapper<UnlinkDatabaseResult>;
DokkuPlugin: ResolverTypeWrapper<DokkuPlugin>;
DokkuPluginResult: ResolverTypeWrapper<DokkuPluginResult>;
SetEnvVarResult: ResolverTypeWrapper<SetEnvVarResult>;
UnsetEnvVarResult: ResolverTypeWrapper<UnsetEnvVarResult>;
CreateDatabaseResult: ResolverTypeWrapper<CreateDatabaseResult>;
AppLogsResult: ResolverTypeWrapper<AppLogsResult>;
DatabaseInfoResult: ResolverTypeWrapper<DatabaseInfoResult>;
DatabaseLogsResult: ResolverTypeWrapper<DatabaseLogsResult>;
IsDatabaseLinkedResult: ResolverTypeWrapper<IsDatabaseLinkedResult>;
EnvVar: ResolverTypeWrapper<EnvVar>;
EnvVarsResult: ResolverTypeWrapper<EnvVarsResult>;
SetDomainResult: ResolverTypeWrapper<SetDomainResult>;
AddDomainResult: ResolverTypeWrapper<AddDomainResult>;
RemoveDomainResult: ResolverTypeWrapper<RemoveDomainResult>;
SetupResult: ResolverTypeWrapper<SetupResult>;
IsPluginInstalledResult: ResolverTypeWrapper<IsPluginInstalledResult>;
AppProxyPort: ResolverTypeWrapper<AppProxyPort>;
CreateAppDokkuInput: CreateAppDokkuInput;
CreateAppGithubInput: CreateAppGithubInput;
RestartAppInput: RestartAppInput;
RebuildAppInput: RebuildAppInput;
CreateDatabaseInput: CreateDatabaseInput;
UnlinkDatabaseInput: UnlinkDatabaseInput;
SetEnvVarInput: SetEnvVarInput;
UnsetEnvVarInput: UnsetEnvVarInput;
DestroyAppInput: DestroyAppInput;
AddDomainInput: AddDomainInput;
RemoveDomainInput: RemoveDomainInput;
SetDomainInput: SetDomainInput;
LinkDatabaseInput: LinkDatabaseInput;
DestroyDatabaseInput: DestroyDatabaseInput;
AddAppProxyPortInput: AddAppProxyPortInput;
RemoveAppProxyPortInput: RemoveAppProxyPortInput;
Query: ResolverTypeWrapper<{}>;
Subscription: ResolverTypeWrapper<{}>;
Mutation: ResolverTypeWrapper<{}>;
CacheControlScope: CacheControlScope;
Upload: ResolverTypeWrapper<Scalars['Upload']>;
Int: ResolverTypeWrapper<Scalars['Int']>;
};
/** Mapping between all available schema types and the resolvers parents */
export type ResolversParentTypes = {
DateTime: Scalars['DateTime'];
App: App;
ID: Scalars['ID'];
String: Scalars['String'];
User: User;
GithubAppInstallationId: GithubAppInstallationId;
AppMetaGithub: AppMetaGithub;
Repository: Repository;
Boolean: Scalars['Boolean'];
Branch: Branch;
AppBuild: AppBuild;
Database: Database;
Domains: Domains;
RealTimeLog: RealTimeLog;
LoginResult: LoginResult;
RegisterGithubAppResult: RegisterGithubAppResult;
CreateAppDokkuResult: CreateAppDokkuResult;
CreateAppGithubResult: CreateAppGithubResult;
DestroyAppResult: DestroyAppResult;
RestartAppResult: RestartAppResult;
RebuildAppResult: RebuildAppResult;
DestroyDatabaseResult: DestroyDatabaseResult;
LinkDatabaseResult: LinkDatabaseResult;
UnlinkDatabaseResult: UnlinkDatabaseResult;
DokkuPlugin: DokkuPlugin;
DokkuPluginResult: DokkuPluginResult;
SetEnvVarResult: SetEnvVarResult;
UnsetEnvVarResult: UnsetEnvVarResult;
CreateDatabaseResult: CreateDatabaseResult;
AppLogsResult: AppLogsResult;
DatabaseInfoResult: DatabaseInfoResult;
DatabaseLogsResult: DatabaseLogsResult;
IsDatabaseLinkedResult: IsDatabaseLinkedResult;
EnvVar: EnvVar;
EnvVarsResult: EnvVarsResult;
SetDomainResult: SetDomainResult;
AddDomainResult: AddDomainResult;
RemoveDomainResult: RemoveDomainResult;
SetupResult: SetupResult;
IsPluginInstalledResult: IsPluginInstalledResult;
AppProxyPort: AppProxyPort;
CreateAppDokkuInput: CreateAppDokkuInput;
CreateAppGithubInput: CreateAppGithubInput;
RestartAppInput: RestartAppInput;
RebuildAppInput: RebuildAppInput;
CreateDatabaseInput: CreateDatabaseInput;
UnlinkDatabaseInput: UnlinkDatabaseInput;
SetEnvVarInput: SetEnvVarInput;
UnsetEnvVarInput: UnsetEnvVarInput;
DestroyAppInput: DestroyAppInput;
AddDomainInput: AddDomainInput;
RemoveDomainInput: RemoveDomainInput;
SetDomainInput: SetDomainInput;
LinkDatabaseInput: LinkDatabaseInput;
DestroyDatabaseInput: DestroyDatabaseInput;
AddAppProxyPortInput: AddAppProxyPortInput;
RemoveAppProxyPortInput: RemoveAppProxyPortInput;
Query: {};
Subscription: {};
Mutation: {};
Upload: Scalars['Upload'];
Int: Scalars['Int'];
};
export type CacheControlDirectiveArgs = { maxAge?: Maybe<Scalars['Int']>;
scope?: Maybe<CacheControlScope>; };
export type CacheControlDirectiveResolver<Result, Parent, ContextType = any, Args = CacheControlDirectiveArgs> = DirectiveResolverFn<Result, Parent, ContextType, Args>;
export interface DateTimeScalarConfig extends GraphQLScalarTypeConfig<ResolversTypes['DateTime'], any> {
name: 'DateTime';
}
export type AppResolvers<ContextType = any, ParentType extends ResolversParentTypes['App'] = ResolversParentTypes['App']> = {
id?: Resolver<ResolversTypes['ID'], ParentType, ContextType>;
name?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
createdAt?: Resolver<ResolversTypes['DateTime'], ParentType, ContextType>;
type?: Resolver<ResolversTypes['AppTypes'], ParentType, ContextType>;
databases?: Resolver<Maybe<Array<ResolversTypes['Database']>>, ParentType, ContextType>;
appMetaGithub?: Resolver<Maybe<ResolversTypes['AppMetaGithub']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type UserResolvers<ContextType = any, ParentType extends ResolversParentTypes['User'] = ResolversParentTypes['User']> = {
userName?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type GithubAppInstallationIdResolvers<ContextType = any, ParentType extends ResolversParentTypes['GithubAppInstallationId'] = ResolversParentTypes['GithubAppInstallationId']> = {
id?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type AppMetaGithubResolvers<ContextType = any, ParentType extends ResolversParentTypes['AppMetaGithub'] = ResolversParentTypes['AppMetaGithub']> = {
repoId?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
repoName?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
repoOwner?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
branch?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
githubAppInstallationId?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type RepositoryResolvers<ContextType = any, ParentType extends ResolversParentTypes['Repository'] = ResolversParentTypes['Repository']> = {
id?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
name?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
fullName?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
private?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type BranchResolvers<ContextType = any, ParentType extends ResolversParentTypes['Branch'] = ResolversParentTypes['Branch']> = {
name?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type AppBuildResolvers<ContextType = any, ParentType extends ResolversParentTypes['AppBuild'] = ResolversParentTypes['AppBuild']> = {
id?: Resolver<ResolversTypes['ID'], ParentType, ContextType>;
status?: Resolver<ResolversTypes['AppBuildStatus'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type DatabaseResolvers<ContextType = any, ParentType extends ResolversParentTypes['Database'] = ResolversParentTypes['Database']> = {
id?: Resolver<ResolversTypes['ID'], ParentType, ContextType>;
name?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
type?: Resolver<ResolversTypes['DatabaseTypes'], ParentType, ContextType>;
version?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
createdAt?: Resolver<ResolversTypes['DateTime'], ParentType, ContextType>;
apps?: Resolver<Maybe<Array<ResolversTypes['App']>>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type DomainsResolvers<ContextType = any, ParentType extends ResolversParentTypes['Domains'] = ResolversParentTypes['Domains']> = {
domains?: Resolver<Array<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type RealTimeLogResolvers<ContextType = any, ParentType extends ResolversParentTypes['RealTimeLog'] = ResolversParentTypes['RealTimeLog']> = {
message?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
type?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type LoginResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['LoginResult'] = ResolversParentTypes['LoginResult']> = {
token?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type RegisterGithubAppResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['RegisterGithubAppResult'] = ResolversParentTypes['RegisterGithubAppResult']> = {
githubAppClientId?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type CreateAppDokkuResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['CreateAppDokkuResult'] = ResolversParentTypes['CreateAppDokkuResult']> = {
appId?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type CreateAppGithubResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['CreateAppGithubResult'] = ResolversParentTypes['CreateAppGithubResult']> = {
result?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type DestroyAppResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['DestroyAppResult'] = ResolversParentTypes['DestroyAppResult']> = {
result?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type RestartAppResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['RestartAppResult'] = ResolversParentTypes['RestartAppResult']> = {
result?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type RebuildAppResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['RebuildAppResult'] = ResolversParentTypes['RebuildAppResult']> = {
result?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type DestroyDatabaseResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['DestroyDatabaseResult'] = ResolversParentTypes['DestroyDatabaseResult']> = {
result?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type LinkDatabaseResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['LinkDatabaseResult'] = ResolversParentTypes['LinkDatabaseResult']> = {
result?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type UnlinkDatabaseResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['UnlinkDatabaseResult'] = ResolversParentTypes['UnlinkDatabaseResult']> = {
result?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type DokkuPluginResolvers<ContextType = any, ParentType extends ResolversParentTypes['DokkuPlugin'] = ResolversParentTypes['DokkuPlugin']> = {
name?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
version?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type DokkuPluginResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['DokkuPluginResult'] = ResolversParentTypes['DokkuPluginResult']> = {
version?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
plugins?: Resolver<Array<ResolversTypes['DokkuPlugin']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type SetEnvVarResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['SetEnvVarResult'] = ResolversParentTypes['SetEnvVarResult']> = {
result?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type UnsetEnvVarResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['UnsetEnvVarResult'] = ResolversParentTypes['UnsetEnvVarResult']> = {
result?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type CreateDatabaseResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['CreateDatabaseResult'] = ResolversParentTypes['CreateDatabaseResult']> = {
result?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type AppLogsResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['AppLogsResult'] = ResolversParentTypes['AppLogsResult']> = {
logs?: Resolver<Array<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type DatabaseInfoResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['DatabaseInfoResult'] = ResolversParentTypes['DatabaseInfoResult']> = {
info?: Resolver<Array<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type DatabaseLogsResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['DatabaseLogsResult'] = ResolversParentTypes['DatabaseLogsResult']> = {
logs?: Resolver<Array<Maybe<ResolversTypes['String']>>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type IsDatabaseLinkedResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['IsDatabaseLinkedResult'] = ResolversParentTypes['IsDatabaseLinkedResult']> = {
isLinked?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type EnvVarResolvers<ContextType = any, ParentType extends ResolversParentTypes['EnvVar'] = ResolversParentTypes['EnvVar']> = {
key?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
value?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type EnvVarsResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['EnvVarsResult'] = ResolversParentTypes['EnvVarsResult']> = {
envVars?: Resolver<Array<ResolversTypes['EnvVar']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type SetDomainResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['SetDomainResult'] = ResolversParentTypes['SetDomainResult']> = {
result?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type AddDomainResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['AddDomainResult'] = ResolversParentTypes['AddDomainResult']> = {
result?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type RemoveDomainResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['RemoveDomainResult'] = ResolversParentTypes['RemoveDomainResult']> = {
result?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type SetupResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['SetupResult'] = ResolversParentTypes['SetupResult']> = {
canConnectSsh?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
sshPublicKey?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
isGithubAppSetup?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
githubAppManifest?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type IsPluginInstalledResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['IsPluginInstalledResult'] = ResolversParentTypes['IsPluginInstalledResult']> = {
isPluginInstalled?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type AppProxyPortResolvers<ContextType = any, ParentType extends ResolversParentTypes['AppProxyPort'] = ResolversParentTypes['AppProxyPort']> = {
scheme?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
host?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
container?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type QueryResolvers<ContextType = any, ParentType extends ResolversParentTypes['Query'] = ResolversParentTypes['Query']> = {
githubInstallationId?: Resolver<ResolversTypes['GithubAppInstallationId'], ParentType, ContextType>;
setup?: Resolver<ResolversTypes['SetupResult'], ParentType, ContextType>;
apps?: Resolver<Array<ResolversTypes['App']>, ParentType, ContextType>;
user?: Resolver<ResolversTypes['User'], ParentType, ContextType>;
repositories?: Resolver<Array<ResolversTypes['Repository']>, ParentType, ContextType, RequireFields<QueryRepositoriesArgs, 'installationId'>>;
branches?: Resolver<Array<ResolversTypes['Branch']>, ParentType, ContextType, RequireFields<QueryBranchesArgs, 'repositoryName' | 'installationId'>>;
appMetaGithub?: Resolver<Maybe<ResolversTypes['AppMetaGithub']>, ParentType, ContextType, RequireFields<QueryAppMetaGithubArgs, 'appId'>>;
app?: Resolver<Maybe<ResolversTypes['App']>, ParentType, ContextType, RequireFields<QueryAppArgs, 'appId'>>;
domains?: Resolver<ResolversTypes['Domains'], ParentType, ContextType, RequireFields<QueryDomainsArgs, 'appId'>>;
database?: Resolver<Maybe<ResolversTypes['Database']>, ParentType, ContextType, RequireFields<QueryDatabaseArgs, 'databaseId'>>;
databases?: Resolver<Array<ResolversTypes['Database']>, ParentType, ContextType>;
isPluginInstalled?: Resolver<ResolversTypes['IsPluginInstalledResult'], ParentType, ContextType, RequireFields<QueryIsPluginInstalledArgs, 'pluginName'>>;
dokkuPlugins?: Resolver<ResolversTypes['DokkuPluginResult'], ParentType, ContextType>;
appLogs?: Resolver<ResolversTypes['AppLogsResult'], ParentType, ContextType, RequireFields<QueryAppLogsArgs, 'appId'>>;
databaseInfo?: Resolver<ResolversTypes['DatabaseInfoResult'], ParentType, ContextType, RequireFields<QueryDatabaseInfoArgs, 'databaseId'>>;
databaseLogs?: Resolver<ResolversTypes['DatabaseLogsResult'], ParentType, ContextType, RequireFields<QueryDatabaseLogsArgs, 'databaseId'>>;
isDatabaseLinked?: Resolver<ResolversTypes['IsDatabaseLinkedResult'], ParentType, ContextType, RequireFields<QueryIsDatabaseLinkedArgs, 'databaseId' | 'appId'>>;
envVars?: Resolver<ResolversTypes['EnvVarsResult'], ParentType, ContextType, RequireFields<QueryEnvVarsArgs, 'appId'>>;
appProxyPorts?: Resolver<Array<ResolversTypes['AppProxyPort']>, ParentType, ContextType, RequireFields<QueryAppProxyPortsArgs, 'appId'>>;
};
export type SubscriptionResolvers<ContextType = any, ParentType extends ResolversParentTypes['Subscription'] = ResolversParentTypes['Subscription']> = {
unlinkDatabaseLogs?: SubscriptionResolver<ResolversTypes['RealTimeLog'], "unlinkDatabaseLogs", ParentType, ContextType>;
linkDatabaseLogs?: SubscriptionResolver<ResolversTypes['RealTimeLog'], "linkDatabaseLogs", ParentType, ContextType>;
createDatabaseLogs?: SubscriptionResolver<ResolversTypes['RealTimeLog'], "createDatabaseLogs", ParentType, ContextType>;
appRestartLogs?: SubscriptionResolver<ResolversTypes['RealTimeLog'], "appRestartLogs", ParentType, ContextType>;
appRebuildLogs?: SubscriptionResolver<ResolversTypes['RealTimeLog'], "appRebuildLogs", ParentType, ContextType>;
appCreateLogs?: SubscriptionResolver<ResolversTypes['RealTimeLog'], "appCreateLogs", ParentType, ContextType>;
};
export type MutationResolvers<ContextType = any, ParentType extends ResolversParentTypes['Mutation'] = ResolversParentTypes['Mutation']> = {
loginWithGithub?: Resolver<Maybe<ResolversTypes['LoginResult']>, ParentType, ContextType, RequireFields<MutationLoginWithGithubArgs, 'code'>>;
registerGithubApp?: Resolver<Maybe<ResolversTypes['RegisterGithubAppResult']>, ParentType, ContextType, RequireFields<MutationRegisterGithubAppArgs, 'code'>>;
addDomain?: Resolver<ResolversTypes['AddDomainResult'], ParentType, ContextType, RequireFields<MutationAddDomainArgs, 'input'>>;
removeDomain?: Resolver<ResolversTypes['RemoveDomainResult'], ParentType, ContextType, RequireFields<MutationRemoveDomainArgs, 'input'>>;
setDomain?: Resolver<ResolversTypes['SetDomainResult'], ParentType, ContextType, RequireFields<MutationSetDomainArgs, 'input'>>;
createAppDokku?: Resolver<ResolversTypes['CreateAppDokkuResult'], ParentType, ContextType, RequireFields<MutationCreateAppDokkuArgs, 'input'>>;
createDatabase?: Resolver<ResolversTypes['CreateDatabaseResult'], ParentType, ContextType, RequireFields<MutationCreateDatabaseArgs, 'input'>>;
setEnvVar?: Resolver<ResolversTypes['SetEnvVarResult'], ParentType, ContextType, RequireFields<MutationSetEnvVarArgs, 'input'>>;
unsetEnvVar?: Resolver<ResolversTypes['UnsetEnvVarResult'], ParentType, ContextType, RequireFields<MutationUnsetEnvVarArgs, 'input'>>;
destroyApp?: Resolver<ResolversTypes['DestroyAppResult'], ParentType, ContextType, RequireFields<MutationDestroyAppArgs, 'input'>>;
restartApp?: Resolver<ResolversTypes['RestartAppResult'], ParentType, ContextType, RequireFields<MutationRestartAppArgs, 'input'>>;
rebuildApp?: Resolver<ResolversTypes['RebuildAppResult'], ParentType, ContextType, RequireFields<MutationRebuildAppArgs, 'input'>>;
destroyDatabase?: Resolver<ResolversTypes['DestroyDatabaseResult'], ParentType, ContextType, RequireFields<MutationDestroyDatabaseArgs, 'input'>>;
linkDatabase?: Resolver<ResolversTypes['LinkDatabaseResult'], ParentType, ContextType, RequireFields<MutationLinkDatabaseArgs, 'input'>>;
unlinkDatabase?: Resolver<ResolversTypes['UnlinkDatabaseResult'], ParentType, ContextType, RequireFields<MutationUnlinkDatabaseArgs, 'input'>>;
addAppProxyPort?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType, RequireFields<MutationAddAppProxyPortArgs, 'input'>>;
removeAppProxyPort?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType, RequireFields<MutationRemoveAppProxyPortArgs, 'input'>>;
createAppGithub?: Resolver<ResolversTypes['CreateAppGithubResult'], ParentType, ContextType, RequireFields<MutationCreateAppGithubArgs, 'input'>>;
};
export interface UploadScalarConfig extends GraphQLScalarTypeConfig<ResolversTypes['Upload'], any> {
name: 'Upload';
}
export type Resolvers<ContextType = any> = {
DateTime?: GraphQLScalarType;
App?: AppResolvers<ContextType>;
User?: UserResolvers<ContextType>;
GithubAppInstallationId?: GithubAppInstallationIdResolvers<ContextType>;
AppMetaGithub?: AppMetaGithubResolvers<ContextType>;
Repository?: RepositoryResolvers<ContextType>;
Branch?: BranchResolvers<ContextType>;
AppBuild?: AppBuildResolvers<ContextType>;
Database?: DatabaseResolvers<ContextType>;
Domains?: DomainsResolvers<ContextType>;
RealTimeLog?: RealTimeLogResolvers<ContextType>;
LoginResult?: LoginResultResolvers<ContextType>;
RegisterGithubAppResult?: RegisterGithubAppResultResolvers<ContextType>;
CreateAppDokkuResult?: CreateAppDokkuResultResolvers<ContextType>;
CreateAppGithubResult?: CreateAppGithubResultResolvers<ContextType>;
DestroyAppResult?: DestroyAppResultResolvers<ContextType>;
RestartAppResult?: RestartAppResultResolvers<ContextType>;
RebuildAppResult?: RebuildAppResultResolvers<ContextType>;
DestroyDatabaseResult?: DestroyDatabaseResultResolvers<ContextType>;
LinkDatabaseResult?: LinkDatabaseResultResolvers<ContextType>;
UnlinkDatabaseResult?: UnlinkDatabaseResultResolvers<ContextType>;
DokkuPlugin?: DokkuPluginResolvers<ContextType>;
DokkuPluginResult?: DokkuPluginResultResolvers<ContextType>;
SetEnvVarResult?: SetEnvVarResultResolvers<ContextType>;
UnsetEnvVarResult?: UnsetEnvVarResultResolvers<ContextType>;
CreateDatabaseResult?: CreateDatabaseResultResolvers<ContextType>;
AppLogsResult?: AppLogsResultResolvers<ContextType>;
DatabaseInfoResult?: DatabaseInfoResultResolvers<ContextType>;
DatabaseLogsResult?: DatabaseLogsResultResolvers<ContextType>;
IsDatabaseLinkedResult?: IsDatabaseLinkedResultResolvers<ContextType>;
EnvVar?: EnvVarResolvers<ContextType>;
EnvVarsResult?: EnvVarsResultResolvers<ContextType>;
SetDomainResult?: SetDomainResultResolvers<ContextType>;
AddDomainResult?: AddDomainResultResolvers<ContextType>;
RemoveDomainResult?: RemoveDomainResultResolvers<ContextType>;
SetupResult?: SetupResultResolvers<ContextType>;
IsPluginInstalledResult?: IsPluginInstalledResultResolvers<ContextType>;
AppProxyPort?: AppProxyPortResolvers<ContextType>;
Query?: QueryResolvers<ContextType>;
Subscription?: SubscriptionResolvers<ContextType>;
Mutation?: MutationResolvers<ContextType>;
Upload?: GraphQLScalarType;
};
/**
* @deprecated
* Use "Resolvers" root object instead. If you wish to get "IResolvers", add "typesPrefix: I" to your config.
*/
export type IResolvers<ContextType = any> = Resolvers<ContextType>;
export type DirectiveResolvers<ContextType = any> = {
cacheControl?: CacheControlDirectiveResolver<any, any, ContextType>;
};
/**
* @deprecated
* Use "DirectiveResolvers" root object instead. If you wish to get "IDirectiveResolvers", add "typesPrefix: I" to your config.
*/
export type IDirectiveResolvers<ContextType = any> = DirectiveResolvers<ContextType>; | the_stack |
import { describe, it } from "@jest/globals";
import { EOL } from "os";
import { createStubLogger, expectEqualWrites } from "../../../adapters/logger.stubs";
import { createEmptyConfigConversionResults } from "../configConversionResults.stubs";
import { ESLintRuleOptions } from "../rules/types";
import { reportConfigConversionResults } from "./reportConfigConversionResults";
const basicExtends = ["prettier"];
describe("reportConfigConversionResults", () => {
it("logs a successful conversion without notices when there is one converted rule without notices", async () => {
// Arrange
const logger = createStubLogger();
const conversionResults = createEmptyConfigConversionResults({
converted: new Map<string, ESLintRuleOptions>([
[
`tslint-rule-one`,
{
ruleArguments: ["a", "b"],
ruleName: "tslint-rule-one",
ruleSeverity: "error",
},
],
]),
extends: basicExtends,
});
// Act
await reportConfigConversionResults({ logger }, ".eslintrc.js", conversionResults);
// Assert
expectEqualWrites(logger.stdout.write, `✨ 1 rule replaced with its ESLint equivalent. ✨`);
});
it("logs a successful conversion with notices when there is one converted rule with notices", async () => {
// Arrange
const logger = createStubLogger();
const conversionResults = createEmptyConfigConversionResults({
converted: new Map<string, ESLintRuleOptions>([
[
`tslint-rule-one`,
{
notices: ["1", "2"],
ruleArguments: ["a", "b"],
ruleName: "tslint-rule-one",
ruleSeverity: "error",
},
],
]),
extends: basicExtends,
});
// Act
await reportConfigConversionResults({ logger }, ".eslintrc.js", conversionResults);
// Assert
expectEqualWrites(
logger.stdout.write,
`✨ 1 rule replaced with its ESLint equivalent. ✨${EOL}`,
`❗ 1 ESLint rule behaves differently from its TSLint counterpart ❗`,
` Check ${logger.debugFileName} for details.`,
);
expectEqualWrites(
logger.info.write,
`1 ESLint rule behaves differently from its TSLint counterpart:`,
` * tslint-rule-one:`,
` - 1`,
` - 2`,
);
});
it("logs successful conversions when there are multiple converted rules", async () => {
// Arrange
const logger = createStubLogger();
const conversionResults = createEmptyConfigConversionResults({
converted: new Map<string, ESLintRuleOptions>([
[
`tslint-rule-one`,
{
notices: ["1", "2"],
ruleArguments: ["a", "b"],
ruleName: "tslint-rule-one",
ruleSeverity: "error",
},
],
[
`tslint-rule-two`,
{
notices: ["3", "4"],
ruleArguments: ["c", "d"],
ruleName: "tslint-rule-two",
ruleSeverity: "warn",
},
],
]),
extends: basicExtends,
});
// Act
await reportConfigConversionResults({ logger }, ".eslintrc.js", conversionResults);
// Assert
expectEqualWrites(
logger.stdout.write,
`✨ 2 rules replaced with their ESLint equivalents. ✨`,
``,
`❗ 2 ESLint rules behave differently from their TSLint counterparts ❗`,
` Check ${logger.debugFileName} for details.`,
);
expectEqualWrites(
logger.info.write,
`2 ESLint rules behave differently from their TSLint counterparts:`,
` * tslint-rule-one:`,
` - 1`,
` - 2`,
` * tslint-rule-two:`,
` - 3`,
` - 4`,
);
});
it("logs a failed conversion when there is one failed conversion", async () => {
// Arrange
const logger = createStubLogger();
const conversionResults = createEmptyConfigConversionResults({
failed: [{ getSummary: () => "It broke." }],
extends: basicExtends,
});
// Act
await reportConfigConversionResults({ logger }, ".eslintrc.js", conversionResults);
// Assert
expectEqualWrites(
logger.stderr.write,
`❌ 1 error thrown. ❌`,
` Check ${logger.debugFileName} for details.`,
);
});
it("logs failed conversions when there are multiple failed conversions", async () => {
// Arrange
const logger = createStubLogger();
const conversionResults = createEmptyConfigConversionResults({
extends: basicExtends,
failed: [{ getSummary: () => "It broke." }, { getSummary: () => "It really broke." }],
});
// Act
await reportConfigConversionResults({ logger }, ".eslintrc.js", conversionResults);
// Assert
expectEqualWrites(
logger.stderr.write,
`❌ 2 errors thrown. ❌`,
` Check ${logger.debugFileName} for details.`,
);
});
it("logs a missing rule when there is a missing rule", async () => {
// Arrange
const logger = createStubLogger();
const conversionResults = createEmptyConfigConversionResults({
extends: basicExtends,
missing: [
{
ruleArguments: ["a", "b"],
ruleName: "tslint-rule-one",
ruleSeverity: "error",
},
],
});
// Act
await reportConfigConversionResults({ logger }, ".eslintrc.js", conversionResults);
// Assert
expectEqualWrites(
logger.stdout.write,
`❓ 1 rule is not known by tslint-to-eslint-config to have an ESLint equivalent. ❓`,
` The "@typescript-eslint/tslint/config" section of .eslintrc.js configures eslint-plugin-tslint to run it in TSLint within ESLint.`,
` Check ${logger.debugFileName} for details.`,
);
expectEqualWrites(
logger.info.write,
`1 rule is not known by tslint-to-eslint-config to have an ESLint equivalent:`,
' * tslint-to-eslint-config does not know the ESLint equivalent for TSLint\'s "tslint-rule-one".',
);
});
it("logs missing rules when there are missing rules", async () => {
// Arrange
const logger = createStubLogger();
const conversionResults = createEmptyConfigConversionResults({
extends: basicExtends,
missing: [
{
ruleArguments: ["a", "b"],
ruleName: "tslint-rule-one",
ruleSeverity: "error",
},
{
ruleArguments: ["c", "d"],
ruleName: "tslint-rule-two",
ruleSeverity: "warning",
},
],
});
// Act
await reportConfigConversionResults({ logger }, ".eslintrc.js", conversionResults);
// Assert
expectEqualWrites(
logger.stdout.write,
`❓ 2 rules are not known by tslint-to-eslint-config to have ESLint equivalents. ❓`,
` The "@typescript-eslint/tslint/config" section of .eslintrc.js configures eslint-plugin-tslint to run them in TSLint within ESLint.`,
` Check ${logger.debugFileName} for details.`,
);
expectEqualWrites(
logger.info.write,
`2 rules are not known by tslint-to-eslint-config to have ESLint equivalents:`,
' * tslint-to-eslint-config does not know the ESLint equivalent for TSLint\'s "tslint-rule-one".',
' * tslint-to-eslint-config does not know the ESLint equivalent for TSLint\'s "tslint-rule-two".',
);
});
it("logs obsolete conversions when there is one obsolete conversion", async () => {
// Arrange
const logger = createStubLogger();
const conversionResults = createEmptyConfigConversionResults({
extends: basicExtends,
obsolete: new Set(["obsolete"]),
});
// Act
await reportConfigConversionResults({ logger }, ".eslintrc.js", conversionResults);
// Assert
expectEqualWrites(
logger.stdout.write,
`🦖 1 rule is obsolete and does not have an ESLint equivalent. 🦖`,
` Check ${logger.debugFileName} for details.`,
);
});
it("logs obsolete conversions when there are multiple obsolete conversions", async () => {
// Arrange
const logger = createStubLogger();
const conversionResults = createEmptyConfigConversionResults({
extends: basicExtends,
obsolete: new Set(["obsolete-a", "obsolete-b"]),
});
// Act
await reportConfigConversionResults({ logger }, ".eslintrc.js", conversionResults);
// Assert
expectEqualWrites(
logger.stdout.write,
`🦖 2 rules are obsolete and do not have ESLint equivalents. 🦖`,
` Check ${logger.debugFileName} for details.`,
);
});
it("logs a Prettier recommendation when extends doesn't include eslint-config-prettier", async () => {
// Arrange
const logger = createStubLogger();
const conversionResults = createEmptyConfigConversionResults({
extends: [],
});
// Act
await reportConfigConversionResults({ logger }, ".eslintrc.js", conversionResults);
// Assert
expectEqualWrites(
logger.stdout.write,
`☠ Prettier plugins are missing from your configuration. ☠`,
` We highly recommend running tslint-to-eslint-config --prettier to disable formatting ESLint rules.`,
` See https://github.com/typescript-eslint/tslint-to-eslint-config/blob/master/docs/FAQs.md#should-i-use-prettier.`,
);
});
}); | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as Models from "../models";
import * as Mappers from "../models/backupPoliciesMappers";
import * as Parameters from "../models/parameters";
import { AzureNetAppFilesManagementClientContext } from "../azureNetAppFilesManagementClientContext";
/** Class representing a BackupPolicies. */
export class BackupPolicies {
private readonly client: AzureNetAppFilesManagementClientContext;
/**
* Create a BackupPolicies.
* @param {AzureNetAppFilesManagementClientContext} client Reference to the service client.
*/
constructor(client: AzureNetAppFilesManagementClientContext) {
this.client = client;
}
/**
* List backup policies for Netapp Account
* @summary List backup policies
* @param resourceGroupName The name of the resource group.
* @param accountName The name of the NetApp account
* @param [options] The optional parameters
* @returns Promise<Models.BackupPoliciesListResponse>
*/
list(resourceGroupName: string, accountName: string, options?: msRest.RequestOptionsBase): Promise<Models.BackupPoliciesListResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param accountName The name of the NetApp account
* @param callback The callback
*/
list(resourceGroupName: string, accountName: string, callback: msRest.ServiceCallback<Models.BackupPoliciesList>): void;
/**
* @param resourceGroupName The name of the resource group.
* @param accountName The name of the NetApp account
* @param options The optional parameters
* @param callback The callback
*/
list(resourceGroupName: string, accountName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BackupPoliciesList>): void;
list(resourceGroupName: string, accountName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BackupPoliciesList>, callback?: msRest.ServiceCallback<Models.BackupPoliciesList>): Promise<Models.BackupPoliciesListResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
accountName,
options
},
listOperationSpec,
callback) as Promise<Models.BackupPoliciesListResponse>;
}
/**
* Get a particular backup Policy
* @summary Get a backup Policy
* @param resourceGroupName The name of the resource group.
* @param accountName The name of the NetApp account
* @param backupPolicyName Backup policy Name which uniquely identify backup policy.
* @param [options] The optional parameters
* @returns Promise<Models.BackupPoliciesGetResponse>
*/
get(resourceGroupName: string, accountName: string, backupPolicyName: string, options?: msRest.RequestOptionsBase): Promise<Models.BackupPoliciesGetResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param accountName The name of the NetApp account
* @param backupPolicyName Backup policy Name which uniquely identify backup policy.
* @param callback The callback
*/
get(resourceGroupName: string, accountName: string, backupPolicyName: string, callback: msRest.ServiceCallback<Models.BackupPolicy>): void;
/**
* @param resourceGroupName The name of the resource group.
* @param accountName The name of the NetApp account
* @param backupPolicyName Backup policy Name which uniquely identify backup policy.
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, accountName: string, backupPolicyName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BackupPolicy>): void;
get(resourceGroupName: string, accountName: string, backupPolicyName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BackupPolicy>, callback?: msRest.ServiceCallback<Models.BackupPolicy>): Promise<Models.BackupPoliciesGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
accountName,
backupPolicyName,
options
},
getOperationSpec,
callback) as Promise<Models.BackupPoliciesGetResponse>;
}
/**
* Create a backup policy for Netapp Account
* @summary Create a backup policy
* @param resourceGroupName The name of the resource group.
* @param accountName The name of the NetApp account
* @param backupPolicyName Backup policy Name which uniquely identify backup policy.
* @param body Backup policy object supplied in the body of the operation.
* @param [options] The optional parameters
* @returns Promise<Models.BackupPoliciesCreateResponse>
*/
create(resourceGroupName: string, accountName: string, backupPolicyName: string, body: Models.BackupPolicy, options?: msRest.RequestOptionsBase): Promise<Models.BackupPoliciesCreateResponse> {
return this.beginCreate(resourceGroupName,accountName,backupPolicyName,body,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.BackupPoliciesCreateResponse>;
}
/**
* Patch a backup policy for Netapp Account
* @summary Patch a backup policy
* @param resourceGroupName The name of the resource group.
* @param accountName The name of the NetApp account
* @param backupPolicyName Backup policy Name which uniquely identify backup policy.
* @param body Backup policy object supplied in the body of the operation.
* @param [options] The optional parameters
* @returns Promise<Models.BackupPoliciesUpdateResponse>
*/
update(resourceGroupName: string, accountName: string, backupPolicyName: string, body: Models.BackupPolicyPatch, options?: msRest.RequestOptionsBase): Promise<Models.BackupPoliciesUpdateResponse> {
return this.beginUpdate(resourceGroupName,accountName,backupPolicyName,body,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.BackupPoliciesUpdateResponse>;
}
/**
* Delete backup policy
* @summary Delete a backup policy
* @param resourceGroupName The name of the resource group.
* @param accountName The name of the NetApp account
* @param backupPolicyName Backup policy Name which uniquely identify backup policy.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(resourceGroupName: string, accountName: string, backupPolicyName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> {
return this.beginDeleteMethod(resourceGroupName,accountName,backupPolicyName,options)
.then(lroPoller => lroPoller.pollUntilFinished());
}
/**
* Create a backup policy for Netapp Account
* @summary Create a backup policy
* @param resourceGroupName The name of the resource group.
* @param accountName The name of the NetApp account
* @param backupPolicyName Backup policy Name which uniquely identify backup policy.
* @param body Backup policy object supplied in the body of the operation.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginCreate(resourceGroupName: string, accountName: string, backupPolicyName: string, body: Models.BackupPolicy, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
accountName,
backupPolicyName,
body,
options
},
beginCreateOperationSpec,
options);
}
/**
* Patch a backup policy for Netapp Account
* @summary Patch a backup policy
* @param resourceGroupName The name of the resource group.
* @param accountName The name of the NetApp account
* @param backupPolicyName Backup policy Name which uniquely identify backup policy.
* @param body Backup policy object supplied in the body of the operation.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginUpdate(resourceGroupName: string, accountName: string, backupPolicyName: string, body: Models.BackupPolicyPatch, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
accountName,
backupPolicyName,
body,
options
},
beginUpdateOperationSpec,
options);
}
/**
* Delete backup policy
* @summary Delete a backup policy
* @param resourceGroupName The name of the resource group.
* @param accountName The name of the NetApp account
* @param backupPolicyName Backup policy Name which uniquely identify backup policy.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginDeleteMethod(resourceGroupName: string, accountName: string, backupPolicyName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
accountName,
backupPolicyName,
options
},
beginDeleteMethodOperationSpec,
options);
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/backupPolicies",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.BackupPoliciesList
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/backupPolicies/{backupPolicyName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName,
Parameters.backupPolicyName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.BackupPolicy
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginCreateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/backupPolicies/{backupPolicyName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName,
Parameters.backupPolicyName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "body",
mapper: {
...Mappers.BackupPolicy,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.BackupPolicy
},
201: {
bodyMapper: Mappers.BackupPolicy
},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/backupPolicies/{backupPolicyName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName,
Parameters.backupPolicyName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "body",
mapper: {
...Mappers.BackupPolicyPatch,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.BackupPolicy
},
202: {
bodyMapper: Mappers.BackupPolicy
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginDeleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/backupPolicies/{backupPolicyName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName,
Parameters.backupPolicyName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
202: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
}; | the_stack |
import {Constants} from "../../scripts/constants";
import {Point, RegionSelector} from "../../scripts/clipperUI/regionSelector";
import {Status} from "../../scripts/clipperUI/status";
import {DomUtils} from "../../scripts/domParsers/domUtils";
import {MithrilUtils} from "../mithrilUtils";
import {MockProps} from "../mockProps";
import {TestModule} from "../testModule";
import {DataUrls} from "./regionSelector_tests_dataUrls";
export class RegionSelectorTests extends TestModule {
private defaultComponent;
protected module() {
return "regionSelector";
}
protected beforeEach() {
let mockClipperState = MockProps.getMockClipperState();
this.defaultComponent = <RegionSelector
clipperState={mockClipperState} />;
}
protected tests() {
test("The innerFrame's dimensions should match corners p1 (top left) and p2 (bottom right)", () => {
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let point1: Point = { x: 50, y: 60 };
let point2: Point = { x: 75, y: 100 };
MithrilUtils.simulateAction(() => {
controllerInstance.state.firstPoint = point1;
controllerInstance.state.secondPoint = point2;
});
ok(document.getElementById(Constants.Ids.outerFrame),
"The outer frame should be rendered");
let innerFrame = document.getElementById(Constants.Ids.innerFrame);
ok(innerFrame, "The inner frame should be rendered");
strictEqual(controllerInstance.refs.innerFrame.style.left, point1.x - 1 + "px",
"The left style of the inner frame should be the minimum of x1 and x2 minus 1");
strictEqual(controllerInstance.refs.innerFrame.style.top, point1.y - 1 + "px",
"The top style of the inner frame should be the minimum of y1 and y2 minus 1");
strictEqual(controllerInstance.refs.innerFrame.style.width, point2.x - point1.x + "px",
"The width style of the inner frame should be xMax - xMin");
strictEqual(controllerInstance.refs.innerFrame.style.height, point2.y - point1.y + "px",
"The height style of the inner frame should be yMax - yMin");
});
test("The innerFrame's dimensions should match corners p1 (bottom left) and p2 (top right)", () => {
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let point1: Point = { x: 50, y: 60 };
let point2: Point = { x: 75, y: 30 };
MithrilUtils.simulateAction(() => {
controllerInstance.state.firstPoint = point1;
controllerInstance.state.secondPoint = point2;
});
ok(document.getElementById(Constants.Ids.outerFrame),
"The outer frame should be rendered");
let innerFrame = document.getElementById(Constants.Ids.innerFrame);
ok(innerFrame, "The inner frame should be rendered");
strictEqual(controllerInstance.refs.innerFrame.style.left, point1.x - 1 + "px",
"The left style of the inner frame should be the minimum of x1 and x2 minus 1");
strictEqual(controllerInstance.refs.innerFrame.style.top, point2.y - 1 + "px",
"The top style of the inner frame should be the minimum of y1 and y2 minus 1");
strictEqual(controllerInstance.refs.innerFrame.style.width, point2.x - point1.x + "px",
"The width style of the inner frame should be xMax - xMin");
strictEqual(controllerInstance.refs.innerFrame.style.height, point1.y - point2.y + "px",
"The height style of the inner frame should be yMax - yMin");
});
test("The innerFrame's dimensions should match corners p1 (top right) and p2 (bottom left)", () => {
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let point1: Point = { x: 50, y: 60 };
let point2: Point = { x: 20, y: 100 };
MithrilUtils.simulateAction(() => {
controllerInstance.state.firstPoint = point1;
controllerInstance.state.secondPoint = point2;
});
ok(document.getElementById(Constants.Ids.outerFrame),
"The outer frame should be rendered");
let innerFrame = document.getElementById(Constants.Ids.innerFrame);
ok(innerFrame, "The inner frame should be rendered");
strictEqual(controllerInstance.refs.innerFrame.style.left, point2.x - 1 + "px",
"The left style of the inner frame should be the minimum of x1 and x2 minus 1");
strictEqual(controllerInstance.refs.innerFrame.style.top, point1.y - 1 + "px",
"The top style of the inner frame should be the minimum of y1 and y2 minus 1");
strictEqual(controllerInstance.refs.innerFrame.style.width, point1.x - point2.x + "px",
"The width style of the inner frame should be xMax - xMin");
strictEqual(controllerInstance.refs.innerFrame.style.height, point2.y - point1.y + "px",
"The height style of the inner frame should be yMax - yMin");
});
test("The innerFrame's dimensions should match corners p1 (bottom right) and p2 (top left)", () => {
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let point1: Point = { x: 50, y: 60 };
let point2: Point = { x: 10, y: 10 };
MithrilUtils.simulateAction(() => {
controllerInstance.state.firstPoint = point1;
controllerInstance.state.secondPoint = point2;
});
ok(document.getElementById(Constants.Ids.outerFrame),
"The outer frame should be rendered");
let innerFrame = document.getElementById(Constants.Ids.innerFrame);
ok(innerFrame, "The inner frame should be rendered");
strictEqual(controllerInstance.refs.innerFrame.style.left, point2.x - 1 + "px",
"The left style of the inner frame should be the minimum of x1 and x2 minus 1");
strictEqual(controllerInstance.refs.innerFrame.style.top, point2.y - 1 + "px",
"The top style of the inner frame should be the minimum of y1 and y2 minus 1");
strictEqual(controllerInstance.refs.innerFrame.style.width, point1.x - point2.x + "px",
"The width style of the inner frame should be xMax - xMin");
strictEqual(controllerInstance.refs.innerFrame.style.height, point1.y - point2.y + "px",
"The height style of the inner frame should be yMax - yMin");
});
test("The innerFrame's left and top values should be allowed to go negative if xMin and yMin are 0", () => {
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let point1: Point = { x: 0, y: 0 };
let point2: Point = { x: 75, y: 100 };
MithrilUtils.simulateAction(() => {
controllerInstance.state.firstPoint = point1;
controllerInstance.state.secondPoint = point2;
});
ok(document.getElementById(Constants.Ids.outerFrame),
"The outer frame should be rendered");
let innerFrame = document.getElementById(Constants.Ids.innerFrame);
ok(innerFrame, "The inner frame should be rendered");
strictEqual(controllerInstance.refs.innerFrame.style.left, point1.x - 1 + "px",
"The left style of the inner frame should be the minimum of x1 and x2 minus 1");
strictEqual(controllerInstance.refs.innerFrame.style.top, point1.y - 1 + "px",
"The top style of the inner frame should be the minimum of y1 and y2 minus 1");
strictEqual(controllerInstance.refs.innerFrame.style.width, point2.x - point1.x + "px",
"The width style of the inner frame should be xMax - xMin");
strictEqual(controllerInstance.refs.innerFrame.style.height, point2.y - point1.y + "px",
"The height style of the inner frame should be yMax - yMin");
});
test("The innerFrame should not exist if no points have been registered, and the outerFrame should", () => {
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
ok(document.getElementById(Constants.Ids.outerFrame),
"The outer frame should be rendered");
ok(!document.getElementById(Constants.Ids.innerFrame),
"The inner frame should not be rendered");
});
test("The innerFrame should not exist if only the first point has been registered, and the outerFrame should", () => {
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
MithrilUtils.simulateAction(() => {
controllerInstance.state.firstPoint = { x: 50, y: 50 };
});
ok(document.getElementById(Constants.Ids.outerFrame),
"The outer frame should be rendered");
ok(!document.getElementById(Constants.Ids.innerFrame),
"The inner frame should not be rendered");
});
test("The outerFrame should be the size of the window", () => {
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
ok(document.getElementById(Constants.Ids.outerFrame),
"The outer frame should be rendered");
// In the tests, window is set to have non-zero innerWidth and innerHeight by default
strictEqual(controllerInstance.refs.outerFrame.width, window.innerWidth,
"The outerFrame's width is the window's innerWidth");
strictEqual(controllerInstance.refs.outerFrame.height, window.innerHeight,
"The outerFrame's height is the window's innerHeight");
});
test("The outerFrame should not paint over the space occupied by the innerFrame", () => {
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let point1: Point = { x: 50, y: 60 };
let point2: Point = { x: 53, y: 63 };
MithrilUtils.simulateAction(() => {
controllerInstance.state.firstPoint = point1;
controllerInstance.state.secondPoint = point2;
});
ok(document.getElementById(Constants.Ids.outerFrame),
"The outer frame should be rendered");
let context = controllerInstance.refs.outerFrame.getContext("2d");
let imageDataOfInnerFrame = context.getImageData(point1.x, point1.y, point2.x - point1.x, point2.y - point1.y);
// Every 4th value in the image data list refers to the pixel's alpha (opacity) value
for (let i = 3; i < imageDataOfInnerFrame.data.length; i += 4) {
strictEqual(imageDataOfInnerFrame.data[i], 0,
"Every pixel that is located in the innerFrame's area should have an alpha of 0");
}
});
test("The outerFrame should paint over the space not occupied by the innerFrame", () => {
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let point1: Point = { x: 45, y: 20 };
let point2: Point = { x: 47, y: 23 };
MithrilUtils.simulateAction(() => {
controllerInstance.state.firstPoint = point1;
controllerInstance.state.secondPoint = point2;
});
ok(document.getElementById(Constants.Ids.outerFrame),
"The outer frame should be rendered");
// We won't check every pixel in the window (for perf), just a small area outside the innerFrame's area ...
let context = controllerInstance.refs.outerFrame.getContext("2d");
let thickness = 3;
// Top innerFrame edge
let area = context.getImageData(
point1.x - thickness, point1.y - thickness,
point2.x - point1.x + (thickness * 2), thickness);
this.assertAreaIsBlack(area.data);
// Left innerFrame edge
area = context.getImageData(
point1.x - thickness, point1.y,
thickness, point2.y - point1.y);
this.assertAreaIsBlack(area.data);
// Right innerFrame edge
area = context.getImageData(
point2.x, point1.y,
thickness, point2.y - point1.y);
this.assertAreaIsBlack(area.data);
// Bottom innerFrame edge
area = context.getImageData(
point1.x - thickness, point2.y,
point2.x - point1.x + (thickness * 2), thickness);
this.assertAreaIsBlack(area.data);
// ... and the corners of the window
// Top left window corner
area = context.getImageData(
0, 0,
1, 1);
this.assertAreaIsBlack(area.data);
// Top right window corner
area = context.getImageData(
window.innerWidth - 1, 0,
1, 1);
this.assertAreaIsBlack(area.data);
// Bottom left window corner
area = context.getImageData(
0, window.innerHeight - 1,
1, 1);
this.assertAreaIsBlack(area.data);
// Bottom right window corner
area = context.getImageData(
window.innerWidth - 1, window.innerHeight - 1,
1, 1);
this.assertAreaIsBlack(area.data);
});
test("The winWidth and winHeight states should be equal to the window's innerWidth and innerHeight by default", () => {
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
strictEqual(controllerInstance.state.winWidth, window.innerWidth,
"The winHeight state should equal window.innerWidth");
strictEqual(controllerInstance.state.winHeight, window.innerHeight,
"The winHeight state should equal window.innerHeight");
});
test("The state's firstPoint and secondPoint should update accordingly after a drag event", () => {
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let from: Point = { x: 100, y: 100 };
let to: Point = { x: 200, y: 200 };
let regionSelectorContainer = $("#" + Constants.Ids.regionSelectorContainer);
regionSelectorContainer.trigger({ type: "mousedown", pageX: from.x, pageY: from.y } as JQueryEventObject);
regionSelectorContainer.trigger({ type: "mousemove", pageX: to.x, pageY: to.y } as JQueryEventObject);
regionSelectorContainer.trigger({ type: "mouseup", pageX: to.x, pageY: to.y } as JQueryEventObject);
deepEqual(controllerInstance.state.firstPoint, { x: from.x, y: from.y },
"The first point should be the same point as the mousedown point");
deepEqual(controllerInstance.state.secondPoint, { x: to.x, y: to.y },
"The second point should be the same point as the mouseup point");
});
test("The state's firstPoint and secondPoint should be undefined if the drag distance is zero", () => {
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let point: Point = { x: 100, y: 100 };
let regionSelectorContainer = $("#" + Constants.Ids.regionSelectorContainer);
regionSelectorContainer.trigger({ type: "mousedown", pageX: point.x, pageY: point.y } as JQueryEventObject);
regionSelectorContainer.trigger({ type: "mousemove", pageX: point.x, pageY: point.y } as JQueryEventObject);
regionSelectorContainer.trigger({ type: "mouseup", pageX: point.x, pageY: point.y } as JQueryEventObject);
ok(!controllerInstance.state.firstPoint, "The first point should be undefined");
ok(!controllerInstance.state.secondPoint, "The second point should be undefined");
});
test("The state's firstPoint and secondPoint should be undefined if the horizontal drag distance is zero", () => {
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let from: Point = { x: 100, y: 100 };
let to: Point = { x: 100, y: 200 };
let regionSelectorContainer = $("#" + Constants.Ids.regionSelectorContainer);
regionSelectorContainer.trigger({ type: "mousedown", pageX: from.x, pageY: from.y } as JQueryEventObject);
regionSelectorContainer.trigger({ type: "mousemove", pageX: to.x, pageY: to.y } as JQueryEventObject);
regionSelectorContainer.trigger({ type: "mouseup", pageX: to.x, pageY: to.y } as JQueryEventObject);
ok(!controllerInstance.state.firstPoint, "The first point should be undefined");
ok(!controllerInstance.state.secondPoint, "The second point should be undefined");
});
test("The state's firstPoint and secondPoint should be undefined if the vertical drag distance is zero", () => {
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let from: Point = { x: 100, y: 100 };
let to: Point = { x: 200, y: 100 };
let regionSelectorContainer = $("#" + Constants.Ids.regionSelectorContainer);
regionSelectorContainer.trigger({ type: "mousedown", pageX: from.x, pageY: from.y } as JQueryEventObject);
regionSelectorContainer.trigger({ type: "mousemove", pageX: to.x, pageY: to.y } as JQueryEventObject);
regionSelectorContainer.trigger({ type: "mouseup", pageX: to.x, pageY: to.y } as JQueryEventObject);
ok(!controllerInstance.state.firstPoint, "The first point should be undefined");
ok(!controllerInstance.state.secondPoint, "The second point should be undefined");
});
test("The state's secondPoint should be updated in the middle of the drag (i.e., before mouseup)", () => {
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let from: Point = { x: 100, y: 100 };
let to: Point = { x: 200, y: 200 };
let regionSelectorContainer = $("#" + Constants.Ids.regionSelectorContainer);
regionSelectorContainer.trigger({ type: "mousedown", pageX: from.x, pageY: from.y } as JQueryEventObject);
regionSelectorContainer.trigger({ type: "mousemove", pageX: to.x, pageY: to.y } as JQueryEventObject);
deepEqual(controllerInstance.state.firstPoint, { x: from.x, y: from.y },
"The first point should be the same point as the mousedown point");
deepEqual(controllerInstance.state.secondPoint, { x: to.x, y: to.y },
"The second point should be the same point as the mouseup point");
});
test("For a single white pixel as the region selection, its quality should not be downgraded", (assert: QUnitAssert) => {
let done = assert.async();
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let img = new Image();
let canvas = document.createElement("canvas") as HTMLCanvasElement;
img.onload = () => {
canvas.getContext("2d").drawImage(img, 0, 0);
let expectedUrl = canvas.toDataURL("image/png");
let actualUrl = controllerInstance.getCompressedDataUrl(canvas);
strictEqual(actualUrl, expectedUrl, "For such a tiny image, the quality should not be downgraded");
ok(actualUrl.length <= DomUtils.maxBytesForMediaTypes,
"The resulting image should not exceed maxBytesForMediaTypes");
done();
};
img.src = DataUrls.whitePixelUrl;
});
test("For a large image as the region selection, the resulting image should be downgraded sufficiently to not exceed maxBytesForMediaTypes", (assert: QUnitAssert) => {
let done = assert.async();
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let img = new Image();
let canvas = document.createElement("canvas") as HTMLCanvasElement;
img.onload = () => {
canvas.getContext("2d").drawImage(img, 0, 0);
let actualUrl = controllerInstance.getCompressedDataUrl(canvas);
ok(actualUrl, "The resulting data url should be non-empty, non-null, and non-undefined");
ok(actualUrl.length <= DomUtils.maxBytesForMediaTypes,
"The resulting image should not exceed maxBytesForMediaTypes");
done();
};
img.src = DataUrls.bigImgUrl;
});
test("When the region selection is turned into a canvas, the canvas width and height should be the absolute distance between (x1,x2) and (y1,y2) respectively", (assert: QUnitAssert) => {
let done = assert.async();
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let point1: Point = { x: 50, y: 75 };
let point2: Point = { x: 51, y: 76 };
MithrilUtils.simulateAction(() => {
controllerInstance.state.firstPoint = point1;
controllerInstance.state.secondPoint = point2;
});
controllerInstance.createSelectionAsCanvas(DataUrls.tabDataUrl).then((canvas: HTMLCanvasElement) => {
ok(canvas, "The canvas should be non-undefined");
strictEqual(canvas.width, Math.abs(point1.x - point2.x), "Width should be the absolute of x1 - x2");
strictEqual(canvas.height, Math.abs(point1.y - point2.y), "Height should be the absolute of y1 - y2");
done();
});
});
test("When the region selection is turned into a canvas, the canvas width and height should be correct when the base image is large", (assert: QUnitAssert) => {
let done = assert.async();
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let point1: Point = { x: 50, y: 75 };
let point2: Point = { x: 200, y: 400 };
MithrilUtils.simulateAction(() => {
controllerInstance.state.firstPoint = point1;
controllerInstance.state.secondPoint = point2;
});
controllerInstance.createSelectionAsCanvas(DataUrls.tabDataUrl).then((canvas: HTMLCanvasElement) => {
ok(canvas, "The canvas should be non-undefined");
strictEqual(canvas.width, Math.abs(point1.x - point2.x), "Width should be the absolute of x1 - x2");
strictEqual(canvas.height, Math.abs(point1.y - point2.y), "Height should be the absolute of y1 - y2");
done();
});
});
test("When the region selection is turned into a canvas, the canvas width and height should be correct when p1 > p2", (assert: QUnitAssert) => {
let done = assert.async();
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let point1: Point = { x: 400, y: 200 };
let point2: Point = { x: 200, y: 100 };
MithrilUtils.simulateAction(() => {
controllerInstance.state.firstPoint = point1;
controllerInstance.state.secondPoint = point2;
});
controllerInstance.createSelectionAsCanvas(DataUrls.tabDataUrl).then((canvas: HTMLCanvasElement) => {
ok(canvas, "The canvas should be non-undefined");
strictEqual(canvas.width, Math.abs(point1.x - point2.x), "Width should be the absolute of x1 - x2");
strictEqual(canvas.height, Math.abs(point1.y - point2.y), "Height should be the absolute of y1 - y2");
done();
});
});
test("When the region selection is turned into a canvas, the canvas width and height should be correct when p1 is northeast of p2", (assert: QUnitAssert) => {
let done = assert.async();
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let point1: Point = { x: 400, y: 100 };
let point2: Point = { x: 200, y: 200 };
MithrilUtils.simulateAction(() => {
controllerInstance.state.firstPoint = point1;
controllerInstance.state.secondPoint = point2;
});
controllerInstance.createSelectionAsCanvas(DataUrls.tabDataUrl).then((canvas: HTMLCanvasElement) => {
ok(canvas, "The canvas should be non-undefined");
strictEqual(canvas.width, Math.abs(point1.x - point2.x), "Width should be the absolute of x1 - x2");
strictEqual(canvas.height, Math.abs(point1.y - point2.y), "Height should be the absolute of y1 - y2");
done();
});
});
test("Given the base image is a white transparent background with 2x2 black on the top left, check that the canvas captures it", (assert: QUnitAssert) => {
let done = assert.async();
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let point1: Point = { x: 0, y: 0 };
let point2: Point = { x: 3, y: 3 };
MithrilUtils.simulateAction(() => {
controllerInstance.state.firstPoint = point1;
controllerInstance.state.secondPoint = point2;
});
controllerInstance.createSelectionAsCanvas(DataUrls.twoByTwoUpperCornerBlackOnTransparentUrl).then((canvas: HTMLCanvasElement) => {
ok(canvas, "The canvas should be non-undefined");
let context = canvas.getContext("2d");
// Top left 2x2 pixels
let area = context.getImageData(
0, 0,
2, 2);
this.assertAreaIsBlack(area.data);
// The 1 pixel border around the black area
let bottom = context.getImageData(
0, 2,
3, 1).data;
for (let i = 0; i < bottom.length; i++) {
strictEqual(bottom[i], 255,
"Every pixel that is not located in the canvas's area should be rgba(255, 255, 255, 255)");
}
let right = context.getImageData(
2, 0,
1, 2).data;
for (let i = 0; i < right.length; i++) {
strictEqual(right[i], 255,
"Every pixel that is not located in the canvas's area should be rgba(255, 255, 255, 255)");
}
done();
});
});
test("createSelectionAsCanvas should call reject if the base image url is empty", (assert: QUnitAssert) => {
let done = assert.async();
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let point1: Point = { x: 0, y: 0 };
let point2: Point = { x: 3, y: 3 };
MithrilUtils.simulateAction(() => {
controllerInstance.state.firstPoint = point1;
controllerInstance.state.secondPoint = point2;
});
controllerInstance.createSelectionAsCanvas("").then((canvas: HTMLCanvasElement) => {
ok(false, "The promise should not be resolved");
}, (error: Error) => {
ok(true, "The promise should be rejected");
}).then(() => {
done();
});
});
test("createSelectionAsCanvas should call reject if the base image url is null", (assert: QUnitAssert) => {
/* tslint:disable:no-null-keyword */
let done = assert.async();
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let point1: Point = { x: 0, y: 0 };
let point2: Point = { x: 3, y: 3 };
MithrilUtils.simulateAction(() => {
controllerInstance.state.firstPoint = point1;
controllerInstance.state.secondPoint = point2;
});
controllerInstance.createSelectionAsCanvas(null).then((canvas: HTMLCanvasElement) => {
ok(false, "The promise should not be resolved");
}, (error: Error) => {
ok(true, "The promise should be rejected");
}).then(() => {
done();
});
/* tslint:enable:no-null-keyword */
});
test("createSelectionAsCanvas should call reject if the base image url is undefined", (assert: QUnitAssert) => {
let done = assert.async();
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let point1: Point = { x: 0, y: 0 };
let point2: Point = { x: 3, y: 3 };
MithrilUtils.simulateAction(() => {
controllerInstance.state.firstPoint = point1;
controllerInstance.state.secondPoint = point2;
});
controllerInstance.createSelectionAsCanvas(undefined).then((canvas: HTMLCanvasElement) => {
ok(false, "The promise should not be resolved");
}, (error: Error) => {
ok(true, "The promise should be rejected");
}).then(() => {
done();
});
});
test("createSelectionAsCanvas should call reject if the first point is undefined", (assert: QUnitAssert) => {
let done = assert.async();
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let point2: Point = { x: 3, y: 3 };
MithrilUtils.simulateAction(() => {
controllerInstance.state.secondPoint2 = point2;
});
controllerInstance.createSelectionAsCanvas(DataUrls.twoByTwoUpperCornerBlackOnTransparentUrl).then((canvas: HTMLCanvasElement) => {
ok(false, "The promise should not be resolved");
}, (error: Error) => {
ok(true, "The promise should be rejected");
}).then(() => {
done();
});
});
test("createSelectionAsCanvas should call reject if the second point is undefined", (assert: QUnitAssert) => {
let done = assert.async();
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let point1: Point = { x: 0, y: 0 };
MithrilUtils.simulateAction(() => {
controllerInstance.state.firstPoint = point1;
});
controllerInstance.createSelectionAsCanvas(DataUrls.twoByTwoUpperCornerBlackOnTransparentUrl).then((canvas: HTMLCanvasElement) => {
ok(false, "The promise should not be resolved");
}, (error: Error) => {
ok(true, "The promise should be rejected");
}).then(() => {
done();
});
});
test("createSelectionAsCanvas should call reject if both points are undefined", (assert: QUnitAssert) => {
let done = assert.async();
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
controllerInstance.createSelectionAsCanvas(DataUrls.twoByTwoUpperCornerBlackOnTransparentUrl).then((canvas: HTMLCanvasElement) => {
ok(false, "The promise should not be resolved");
}, (error: Error) => {
ok(true, "The promise should be rejected");
}).then(() => {
done();
});
});
test("saveCompressedSelectionToState should resolve with the canvas in the general case", (assert: QUnitAssert) => {
let done = assert.async();
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let point1: Point = { x: 0, y: 0 };
let point2: Point = { x: 3, y: 3 };
MithrilUtils.simulateAction(() => {
controllerInstance.state.firstPoint = point1;
controllerInstance.state.secondPoint = point2;
});
controllerInstance.saveCompressedSelectionToState(DataUrls.twoByTwoUpperCornerBlackOnTransparentUrl).then((canvas: HTMLCanvasElement) => {
ok(canvas, "The canvas should be non-undefined");
strictEqual(canvas.width, Math.abs(point1.x - point2.x), "Width should be the absolute of x1 - x2");
strictEqual(canvas.height, Math.abs(point1.y - point2.y), "Height should be the absolute of y1 - y2");
done();
});
});
test("saveCompressedSelectionToState should set the regionResult state to success in the general case", (assert: QUnitAssert) => {
let done = assert.async();
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let point1: Point = { x: 0, y: 0 };
let point2: Point = { x: 3, y: 3 };
MithrilUtils.simulateAction(() => {
controllerInstance.state.firstPoint = point1;
controllerInstance.state.secondPoint = point2;
});
controllerInstance.saveCompressedSelectionToState(DataUrls.twoByTwoUpperCornerBlackOnTransparentUrl).then((canvas: HTMLCanvasElement) => {
strictEqual(controllerInstance.props.clipperState.regionResult.status, Status.Succeeded, "The regionResult state should indicate it succeeded");
ok(controllerInstance.props.clipperState.regionResult.data, "The regionResult array should not be undefined");
strictEqual(controllerInstance.props.clipperState.regionResult.data.length, 1, "The regionResult array should contain one element");
ok(controllerInstance.props.clipperState.regionResult.data[0], "The regionResult's new element should be a non-empty string");
done();
});
});
test("saveCompressedSelectionToState should append the result on subsequent calls", (assert: QUnitAssert) => {
let done = assert.async();
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let point1: Point = { x: 0, y: 0 };
let point2: Point = { x: 3, y: 3 };
MithrilUtils.simulateAction(() => {
controllerInstance.state.firstPoint = point1;
controllerInstance.state.secondPoint = point2;
});
controllerInstance.saveCompressedSelectionToState(DataUrls.twoByTwoUpperCornerBlackOnTransparentUrl).then((canvas: HTMLCanvasElement) => {
strictEqual(controllerInstance.props.clipperState.regionResult.status, Status.Succeeded, "The regionResult state should indicate it succeeded");
ok(controllerInstance.props.clipperState.regionResult.data, "The regionResult array should not be undefined");
strictEqual(controllerInstance.props.clipperState.regionResult.data.length, 1, "The regionResult array should contain one element");
ok(controllerInstance.props.clipperState.regionResult.data[0], "The regionResult's new element should be a non-empty string");
let firstData = controllerInstance.props.clipperState.regionResult.data[0];
point1 = { x: 1, y: 1 };
point2 = { x: 2, y: 2 };
MithrilUtils.simulateAction(() => {
controllerInstance.state.firstPoint = point1;
controllerInstance.state.secondPoint = point2;
});
controllerInstance.saveCompressedSelectionToState(DataUrls.twoByTwoUpperCornerBlackOnTransparentUrl).then((canvas2: HTMLCanvasElement) => {
strictEqual(controllerInstance.props.clipperState.regionResult.status, Status.Succeeded, "The regionResult state should indicate it succeeded");
ok(controllerInstance.props.clipperState.regionResult.data, "The regionResult array should not be undefined");
strictEqual(controllerInstance.props.clipperState.regionResult.data.length, 2, "The regionResult array should contain one element");
ok(controllerInstance.props.clipperState.regionResult.data[1], "The regionResult's new element should be a non-empty string");
strictEqual(controllerInstance.props.clipperState.regionResult.data[0], firstData, "The first result should not be modified");
notStrictEqual(controllerInstance.props.clipperState.regionResult.data[1], firstData, "Since new points were selected, the second result should not equal the first");
done();
});
});
});
test("saveCompressedSelectionToState should unset the user's selection in the reject case", (assert: QUnitAssert) => {
let done = assert.async();
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
controllerInstance.saveCompressedSelectionToState(undefined).then((canvas: HTMLCanvasElement) => {
ok(false, "The promise should not be resolved");
}, (error: Error) => {
strictEqual(controllerInstance.state.firstPoint, undefined, "The first point should be undefined");
strictEqual(controllerInstance.state.secondPoint, undefined, "The first point should be undefined");
ok(!controllerInstance.state.selectionInProgress, "The selection should not be indicated as in progress");
strictEqual(controllerInstance.props.clipperState.regionResult.status, Status.NotStarted, "The regionResult state should indicate it has not started");
ok(!controllerInstance.props.clipperState.regionResult.data, "There shouldn't be any regionResult data");
}).then(() => {
done();
});
});
test("The captured content should display the inner frame", (assert: QUnitAssert) => {
let done = assert.async();
let controllerInstance = MithrilUtils.mountToFixture(this.defaultComponent);
let innerFrame = document.getElementById(Constants.Ids.innerFrame) as HTMLDivElement;
ok(!innerFrame, "The inner frame shouldn't exist when there are no points");
let point1: Point = { x: 0, y: 0 };
let point2: Point = { x: 3, y: 3 };
MithrilUtils.simulateAction(() => {
controllerInstance.state.firstPoint = point1;
controllerInstance.state.secondPoint = point2;
});
innerFrame = document.getElementById(Constants.Ids.innerFrame) as HTMLDivElement;
ok(innerFrame, "The inner frame should exist when there are 2 points");
controllerInstance.saveCompressedSelectionToState(DataUrls.twoByTwoUpperCornerBlackOnTransparentUrl).then((canvas: HTMLCanvasElement) => {
// Let a redraw occur
MithrilUtils.simulateAction(() => {});
innerFrame = document.getElementById(Constants.Ids.innerFrame) as HTMLDivElement;
ok(innerFrame, "The inner frame should exist when we've taken the screenshot");
done();
});
});
}
private assertAreaIsBlack(pixelValueList: Uint8ClampedArray) {
for (let i = 0; i < pixelValueList.length; i++) {
strictEqual(pixelValueList[i], i % 4 === 3 ? 255 : 0,
"Every pixel that is not located in the innerFrame's area should be rgba(0, 0, 0, 255)");
}
}
}
(new RegionSelectorTests()).runTests(); | the_stack |
import os from 'os';
import { resolve } from 'path';
import { Octokit } from '@octokit/rest';
import del = require('del');
import nock from 'nock';
import { getOptions } from '../../options/options';
import { runSequentially } from '../../runSequentially';
import { getCommits } from '../../ui/getCommits';
import { listenForCallsToNockScope } from '../nockHelpers';
import { getDevAccessToken } from '../private/getDevAccessToken';
jest.unmock('make-dir');
jest.unmock('del');
jest.setTimeout(10000);
const INTEGRATION_TEST_DATA_PATH = resolve(
'./src/test/integration/mock-environment'
);
const HOMEDIR_PATH = resolve('./src/test/integration/mock-environment/homedir');
const REPO_OWNER = 'backport-org';
const REPO_NAME = 'integration-test';
const BRANCH_NAME = 'backport/7.x/commit-5bf29b7d';
const USERNAME = 'sqren';
describe('integration', () => {
afterAll(() => {
nock.cleanAll();
});
beforeAll(() => {
// set alternative homedir
jest.spyOn(os, 'homedir').mockReturnValue(HOMEDIR_PATH);
});
describe('when a single commit is backported', () => {
let res: Awaited<ReturnType<typeof runSequentially>>;
let accessToken: string;
let createPullRequestsMockCalls: unknown[];
beforeAll(async () => {
accessToken = await getDevAccessToken();
await resetState(accessToken);
createPullRequestsMockCalls = mockCreatePullRequest({
number: 1337,
html_url: 'myHtmlUrl',
});
const options = await getOptions([], {
githubApiBaseUrlV3: 'https://api.foo.com',
ci: true,
sha: '5bf29b7d847ea3dbde9280448f0f62ad0f22d3ad',
username: USERNAME,
accessToken,
upstream: 'backport-org/integration-test',
});
const commits = await getCommits(options);
const targetBranches: string[] = ['7.x'];
res = await runSequentially({ options, commits, targetBranches });
});
it('returns pull request', () => {
expect(res).toEqual([
{
didUpdate: false,
pullRequestUrl: 'myHtmlUrl',
pullRequestNumber: 1337,
status: 'success',
targetBranch: '7.x',
},
]);
});
it('sends the correct http body when creating pull request', () => {
expect(createPullRequestsMockCalls).toMatchInlineSnapshot(`
Array [
Object {
"base": "7.x",
"body": "This is an automatic backport of commit 5bf29b7d847ea3dbde9280448f0f62ad0f22d3ad to 7.x.
Please refer to the [Backport tool documentation](https://github.com/sqren/backport) for additional information",
"head": "sqren:backport/7.x/commit-5bf29b7d",
"title": "[7.x] Add ❤️ emoji",
},
]
`);
});
it('should not create new branches in origin (backport-org/integration-test)', async () => {
const branches = await getBranches({
accessToken,
repoOwner: REPO_OWNER,
repoName: REPO_NAME,
});
expect(branches.map((b) => b.name)).toEqual(['7.x', 'master']);
});
it('should create branch in the fork (sqren/integration-test)', async () => {
const branches = await getBranches({
accessToken,
repoOwner: USERNAME,
repoName: REPO_NAME,
});
expect(branches.map((b) => b.name)).toEqual([
'7.x',
BRANCH_NAME,
'master',
]);
});
it('should have cherry picked the correct commit', async () => {
const branches = await getBranches({
accessToken,
repoOwner: USERNAME,
repoName: REPO_NAME,
});
const sha = branches.find((branch) => branch.name === '7.x')?.commit.sha;
expect(sha).toEqual('b68e4fcaaf4427fe1e902c718b3bb3f07b560fb5');
});
});
// describe.skip('when two commits are backported', () => {
// let createPullRequestsMockCalls: unknown[];
// let res: Awaited<ReturnType<typeof runSequentially>>;
// let accessToken: string;
// beforeAll(async () => {
// accessToken = await getDevAccessToken();
// await resetState(accessToken);
// createPullRequestsMockCalls = mockCreatePullRequest({
// number: 1337,
// html_url: 'myHtmlUrl',
// });
// const options = {
// githubApiBaseUrlV3: 'https://api.foo.com',
// ci: true,
// sha: '5bf29b7d847ea3dbde9280448f0f62ad0f22d3ad',
// username: USERNAME,
// accessToken,
// upstream: 'backport-org/integration-test',
// } as ValidConfigOptions;
// const commits = await getCommits(options);
// const targetBranches: string[] = ['7.x'];
// res = await runSequentially({ options, commits, targetBranches });
// });
// it('sends the correct http body when creating pull request', () => {
// expect(createPullRequestsMockCalls).toMatchInlineSnapshot();
// });
// it('returns pull request', () => {
// expect(res).toEqual([
// { pullRequestUrl: 'myHtmlUrl', success: true, targetBranch: '6.0' },
// ]);
// });
// it('should not create new branches in origin (backport-org/integration-test)', async () => {
// const branches = await getBranches({
// accessToken,
// repoOwner: REPO_OWNER,
// repoName: REPO_NAME,
// });
// expect(branches.map((b) => b.name)).toEqual(['7.x', '* master']);
// });
// it('should create branch in the fork (sqren/integration-test)', async () => {
// const branches = await getBranches({
// accessToken,
// repoOwner: USERNAME,
// repoName: REPO_NAME,
// });
// expect(branches.map((b) => b.name)).toEqual([
// '7.x',
// 'backport/6.0/pr-85_commit-2e63475c',
// 'master',
// ]);
// });
// it('should have cherry picked the correct commit', async () => {
// const branches = await getBranches({
// accessToken,
// repoOwner: USERNAME,
// repoName: REPO_NAME,
// });
// const sha = branches.find((branch) => branch.name === '7.x')?.commit.sha;
// expect(sha).toEqual('foo');
// });
// });
describe('when disabling fork mode', () => {
let res: Awaited<ReturnType<typeof runSequentially>>;
let accessToken: string;
let createPullRequestsMockCalls: unknown[];
beforeAll(async () => {
accessToken = await getDevAccessToken();
await resetState(accessToken);
createPullRequestsMockCalls = mockCreatePullRequest({
number: 1337,
html_url: 'myHtmlUrl',
});
const options = await getOptions([], {
githubApiBaseUrlV3: 'https://api.foo.com',
ci: true,
sha: '5bf29b7d847ea3dbde9280448f0f62ad0f22d3ad',
username: USERNAME,
accessToken,
upstream: 'backport-org/integration-test',
fork: false,
});
const commits = await getCommits(options);
const targetBranches: string[] = ['7.x'];
res = await runSequentially({ options, commits, targetBranches });
});
it('sends the correct http body when creating pull request', () => {
expect(createPullRequestsMockCalls).toMatchInlineSnapshot(`
Array [
Object {
"base": "7.x",
"body": "This is an automatic backport of commit 5bf29b7d847ea3dbde9280448f0f62ad0f22d3ad to 7.x.
Please refer to the [Backport tool documentation](https://github.com/sqren/backport) for additional information",
"head": "backport-org:backport/7.x/commit-5bf29b7d",
"title": "[7.x] Add ❤️ emoji",
},
]
`);
});
it('returns pull request', () => {
expect(res).toEqual([
{
didUpdate: false,
pullRequestNumber: 1337,
pullRequestUrl: 'myHtmlUrl',
status: 'success',
targetBranch: '7.x',
},
]);
});
it('should create new branches in origin (backport-org/integration-test)', async () => {
const branches = await getBranches({
accessToken,
repoOwner: REPO_OWNER,
repoName: REPO_NAME,
});
expect(branches.map((b) => b.name)).toEqual([
'7.x',
BRANCH_NAME,
'master',
]);
});
it('should NOT create branch in the fork (sqren/integration-test)', async () => {
const branches = await getBranches({
accessToken,
repoOwner: USERNAME,
repoName: REPO_NAME,
});
expect(branches.map((b) => b.name)).toEqual(['7.x', 'master']);
});
it('should cherry pick the correct commit', async () => {
const branches = await getBranches({
accessToken,
repoOwner: REPO_OWNER,
repoName: REPO_NAME,
});
const sha = branches.find((branch) => branch.name === '7.x')?.commit.sha;
expect(sha).toEqual('b68e4fcaaf4427fe1e902c718b3bb3f07b560fb5');
});
});
});
function mockCreatePullRequest(response: { number: number; html_url: string }) {
const scope = nock('https://api.foo.com', { allowUnmocked: true })
.post('/repos/backport-org/integration-test/pulls')
.reply(200, response);
return listenForCallsToNockScope(scope);
}
async function getBranches({
accessToken,
repoOwner,
repoName,
}: {
accessToken: string;
repoOwner: string;
repoName: string;
}) {
// console.log(`fetch branches for ${repoOwner}`);
const octokit = new Octokit({
auth: accessToken,
});
const res = await octokit.repos.listBranches({
owner: repoOwner,
repo: repoName,
});
return res.data;
}
async function deleteBranch({
accessToken,
repoOwner,
repoName,
branchName,
}: {
accessToken: string;
repoOwner: string;
repoName: string;
branchName: string;
}) {
try {
const octokit = new Octokit({
auth: accessToken,
});
// console.log({ accessToken });
const opts = {
owner: repoOwner,
repo: repoName,
ref: `heads/${branchName}`,
};
const res = await octokit.git.deleteRef(opts);
// console.log(`Deleted ${repoOwner}:heads/${branchName}`);
return res.data;
} catch (e) {
// console.log(
// `Could not delete ${repoOwner}:heads/${branchName} (${e.message})`
// );
if (e.message === 'Reference does not exist') {
return;
}
throw e;
}
}
async function resetState(accessToken: string) {
await deleteBranch({
accessToken,
repoOwner: REPO_OWNER,
repoName: REPO_NAME,
branchName: BRANCH_NAME,
});
await deleteBranch({
accessToken,
repoOwner: USERNAME,
repoName: REPO_NAME,
branchName: BRANCH_NAME,
});
await del(INTEGRATION_TEST_DATA_PATH);
} | the_stack |
import * as R from 'ramda';
import { sendToLagoonLogs } from '@lagoon/commons/dist/logs';
import {
createDeployTask,
createMiscTask,
createPromoteTask
} from '@lagoon/commons/dist/tasks';
import { ResolverFn } from '../';
import {
pubSub,
createEnvironmentFilteredSubscriber
} from '../../clients/pubSub';
import { getConfigFromEnv, getLagoonRouteFromEnv } from '../../util/config';
import { knex, query, isPatchEmpty } from '../../util/db';
import { Sql } from './sql';
import { Helpers } from './helpers';
import { EVENTS } from './events';
import { Helpers as environmentHelpers } from '../environment/helpers';
import { Helpers as projectHelpers } from '../project/helpers';
import { addTask } from '@lagoon/commons/dist/api';
import { Sql as environmentSql } from '../environment/sql';
import S3 from 'aws-sdk/clients/s3';
import sha1 from 'sha1';
const accessKeyId = process.env.S3_FILES_ACCESS_KEY_ID || 'minio'
const secretAccessKey = process.env.S3_FILES_SECRET_ACCESS_KEY || 'minio123'
const bucket = process.env.S3_FILES_BUCKET || 'lagoon-files'
const region = process.env.S3_FILES_REGION
const s3Origin = process.env.S3_FILES_HOST || 'http://docker.for.mac.localhost:9000'
const config = {
origin: s3Origin,
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
region: region,
bucket: bucket
};
const s3Client = new S3({
endpoint: config.origin,
accessKeyId: config.accessKeyId,
secretAccessKey: config.secretAccessKey,
region: config.region,
params: {
Bucket: config.bucket
},
s3ForcePathStyle: true,
signatureVersion: 'v4'
});
const convertDateFormat = R.init;
export const getBuildLog: ResolverFn = async (
{ remoteId, environment, name, status },
_args,
{ sqlClientPool }
) => {
if (!remoteId) {
return null;
}
const environmentData = await environmentHelpers(
sqlClientPool
).getEnvironmentById(parseInt(environment));
const projectData = await projectHelpers(sqlClientPool).getProjectById(
environmentData.project
);
// we need to get the safename of the environment from when it was created
const makeSafe = string => string.toLocaleLowerCase().replace(/[^0-9a-z-]/g,'-')
var environmentName = makeSafe(environmentData.name)
var overlength = 58 - projectData.name.length;
if ( environmentName.length > overlength ) {
var hash = sha1(environmentName).substring(0,4)
environmentName = environmentName.substring(0, overlength-5)
environmentName = environmentName.concat('-' + hash)
}
try {
// where it should be, check `buildlogs/projectName/environmentName/buildName-remoteId.txt`
let buildLog = 'buildlogs/'+projectData.name+'/'+environmentName+'/'+name+'-'+remoteId+'.txt'
const data = await s3Client.getObject({Bucket: bucket, Key: buildLog}).promise();
if (!data) {
return null;
}
let logMsg = new Buffer(JSON.parse(JSON.stringify(data.Body)).data).toString('ascii');
return logMsg;
} catch (e) {
// there is no fallback location for build logs, so there is no log to show the user
return `There was an error loading the logs: ${e.message}\nIf this error persists, contact your Lagoon support team.`;
}
};
export const getDeploymentsByEnvironmentId: ResolverFn = async (
{ id: eid, environmentAuthz },
{ name, limit },
{ sqlClientPool, hasPermission }
) => {
const environment = await environmentHelpers(
sqlClientPool
).getEnvironmentById(eid);
if (!environmentAuthz) {
await hasPermission('deployment', 'view', {
project: environment.project
});
}
let queryBuilder = knex('deployment')
.where('environment', eid)
.orderBy('created', 'desc')
.orderBy('id', 'desc');
if (name) {
queryBuilder = queryBuilder.andWhere('name', name);
}
if (limit) {
queryBuilder = queryBuilder.limit(limit);
}
return query(sqlClientPool, queryBuilder.toString());
};
export const getDeploymentByRemoteId: ResolverFn = async (
_root,
{ id },
{ sqlClientPool, hasPermission }
) => {
const queryString = knex('deployment')
.where('remote_id', '=', id)
.toString();
const rows = await query(sqlClientPool, queryString);
const deployment = R.prop(0, rows);
if (!deployment) {
return null;
}
const perms = await query(
sqlClientPool,
Sql.selectPermsForDeployment(deployment.id)
);
await hasPermission('deployment', 'view', {
project: R.path(['0', 'pid'], perms)
});
return deployment;
};
export const getDeploymentUrl: ResolverFn = async (
{ id, environment },
_args,
{ sqlClientPool }
) => {
const lagoonUiRoute = getLagoonRouteFromEnv(
/\/ui-/,
getConfigFromEnv('UI_URL', 'http://localhost:8888')
);
const { name: project, openshiftProjectName } = await projectHelpers(
sqlClientPool
).getProjectByEnvironmentId(environment);
const deployment = await Helpers(sqlClientPool).getDeploymentById(id);
return `${lagoonUiRoute}/projects/${project}/${openshiftProjectName}/deployments/${deployment.name}`;
};
export const addDeployment: ResolverFn = async (
root,
{
input: {
id,
name,
status,
created,
started,
completed,
environment: environmentId,
remoteId
}
},
{ sqlClientPool, hasPermission, userActivityLogger }
) => {
const environment = await environmentHelpers(
sqlClientPool
).getEnvironmentById(environmentId);
await hasPermission('environment', `deploy:${environment.environmentType}`, {
project: environment.project
});
const { insertId } = await query(
sqlClientPool,
Sql.insertDeployment({
id,
name,
status,
created,
started,
completed,
environment: environmentId,
remoteId
})
);
const rows = await query(sqlClientPool, Sql.selectDeployment(insertId));
const deployment = R.prop(0, rows);
pubSub.publish(EVENTS.DEPLOYMENT.ADDED, deployment);
return deployment;
};
export const deleteDeployment: ResolverFn = async (
root,
{ input: { id } },
{ sqlClientPool, hasPermission, userActivityLogger }
) => {
const perms = await query(sqlClientPool, Sql.selectPermsForDeployment(id));
await hasPermission('deployment', 'delete', {
project: R.path(['0', 'pid'], perms)
});
await query(sqlClientPool, Sql.deleteDeployment(id));
userActivityLogger(`User deleted deployment '${id}'`, {
project: '',
event: 'api:deleteDeployment',
payload: {
deployment: id
}
});
return 'success';
};
export const updateDeployment: ResolverFn = async (
root,
{
input: {
id,
patch,
patch: {
name,
status,
created,
started,
completed,
environment,
remoteId
}
}
},
{ sqlClientPool, hasPermission, userActivityLogger }
) => {
if (isPatchEmpty({ patch })) {
throw new Error('Input patch requires at least 1 attribute');
}
const permsDeployment = await query(
sqlClientPool,
Sql.selectPermsForDeployment(id)
);
// Check access to modify deployment as it currently stands
await hasPermission('deployment', 'update', {
project: R.path(['0', 'pid'], permsDeployment)
});
if (environment) {
const permsEnv = await environmentHelpers(sqlClientPool).getEnvironmentById(
environment
);
// Check access to modify deployment as it will be updated
await hasPermission('environment', 'view', {
project: permsEnv.project
});
}
await query(
sqlClientPool,
Sql.updateDeployment({
id,
patch: {
name,
status,
created,
started,
completed,
environment,
remoteId
}
})
);
const rows = await query(sqlClientPool, Sql.selectDeployment(id));
const deployment = R.prop(0, rows);
pubSub.publish(EVENTS.DEPLOYMENT.UPDATED, deployment);
userActivityLogger(`User updated deployment '${id}'`, {
project: '',
event: 'api:updateDeployment',
payload: {
id,
deployment,
patch: {
name,
status,
created,
started,
completed,
environment,
remoteId
}
}
});
return deployment;
};
export const cancelDeployment: ResolverFn = async (
root,
{ input: { deployment: deploymentInput } },
{ sqlClientPool, hasPermission, userActivityLogger }
) => {
const deployment = await Helpers(
sqlClientPool
).getDeploymentByDeploymentInput(deploymentInput);
const environment = await environmentHelpers(
sqlClientPool
).getEnvironmentById(deployment.environment);
const project = await projectHelpers(sqlClientPool).getProjectById(
environment.project
);
await hasPermission('deployment', 'cancel', {
project: project.id
});
const data = {
build: deployment,
environment,
project
};
userActivityLogger(
`User cancelled deployment for '${deployment.environment}'`,
{
project: '',
event: 'api:cancelDeployment',
payload: {
deploymentInput,
data: data.build
}
}
);
try {
await createMiscTask({ key: 'build:cancel', data });
return 'success';
} catch (error) {
sendToLagoonLogs(
'error',
'',
'',
'api:cancelDeployment',
{ deploymentId: deployment.id },
`Deployment not cancelled, reason: ${error}`
);
return `Error: ${error.message}`;
}
};
export const deployEnvironmentLatest: ResolverFn = async (
root,
{ input: { environment: environmentInput } },
{ sqlClientPool, hasPermission, userActivityLogger }
) => {
const environments = await environmentHelpers(
sqlClientPool
).getEnvironmentsByEnvironmentInput(environmentInput);
const activeEnvironments = R.filter(
R.propEq('deleted', '0000-00-00 00:00:00'),
environments
);
if (activeEnvironments.length < 1 || activeEnvironments.length > 1) {
throw new Error('Unauthorized');
}
const environment = R.prop(0, activeEnvironments);
const project = await projectHelpers(sqlClientPool).getProjectById(
environment.project
);
await hasPermission('environment', `deploy:${environment.environmentType}`, {
project: project.id
});
if (project.deploymentsDisabled == 1){
throw new Error('Deployments have been disabled for this project');
}
if (
environment.deployType === 'branch' ||
environment.deployType === 'promote'
) {
if (!environment.deployBaseRef) {
throw new Error('Cannot deploy: deployBaseRef is empty');
}
} else if (environment.deployType === 'pullrequest') {
if (
!environment.deployBaseRef &&
!environment.deployHeadRef &&
!environment.deployTitle
) {
throw new Error(
'Cannot deploy: deployBaseRef, deployHeadRef or deployTitle is empty'
);
}
}
let deployData: {
[key: string]: any;
} = {
projectName: project.name,
type: environment.deployType
};
let meta: {
[key: string]: any;
} = {
projectName: project.name
};
let taskFunction;
switch (environment.deployType) {
case 'branch':
deployData = {
...deployData,
branchName: environment.deployBaseRef
};
meta = {
...meta,
branchName: deployData.branchName
};
taskFunction = createDeployTask;
break;
case 'pullrequest':
deployData = {
...deployData,
pullrequestTitle: environment.deployTitle,
pullrequestNumber: environment.name.replace('pr-', ''),
headBranchName: environment.deployHeadRef,
headSha: `origin/${environment.deployHeadRef}`,
baseBranchName: environment.deployBaseRef,
baseSha: `origin/${environment.deployBaseRef}`,
branchName: environment.name
};
meta = {
...meta,
pullrequestTitle: deployData.pullrequestTitle
};
taskFunction = createDeployTask;
break;
case 'promote':
deployData = {
...deployData,
branchName: environment.name,
promoteSourceEnvironment: environment.deployBaseRef
};
meta = {
...meta,
branchName: deployData.branchName,
promoteSourceEnvironment: deployData.promoteSourceEnvironment
};
taskFunction = createPromoteTask;
break;
default:
return `Error: Unknown deploy type ${environment.deployType}`;
}
userActivityLogger(
`User triggered a deployment on '${deployData.projectName}' for '${environment.name}'`,
{
project: deployData.projectName || '',
event: 'api:deployEnvironmentLatest',
payload: {
deployData
}
}
);
try {
await taskFunction(deployData);
sendToLagoonLogs(
'info',
deployData.projectName,
'',
'api:deployEnvironmentLatest',
meta,
`*[${deployData.projectName}]* Deployment triggered \`${environment.name}\``
);
return 'success';
} catch (error) {
switch (error.name) {
case 'NoNeedToDeployBranch':
sendToLagoonLogs(
'info',
deployData.projectName,
'',
'api:deployEnvironmentLatest',
meta,
`*[${deployData.projectName}]* Deployment skipped \`${environment.name}\`: ${error.message}`
);
return `Skipped: ${error.message}`;
default:
sendToLagoonLogs(
'error',
deployData.projectName,
'',
'api:deployEnvironmentLatest:error',
meta,
`*[${deployData.projectName}]* Error deploying \`${environment.name}\`: ${error.message}`
);
return `Error: ${error.message}`;
}
}
};
export const deployEnvironmentBranch: ResolverFn = async (
root,
{ input: { project: projectInput, branchName, branchRef } },
{ sqlClientPool, hasPermission, userActivityLogger }
) => {
const project = await projectHelpers(sqlClientPool).getProjectByProjectInput(
projectInput
);
const envType =
branchName === project.productionEnvironment ? 'production' : 'development';
await hasPermission('environment', `deploy:${envType}`, {
project: project.id
});
if (project.deploymentsDisabled == 1){
throw new Error('Deployments have been disabled for this project');
}
const deployData = {
type: 'branch',
projectName: project.name,
branchName,
sha: branchRef
};
const meta = {
projectName: project.name,
branchName: deployData.branchName
};
userActivityLogger(
`User triggered a deployment on '${deployData.projectName}' for '${deployData.branchName}'`,
{
project: deployData.projectName || '',
event: 'api:deployEnvironmentBranch',
payload: {
deployData
}
}
);
try {
await createDeployTask(deployData);
sendToLagoonLogs(
'info',
deployData.projectName,
'',
'api:deployEnvironmentBranch',
meta,
`*[${deployData.projectName}]* Deployment triggered \`${deployData.branchName}\``
);
return 'success';
} catch (error) {
switch (error.name) {
case 'NoNeedToDeployBranch':
sendToLagoonLogs(
'info',
deployData.projectName,
'',
'api:deployEnvironmentBranch',
meta,
`*[${deployData.projectName}]* Deployment skipped \`${deployData.branchName}\`: ${error.message}`
);
return `Skipped: ${error.message}`;
default:
sendToLagoonLogs(
'error',
deployData.projectName,
'',
'api:deployEnvironmentBranch:error',
meta,
`*[${deployData.projectName}]* Error deploying \`${deployData.branchName}\`: ${error}`
);
console.log(error);
return `Error: ${error}`;
}
}
};
export const deployEnvironmentPullrequest: ResolverFn = async (
root,
{
input: {
project: projectInput,
number,
title,
baseBranchName,
baseBranchRef,
headBranchName,
headBranchRef
}
},
{ sqlClientPool, hasPermission, userActivityLogger }
) => {
const branchName = `pr-${number}`;
const project = await projectHelpers(sqlClientPool).getProjectByProjectInput(
projectInput
);
const envType =
branchName === project.productionEnvironment ? 'production' : 'development';
await hasPermission('environment', `deploy:${envType}`, {
project: project.id
});
if (project.deploymentsDisabled == 1){
throw new Error('Deployments have been disabled for this project');
}
const deployData = {
type: 'pullrequest',
projectName: project.name,
pullrequestTitle: title,
pullrequestNumber: number,
headBranchName,
headSha: headBranchRef,
baseBranchName,
baseSha: baseBranchRef,
branchName
};
const meta = {
projectName: project.name,
pullrequestTitle: deployData.pullrequestTitle
};
userActivityLogger(
`User triggered a pull-request deployment on '${deployData.projectName}' for '${deployData.branchName}'`,
{
project: deployData.projectName || '',
event: 'api:deployEnvironmentPullrequest',
payload: {
deployData
}
}
);
try {
await createDeployTask(deployData);
sendToLagoonLogs(
'info',
deployData.projectName,
'',
'api:deployEnvironmentPullrequest',
meta,
`*[${deployData.projectName}]* Deployment triggered \`${deployData.branchName}\``
);
return 'success';
} catch (error) {
switch (error.name) {
case 'NoNeedToDeployBranch':
sendToLagoonLogs(
'info',
deployData.projectName,
'',
'api:deployEnvironmentPullrequest',
meta,
`*[${deployData.projectName}]* Deployment skipped \`${deployData.branchName}\`: ${error.message}`
);
return `Skipped: ${error.message}`;
default:
sendToLagoonLogs(
'error',
deployData.projectName,
'',
'api:deployEnvironmentPullrequest:error',
meta,
`*[${deployData.projectName}]* Error deploying \`${deployData.branchName}\`: ${error.message}`
);
return `Error: ${error.message}`;
}
}
};
export const deployEnvironmentPromote: ResolverFn = async (
root,
{
input: {
sourceEnvironment: sourceEnvironmentInput,
project: projectInput,
destinationEnvironment
}
},
{ sqlClientPool, hasPermission, userActivityLogger }
) => {
const destProject = await projectHelpers(
sqlClientPool
).getProjectByProjectInput(projectInput);
const envType =
destinationEnvironment === destProject.productionEnvironment
? 'production'
: 'development';
await hasPermission('environment', `deploy:${envType}`, {
project: destProject.id
});
if (destProject.deploymentsDisabled == 1){
throw new Error('Deployments have been disabled for this project');
}
const sourceEnvironments = await environmentHelpers(
sqlClientPool
).getEnvironmentsByEnvironmentInput(sourceEnvironmentInput);
const activeEnvironments = R.filter(
R.propEq('deleted', '0000-00-00 00:00:00'),
sourceEnvironments
);
if (activeEnvironments.length < 1 || activeEnvironments.length > 1) {
throw new Error('Unauthorized');
}
const sourceEnvironment = R.prop(0, activeEnvironments);
await hasPermission('environment', 'view', {
project: sourceEnvironment.project
});
const deployData = {
type: 'promote',
projectName: destProject.name,
branchName: destinationEnvironment,
promoteSourceEnvironment: sourceEnvironment.name
};
const meta = {
projectName: deployData.projectName,
branchName: deployData.branchName,
promoteSourceEnvironment: deployData.promoteSourceEnvironment
};
userActivityLogger(
`User promoted the environment on '${deployData.projectName}' from '${deployData.promoteSourceEnvironment}' to '${deployData.branchName}'`,
{
project: deployData.projectName || '',
event: 'api:deployEnvironmentPromote',
payload: {
deployData
}
}
);
try {
await createPromoteTask(deployData);
sendToLagoonLogs(
'info',
deployData.projectName,
'',
'api:deployEnvironmentPromote',
meta,
`*[${deployData.projectName}]* Deployment triggered \`${deployData.branchName}\``
);
return 'success';
} catch (error) {
switch (error.name) {
case 'NoNeedToDeployBranch':
sendToLagoonLogs(
'info',
deployData.projectName,
'',
'api:deployEnvironmentPromote',
meta,
`*[${deployData.projectName}]* Deployment skipped \`${deployData.branchName}\`: ${error.message}`
);
return `Skipped: ${error.message}`;
default:
sendToLagoonLogs(
'error',
deployData.projectName,
'',
'api:deployEnvironmentPromote:error',
meta,
`*[${deployData.projectName}]* Error deploying \`${deployData.branchName}\`: ${error.message}`
);
return `Error: ${error.message}`;
}
}
};
export const switchActiveStandby: ResolverFn = async (
root,
{ input: { project: projectInput } },
{ sqlClientPool, hasPermission }
) => {
const project = await projectHelpers(sqlClientPool).getProjectByProjectInput(
projectInput
);
// active/standby really only should be between production environments
await hasPermission('environment', `deploy:production`, {
project: project.id
});
await hasPermission('task', 'view', {
project: project.id
});
if (project.standbyProductionEnvironment == null) {
sendToLagoonLogs(
'error',
'',
'',
'api:switchActiveStandby',
'',
`Failed to create active to standby task, reason: no standbyProductionEnvironment configured`
);
return `Error: no standbyProductionEnvironment configured`;
}
// we want the task to show in the standby environment, as this is where the task will be initiated.
const environmentRows = await query(
sqlClientPool,
environmentSql.selectEnvironmentByNameAndProject(
project.standbyProductionEnvironment,
project.id
)
);
const environment = environmentRows[0];
var environmentId = parseInt(environment.id);
// we need to pass some additional information about the production environment
const environmentRowsProd = await query(
sqlClientPool,
environmentSql.selectEnvironmentByNameAndProject(
project.productionEnvironment,
project.id
)
);
const environmentProd = environmentRowsProd[0];
var environmentProdId = parseInt(environmentProd.id);
// construct the data for the misc task
// set up the task data payload
const data = {
project: {
id: project.id,
name: project.name,
productionEnvironment: project.productionEnvironment,
standbyProductionEnvironment: project.standbyProductionEnvironment
},
productionEnvironment: {
id: environmentProdId,
name: environmentProd.name,
openshiftProjectName: environmentProd.openshiftProjectName
},
environment: {
id: environmentId,
name: environment.name,
openshiftProjectName: environment.openshiftProjectName
},
task: {
id: '0',
name: 'Active/Standby Switch'
}
};
// try it now
try {
// add a task into the environment
var date = new Date();
var created = convertDateFormat(date.toISOString());
const sourceTaskData = await addTask(
'Active/Standby Switch',
'ACTIVE',
created,
environmentId,
null,
null,
null,
null,
'',
'',
false
);
data.task.id = sourceTaskData.addTask.id.toString();
// queue the task to trigger the migration
await createMiscTask({ key: 'route:migrate', data });
// return the task id and remote id
var retData = {
id: data.task.id,
environment: environmentId
};
return retData;
} catch (error) {
sendToLagoonLogs(
'error',
'',
'',
'api:switchActiveStandby',
data,
`Failed to create active to standby task, reason: ${error}`
);
return `Error: ${error.message}`;
}
};
export const deploymentSubscriber = createEnvironmentFilteredSubscriber([
EVENTS.DEPLOYMENT.ADDED,
EVENTS.DEPLOYMENT.UPDATED
]); | the_stack |
import { HardhatRuntimeEnvironment } from 'hardhat/types'
import { DeployFunction } from 'hardhat-deploy/types'
import { getDappAddresses, getNativeToken, isEtheremNetwork } from '../config'
import {
ICollateralEscrow,
ILoansEscrow,
ITellerDiamond,
ITToken,
UpgradeableBeaconFactory,
} from '../types/typechain'
import {
deploy,
deployDiamond,
DeployDiamondArgs,
Facets,
} from '../utils/deploy-helpers'
const deployProtocol: DeployFunction = async (hre) => {
const { contracts, network, getNamedAccounts, log } = hre
const { deployer } = await getNamedAccounts()
log('********** Teller Diamond **********', { indent: 1 })
const loansEscrowBeacon = await deployLoansEscrowBeacon(hre)
const collateralEscrowBeacon = await deployCollateralEscrowBeacon(hre)
const tTokenBeacon = await deployTTokenBeacon(hre)
const priceAggregator = await contracts.get('PriceAggregator')
const wrappedNativeToken = getNativeToken(network)
const dappAddresses = getDappAddresses(network)
let execute: DeployDiamondArgs<ITellerDiamond, any>['execute']
try {
// Try to get deployment of TellerDiamond
await contracts.get('TellerDiamond')
// If deployment exists execute upgrade function
const executeMethod = 'setPriceAggregator'
const upgradeExecute = {
methodName: executeMethod,
args: [priceAggregator.address],
}
execute = upgradeExecute
} catch {
// Else execute initialize function
const executeMethod = 'init'
const initExecute: DeployDiamondArgs<
ITellerDiamond,
typeof executeMethod
>['execute'] = {
methodName: executeMethod,
args: [
{
admin: deployer,
loansEscrowBeacon: loansEscrowBeacon.address,
collateralEscrowBeacon: collateralEscrowBeacon.address,
tTokenBeacon: tTokenBeacon.address,
// Teller Gnosis Safe contract
nftLiquidationController:
'0x95143890162bd671d77ae9b771881a1cb76c29a4',
wrappedNativeToken: wrappedNativeToken,
priceAggregator: priceAggregator.address,
},
],
}
execute = initExecute
}
const nftV2 = await contracts.get('TellerNFT_V2')
// Deploy platform diamond
const facets: Facets = [
// Settings
{
contract: 'SettingsFacet',
skipIfAlreadyDeployed: false,
},
{
contract: 'PlatformSettingsFacet',
skipIfAlreadyDeployed: false,
},
{
contract: 'AssetSettingsDataFacet',
skipIfAlreadyDeployed: false,
},
{
contract: 'AssetSettingsFacet',
skipIfAlreadyDeployed: false,
},
{
contract: 'PausableFacet',
skipIfAlreadyDeployed: false,
},
// Pricing
{
contract: 'PriceAggFacet',
skipIfAlreadyDeployed: false,
},
// Lending
{
contract: 'LendingFacet',
skipIfAlreadyDeployed: false,
},
// Loans
{
contract: 'CollateralFacet',
skipIfAlreadyDeployed: false,
},
{
contract: 'CreateLoanConsensusFacet',
skipIfAlreadyDeployed: false,
},
{
contract: 'LoanDataFacet',
skipIfAlreadyDeployed: false,
},
{
contract: 'SignersFacet',
skipIfAlreadyDeployed: false,
},
// Dapps
{
contract: 'AaveFacet',
skipIfAlreadyDeployed: false,
args: [dappAddresses.aaveLendingPoolAddressProvider],
},
{
contract: 'PoolTogetherFacet',
skipIfAlreadyDeployed: false,
},
]
// Network specify Facets
if (isEtheremNetwork(network)) {
const nftMigrator = await contracts.get('NFTMigrator')
facets.push(
// Loans
{
contract: 'MainnetCreateLoanWithNFTFacet',
args: [nftV2.address],
skipIfAlreadyDeployed: false,
},
{
contract: 'MainnetRepayFacet',
args: [nftV2.address],
skipIfAlreadyDeployed: false,
},
// NFT
{
contract: 'MainnetNFTFacet',
skipIfAlreadyDeployed: false,
args: [nftV2.address, nftMigrator.address],
mock: process.env.TESTING === '1',
},
{
contract: 'NFTMainnetBridgingToPolygonFacet',
skipIfAlreadyDeployed: false,
args: [nftMigrator.address],
},
{
contract: 'MainnetNFTInterestFacet',
skipIfAlreadyDeployed: true,
},
// Dapps
{
contract: 'UniswapFacet',
skipIfAlreadyDeployed: false,
args: [dappAddresses.uniswapV2RouterAddress],
},
{
contract: 'CompoundFacet',
skipIfAlreadyDeployed: false,
},
{
contract: 'CompoundClaimCompFacet',
skipIfAlreadyDeployed: false,
args: [dappAddresses.compoundComptrollerAddress],
}
// disable for now
// {
// contract: 'YearnFacet',
// skipIfAlreadyDeployed: false,
// }
)
} else {
facets.push(
// Loans
{
contract: 'CreateLoanWithNFTFacet',
args: [nftV2.address],
skipIfAlreadyDeployed: false,
},
{
contract: 'RepayFacet',
args: [nftV2.address],
skipIfAlreadyDeployed: false,
},
// NFT
{
contract: 'NFTFacet',
skipIfAlreadyDeployed: false,
args: [nftV2.address],
},
// Dapps
{
contract: 'SushiswapFacet',
skipIfAlreadyDeployed: false,
args: [dappAddresses.sushiswapV2RouterAddress],
}
)
}
const tellerDiamondArgs: DeployDiamondArgs<ITellerDiamond, any> = {
hre,
name: 'TellerDiamond',
facets,
owner: deployer,
execute,
}
const diamond = await deployDiamond<ITellerDiamond, any>(tellerDiamondArgs)
await addAuthorizedAddresses(hre, diamond)
const ERC1155_PREDICATE = `0x0B9020d4E32990D67559b1317c7BF0C15D6EB88f`
// set approval for all tokens to be transfered by ERC1155 Predicate
if (
isEtheremNetwork(network, true) &&
nftV2.isApprovedForAll(diamond.address, ERC1155_PREDICATE)
) {
await diamond.initNFTBridge()
}
}
const addAuthorizedAddresses = async (
hre: HardhatRuntimeEnvironment,
diamond: ITellerDiamond
): Promise<void> => {
const { getNamedSigner, getNamedAccounts, network } = hre
const addresses = new Set([
'0xAFe87013dc96edE1E116a288D80FcaA0eFFE5fe5', // - deployer
'0xd59e99927018b995ee9Ad6b9003677f1e7393F8A', // - noah
'0xa243A7b4e9AF8D7e87a5443Aa7E21AB27624eaaA', // - ryry
'0x592000b2c8c590531d490893C16AfC4b9cbbe6B9', // - ryry
'0xd965Cd540d2B80e7ef2840Ff097016B3A0e930fC', // - jer
'0xb8fAF03a268F259dDD9adfAf8E1148Fc81021e54', // - sy
'0xc756Be144729EcDBE51f49073D295ABd318f0048', // - tan
])
if (network.name === 'mainnet') {
} else if (network.name === 'hardhat' || network.name === 'localhost') {
const accounts = await getNamedAccounts()
addresses.add(accounts.lender)
addresses.add(accounts.borrower)
addresses.add(accounts.liquidator)
addresses.add(accounts.funder)
}
// Check if addresses in list already have authorization
const list: string[] = []
for (const address of Array.from(addresses)) {
const has = await diamond.hasAuthorization(address)
if (!has) {
list.push(address)
}
}
if (list.length > 0)
await diamond
.connect(await getNamedSigner('deployer'))
.addAuthorizedAddressList(list)
.then(({ wait }) => wait())
}
const deployLoansEscrowBeacon = async (
hre: HardhatRuntimeEnvironment
): Promise<UpgradeableBeaconFactory> => {
const { getNamedSigner, ethers, log } = hre
const deployer = await getNamedSigner('deployer')
log('********** Loans Escrow Beacon **********', { indent: 2 })
log('')
const logicVersion = 1
const loansEscrowLogic = await deploy<ILoansEscrow>({
hre,
contract: `LoansEscrow_V${logicVersion}`,
indent: 3,
})
const beaconProxy = await deploy({
hre,
contract: 'InitializeableBeaconProxy',
indent: 4,
})
const beacon = await deploy<UpgradeableBeaconFactory>({
hre,
contract: 'UpgradeableBeaconFactory',
name: 'EscrowBeaconFactory',
args: [beaconProxy.address, loansEscrowLogic.address],
skipIfAlreadyDeployed: true,
indent: 4,
})
// Check to see if we need to upgrade
const currentImpl = await beacon.implementation()
if (
ethers.utils.getAddress(currentImpl) !==
ethers.utils.getAddress(loansEscrowLogic.address)
) {
log(`Upgrading Loans Escrow logic: ${loansEscrowLogic.address}`, {
indent: 5,
star: true,
})
await beacon
.connect(deployer)
.upgradeTo(loansEscrowLogic.address)
.then(({ wait }) => wait())
}
log('')
return beacon
}
const deployCollateralEscrowBeacon = async (
hre: HardhatRuntimeEnvironment
): Promise<UpgradeableBeaconFactory> => {
const { getNamedSigner, ethers, log } = hre
const deployer = await getNamedSigner('deployer')
log('********** Collateral Escrow Beacon **********', { indent: 2 })
log('')
const logicVersion = 1
const collateralEscrowLogic = await deploy<ICollateralEscrow>({
hre,
contract: `CollateralEscrow_V${logicVersion}`,
indent: 3,
})
const beaconProxy = await deploy({
hre,
contract: 'InitializeableBeaconProxy',
indent: 4,
})
const beacon = await deploy<UpgradeableBeaconFactory>({
hre,
contract: 'UpgradeableBeaconFactory',
name: 'CollateralEscrowBeaconFactory',
args: [beaconProxy.address, collateralEscrowLogic.address],
skipIfAlreadyDeployed: true,
indent: 4,
})
// Check to see if we need to upgrade
const currentImpl = await beacon.implementation()
if (
ethers.utils.getAddress(currentImpl) !==
ethers.utils.getAddress(collateralEscrowLogic.address)
) {
log(`Upgrading Collateral Escrow logic: ${collateralEscrowLogic.address}`, {
indent: 5,
star: true,
})
await beacon
.connect(deployer)
.upgradeTo(collateralEscrowLogic.address)
.then(({ wait }) => wait())
}
log('')
return beacon
}
const deployTTokenBeacon = async (
hre: HardhatRuntimeEnvironment
): Promise<UpgradeableBeaconFactory> => {
const { getNamedSigner, ethers, log } = hre
const deployer = await getNamedSigner('deployer')
log('********** Teller Token (TToken) Beacon **********', { indent: 2 })
log('')
const logicVersion = '2_Alpha'
const tTokenLogic = await deploy<ITToken>({
hre,
contract: `TToken_V${logicVersion}`,
indent: 3,
})
const beaconProxy = await deploy({
hre,
contract: 'InitializeableBeaconProxy',
indent: 4,
})
const beacon = await deploy<UpgradeableBeaconFactory>({
hre,
contract: 'UpgradeableBeaconFactory',
name: 'TTokenBeaconFactory',
args: [beaconProxy.address, tTokenLogic.address],
skipIfAlreadyDeployed: true,
indent: 4,
})
// Check to see if we need to upgrade
const currentImpl = await beacon.implementation()
if (
ethers.utils.getAddress(currentImpl) !==
ethers.utils.getAddress(tTokenLogic.address)
) {
log(`Upgrading Teller Token logic: ${tTokenLogic.address}`, {
indent: 5,
star: true,
})
await beacon
.connect(deployer)
.upgradeTo(tTokenLogic.address)
.then(({ wait }) => wait())
}
log('')
return beacon
}
deployProtocol.tags = ['protocol']
deployProtocol.dependencies = ['setup', 'nft', 'price-agg']
export default deployProtocol | the_stack |
import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types";
/**
* <p>Sends Conflict Exception.</p>
*/
export interface ConflictException extends __SmithyException, $MetadataBearer {
name: "ConflictException";
$fault: "client";
/**
* <p>Sends Conflict Exception message.</p>
*/
message?: string;
}
export namespace ConflictException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ConflictException): any => ({
...obj,
});
}
/**
* <p>Lists all the devices under test</p>
*/
export interface DeviceUnderTest {
/**
* <p>Lists devices thing arn</p>
*/
thingArn?: string;
/**
* <p>Lists devices certificate arn</p>
*/
certificateArn?: string;
}
export namespace DeviceUnderTest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeviceUnderTest): any => ({
...obj,
});
}
/**
* <p>Gets Suite Definition Configuration.</p>
*/
export interface SuiteDefinitionConfiguration {
/**
* <p>Gets Suite Definition Configuration name.</p>
*/
suiteDefinitionName?: string;
/**
* <p>Gets the devices configured.</p>
*/
devices?: DeviceUnderTest[];
/**
* <p>Gets the tests intended for qualification in a suite.</p>
*/
intendedForQualification?: boolean;
/**
* <p>Gets test suite root group.</p>
*/
rootGroup?: string;
/**
* <p>Gets device permission arn.</p>
*/
devicePermissionRoleArn?: string;
}
export namespace SuiteDefinitionConfiguration {
/**
* @internal
*/
export const filterSensitiveLog = (obj: SuiteDefinitionConfiguration): any => ({
...obj,
});
}
export interface CreateSuiteDefinitionRequest {
/**
* <p>Creates a Device Advisor test suite with suite definition configuration.</p>
*/
suiteDefinitionConfiguration?: SuiteDefinitionConfiguration;
/**
* <p>The tags to be attached to the suite definition.</p>
*/
tags?: { [key: string]: string };
}
export namespace CreateSuiteDefinitionRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateSuiteDefinitionRequest): any => ({
...obj,
});
}
export interface CreateSuiteDefinitionResponse {
/**
* <p>Creates a Device Advisor test suite with suite UUID.</p>
*/
suiteDefinitionId?: string;
/**
* <p>Creates a Device Advisor test suite with Amazon Resource name.</p>
*/
suiteDefinitionArn?: string;
/**
* <p>Creates a Device Advisor test suite with suite definition name.</p>
*/
suiteDefinitionName?: string;
/**
* <p>Creates a Device Advisor test suite with TimeStamp of when it was created.</p>
*/
createdAt?: Date;
}
export namespace CreateSuiteDefinitionResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateSuiteDefinitionResponse): any => ({
...obj,
});
}
/**
* <p>Sends Internal Failure Exception.</p>
*/
export interface InternalServerException extends __SmithyException, $MetadataBearer {
name: "InternalServerException";
$fault: "server";
/**
* <p>Sends Internal Failure Exception message.</p>
*/
message?: string;
}
export namespace InternalServerException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InternalServerException): any => ({
...obj,
});
}
/**
* <p>Sends invalid request exception.</p>
*/
export interface ValidationException extends __SmithyException, $MetadataBearer {
name: "ValidationException";
$fault: "client";
/**
* <p>Sends invalid request exception message.</p>
*/
message?: string;
}
export namespace ValidationException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ValidationException): any => ({
...obj,
});
}
export interface DeleteSuiteDefinitionRequest {
/**
* <p>Suite definition Id of the test suite to be deleted.</p>
*/
suiteDefinitionId: string | undefined;
}
export namespace DeleteSuiteDefinitionRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteSuiteDefinitionRequest): any => ({
...obj,
});
}
export interface DeleteSuiteDefinitionResponse {}
export namespace DeleteSuiteDefinitionResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteSuiteDefinitionResponse): any => ({
...obj,
});
}
export interface GetSuiteDefinitionRequest {
/**
* <p>Suite definition Id of the test suite to get.</p>
*/
suiteDefinitionId: string | undefined;
/**
* <p>Suite definition version of the test suite to get.</p>
*/
suiteDefinitionVersion?: string;
}
export namespace GetSuiteDefinitionRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetSuiteDefinitionRequest): any => ({
...obj,
});
}
export interface GetSuiteDefinitionResponse {
/**
* <p>Suite definition Id of the suite definition.</p>
*/
suiteDefinitionId?: string;
/**
* <p>The ARN of the suite definition.</p>
*/
suiteDefinitionArn?: string;
/**
* <p>Suite definition version of the suite definition.</p>
*/
suiteDefinitionVersion?: string;
/**
* <p>Latest suite definition version of the suite definition.</p>
*/
latestVersion?: string;
/**
* <p>Suite configuration of the suite definition.</p>
*/
suiteDefinitionConfiguration?: SuiteDefinitionConfiguration;
/**
* <p>Date (in Unix epoch time) when the suite definition was created.</p>
*/
createdAt?: Date;
/**
* <p>Date (in Unix epoch time) when the suite definition was last modified.</p>
*/
lastModifiedAt?: Date;
/**
* <p>Tags attached to the suite definition.</p>
*/
tags?: { [key: string]: string };
}
export namespace GetSuiteDefinitionResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetSuiteDefinitionResponse): any => ({
...obj,
});
}
/**
* <p>Sends Resource Not Found Exception.</p>
*/
export interface ResourceNotFoundException extends __SmithyException, $MetadataBearer {
name: "ResourceNotFoundException";
$fault: "client";
/**
* <p>Sends Resource Not Found Exception message.</p>
*/
message?: string;
}
export namespace ResourceNotFoundException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ResourceNotFoundException): any => ({
...obj,
});
}
export interface GetSuiteRunRequest {
/**
* <p>Suite definition Id for the test suite run.</p>
*/
suiteDefinitionId: string | undefined;
/**
* <p>Suite run Id for the test suite run.</p>
*/
suiteRunId: string | undefined;
}
export namespace GetSuiteRunRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetSuiteRunRequest): any => ({
...obj,
});
}
export enum SuiteRunStatus {
CANCELED = "CANCELED",
ERROR = "ERROR",
FAIL = "FAIL",
PASS = "PASS",
PASS_WITH_WARNINGS = "PASS_WITH_WARNINGS",
PENDING = "PENDING",
RUNNING = "RUNNING",
STOPPED = "STOPPED",
STOPPING = "STOPPING",
}
/**
* <p>Gets suite run configuration.</p>
*/
export interface SuiteRunConfiguration {
/**
* <p>Gets the primary device for suite run.</p>
*/
primaryDevice?: DeviceUnderTest;
/**
* <p>Gets test case list.</p>
*/
selectedTestList?: string[];
}
export namespace SuiteRunConfiguration {
/**
* @internal
*/
export const filterSensitiveLog = (obj: SuiteRunConfiguration): any => ({
...obj,
});
}
export enum Status {
CANCELED = "CANCELED",
ERROR = "ERROR",
FAIL = "FAIL",
PASS = "PASS",
PASS_WITH_WARNINGS = "PASS_WITH_WARNINGS",
PENDING = "PENDING",
RUNNING = "RUNNING",
STOPPED = "STOPPED",
STOPPING = "STOPPING",
}
/**
* <p>Provides test case run.</p>
*/
export interface TestCaseRun {
/**
* <p>Provides test case run Id.</p>
*/
testCaseRunId?: string;
/**
* <p>Provides test case run definition Id.</p>
*/
testCaseDefinitionId?: string;
/**
* <p>Provides test case run definition Name.</p>
*/
testCaseDefinitionName?: string;
/**
* <p>Provides test case run status.</p>
*/
status?: Status | string;
/**
* <p>Provides test case run start time.</p>
*/
startTime?: Date;
/**
* <p>Provides test case run end time.</p>
*/
endTime?: Date;
/**
* <p>Provides test case run log Url.</p>
*/
logUrl?: string;
/**
* <p>Provides test case run warnings.</p>
*/
warnings?: string;
/**
* <p>Provides test case run failure result.</p>
*/
failure?: string;
}
export namespace TestCaseRun {
/**
* @internal
*/
export const filterSensitiveLog = (obj: TestCaseRun): any => ({
...obj,
});
}
/**
* <p>Show Group Result.</p>
*/
export interface GroupResult {
/**
* <p>Group result Id.</p>
*/
groupId?: string;
/**
* <p>Group Result Name.</p>
*/
groupName?: string;
/**
* <p>Tests under Group Result.</p>
*/
tests?: TestCaseRun[];
}
export namespace GroupResult {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GroupResult): any => ({
...obj,
});
}
/**
* <p>Show each group result.</p>
*/
export interface TestResult {
/**
* <p>Show each group of test results.</p>
*/
groups?: GroupResult[];
}
export namespace TestResult {
/**
* @internal
*/
export const filterSensitiveLog = (obj: TestResult): any => ({
...obj,
});
}
export interface GetSuiteRunResponse {
/**
* <p>Suite definition Id for the test suite run.</p>
*/
suiteDefinitionId?: string;
/**
* <p>Suite definition version for the test suite run.</p>
*/
suiteDefinitionVersion?: string;
/**
* <p>Suite run Id for the test suite run.</p>
*/
suiteRunId?: string;
/**
* <p>The ARN of the suite run.</p>
*/
suiteRunArn?: string;
/**
* <p>Suite run configuration for the test suite run.</p>
*/
suiteRunConfiguration?: SuiteRunConfiguration;
/**
* <p>Test results for the test suite run.</p>
*/
testResult?: TestResult;
/**
* <p>Date (in Unix epoch time) when the test suite run was started.</p>
*/
startTime?: Date;
/**
* <p>Date (in Unix epoch time) when the test suite run ended.</p>
*/
endTime?: Date;
/**
* <p>Status for the test suite run.</p>
*/
status?: SuiteRunStatus | string;
/**
* <p>Error reason for any test suite run failure.</p>
*/
errorReason?: string;
/**
* <p>The tags attached to the suite run.</p>
*/
tags?: { [key: string]: string };
}
export namespace GetSuiteRunResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetSuiteRunResponse): any => ({
...obj,
});
}
export interface GetSuiteRunReportRequest {
/**
* <p>Suite definition Id of the test suite.</p>
*/
suiteDefinitionId: string | undefined;
/**
* <p>Suite run Id of the test suite run.</p>
*/
suiteRunId: string | undefined;
}
export namespace GetSuiteRunReportRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetSuiteRunReportRequest): any => ({
...obj,
});
}
export interface GetSuiteRunReportResponse {
/**
* <p>Download URL of the qualification report.</p>
*/
qualificationReportDownloadUrl?: string;
}
export namespace GetSuiteRunReportResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetSuiteRunReportResponse): any => ({
...obj,
});
}
export interface ListSuiteDefinitionsRequest {
/**
* <p>The maximum number of results to return at once.</p>
*/
maxResults?: number;
/**
* <p>A token used to get the next set of results.</p>
*/
nextToken?: string;
}
export namespace ListSuiteDefinitionsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListSuiteDefinitionsRequest): any => ({
...obj,
});
}
/**
* <p>Information about the suite definition.</p>
*/
export interface SuiteDefinitionInformation {
/**
* <p>Suite definition Id of the test suite.</p>
*/
suiteDefinitionId?: string;
/**
* <p>Suite name of the test suite.</p>
*/
suiteDefinitionName?: string;
/**
* <p>Specifies the devices under test for the test suite.</p>
*/
defaultDevices?: DeviceUnderTest[];
/**
* <p>Specifies if the test suite is intended for qualification.</p>
*/
intendedForQualification?: boolean;
/**
* <p>Date (in Unix epoch time) when the test suite was created.</p>
*/
createdAt?: Date;
}
export namespace SuiteDefinitionInformation {
/**
* @internal
*/
export const filterSensitiveLog = (obj: SuiteDefinitionInformation): any => ({
...obj,
});
}
export interface ListSuiteDefinitionsResponse {
/**
* <p>An array of objects that provide summaries of information about the suite definitions in the list.</p>
*/
suiteDefinitionInformationList?: SuiteDefinitionInformation[];
/**
* <p>A token used to get the next set of results.</p>
*/
nextToken?: string;
}
export namespace ListSuiteDefinitionsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListSuiteDefinitionsResponse): any => ({
...obj,
});
}
export interface ListSuiteRunsRequest {
/**
* <p>Lists the test suite runs of the specified test suite based on suite definition Id.</p>
*/
suiteDefinitionId?: string;
/**
* <p>Must be passed along with suiteDefinitionId. Lists the test suite runs of the specified test suite based on suite definition version.</p>
*/
suiteDefinitionVersion?: string;
/**
* <p>The maximum number of results to return at once.</p>
*/
maxResults?: number;
/**
* <p>A token to retrieve the next set of results.</p>
*/
nextToken?: string;
}
export namespace ListSuiteRunsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListSuiteRunsRequest): any => ({
...obj,
});
}
/**
* <p>Information about the suite run.</p>
*/
export interface SuiteRunInformation {
/**
* <p>Suite definition Id of the suite run.</p>
*/
suiteDefinitionId?: string;
/**
* <p>Suite definition version of the suite run.</p>
*/
suiteDefinitionVersion?: string;
/**
* <p>Suite definition name of the suite run.</p>
*/
suiteDefinitionName?: string;
/**
* <p>Suite run Id of the suite run.</p>
*/
suiteRunId?: string;
/**
* <p>Date (in Unix epoch time) when the suite run was created.</p>
*/
createdAt?: Date;
/**
* <p>Date (in Unix epoch time) when the suite run was started.</p>
*/
startedAt?: Date;
/**
* <p>Date (in Unix epoch time) when the suite run ended.</p>
*/
endAt?: Date;
/**
* <p>Status of the suite run.</p>
*/
status?: SuiteRunStatus | string;
/**
* <p>Number of test cases that passed in the suite run.</p>
*/
passed?: number;
/**
* <p>Number of test cases that failed in the suite run.</p>
*/
failed?: number;
}
export namespace SuiteRunInformation {
/**
* @internal
*/
export const filterSensitiveLog = (obj: SuiteRunInformation): any => ({
...obj,
});
}
export interface ListSuiteRunsResponse {
/**
* <p>An array of objects that provide summaries of information about the suite runs in the list.</p>
*/
suiteRunsList?: SuiteRunInformation[];
/**
* <p>A token to retrieve the next set of results.</p>
*/
nextToken?: string;
}
export namespace ListSuiteRunsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListSuiteRunsResponse): any => ({
...obj,
});
}
export interface ListTagsForResourceRequest {
/**
* <p>The ARN of the IoT Device Advisor resource.</p>
*/
resourceArn: string | undefined;
}
export namespace ListTagsForResourceRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListTagsForResourceRequest): any => ({
...obj,
});
}
export interface ListTagsForResourceResponse {
/**
* <p>The tags attached to the IoT Device Advisor resource.</p>
*/
tags?: { [key: string]: string };
}
export namespace ListTagsForResourceResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListTagsForResourceResponse): any => ({
...obj,
});
}
export interface StartSuiteRunRequest {
/**
* <p>Suite definition Id of the test suite.</p>
*/
suiteDefinitionId: string | undefined;
/**
* <p>Suite definition version of the test suite.</p>
*/
suiteDefinitionVersion?: string;
/**
* <p>Suite run configuration.</p>
*/
suiteRunConfiguration?: SuiteRunConfiguration;
/**
* <p>The tags to be attached to the suite run.</p>
*/
tags?: { [key: string]: string };
}
export namespace StartSuiteRunRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: StartSuiteRunRequest): any => ({
...obj,
});
}
export interface StartSuiteRunResponse {
/**
* <p>Suite Run Id of the started suite run.</p>
*/
suiteRunId?: string;
/**
* <p>Amazon resource name of the started suite run.</p>
*/
suiteRunArn?: string;
/**
* <p>Date (in Unix epoch time) when the suite run was created.</p>
*/
createdAt?: Date;
}
export namespace StartSuiteRunResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: StartSuiteRunResponse): any => ({
...obj,
});
}
export interface StopSuiteRunRequest {
/**
* <p>Suite definition Id of the test suite run to be stopped.</p>
*/
suiteDefinitionId: string | undefined;
/**
* <p>Suite run Id of the test suite run to be stopped.</p>
*/
suiteRunId: string | undefined;
}
export namespace StopSuiteRunRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: StopSuiteRunRequest): any => ({
...obj,
});
}
export interface StopSuiteRunResponse {}
export namespace StopSuiteRunResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: StopSuiteRunResponse): any => ({
...obj,
});
}
export interface TagResourceRequest {
/**
* <p>The resource ARN of an IoT Device Advisor resource.</p>
*/
resourceArn: string | undefined;
/**
* <p>The tags to be attached to the IoT Device Advisor resource.</p>
*/
tags: { [key: string]: string } | undefined;
}
export namespace TagResourceRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: TagResourceRequest): any => ({
...obj,
});
}
export interface TagResourceResponse {}
export namespace TagResourceResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: TagResourceResponse): any => ({
...obj,
});
}
export interface UntagResourceRequest {
/**
* <p>The resource ARN of an IoT Device Advisor resource.</p>
*/
resourceArn: string | undefined;
/**
* <p>List of tag keys to remove from the IoT Device Advisor resource.</p>
*/
tagKeys: string[] | undefined;
}
export namespace UntagResourceRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UntagResourceRequest): any => ({
...obj,
});
}
export interface UntagResourceResponse {}
export namespace UntagResourceResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UntagResourceResponse): any => ({
...obj,
});
}
export interface UpdateSuiteDefinitionRequest {
/**
* <p>Suite definition Id of the test suite to be updated.</p>
*/
suiteDefinitionId: string | undefined;
/**
* <p>Updates a Device Advisor test suite with suite definition configuration.</p>
*/
suiteDefinitionConfiguration?: SuiteDefinitionConfiguration;
}
export namespace UpdateSuiteDefinitionRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateSuiteDefinitionRequest): any => ({
...obj,
});
}
export interface UpdateSuiteDefinitionResponse {
/**
* <p>Suite definition Id of the updated test suite.</p>
*/
suiteDefinitionId?: string;
/**
* <p>Amazon Resource name of the updated test suite.</p>
*/
suiteDefinitionArn?: string;
/**
* <p>Suite definition name of the updated test suite.</p>
*/
suiteDefinitionName?: string;
/**
* <p>Suite definition version of the updated test suite.</p>
*/
suiteDefinitionVersion?: string;
/**
* <p>Timestamp of when the test suite was created.</p>
*/
createdAt?: Date;
/**
* <p>Timestamp of when the test suite was updated.</p>
*/
lastUpdatedAt?: Date;
}
export namespace UpdateSuiteDefinitionResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateSuiteDefinitionResponse): any => ({
...obj,
});
} | the_stack |
import { Injectable, Autowired, Optional } from '@opensumi/di';
import { Decoration, TargetMatchMode } from '@opensumi/ide-components';
import {
DisposableCollection,
Disposable,
ILogger,
WithEventBus,
URI,
ThrottledDelayer,
FileStat,
} from '@opensumi/ide-core-browser';
import { FileTreeDropEvent } from '@opensumi/ide-core-common/lib/types/dnd';
import { IMessageService } from '@opensumi/ide-overlay';
import { IFileTreeAPI, IFileTreeService } from '../../common';
import { Directory, File } from '../../common/file-tree-node.define';
import treeNodeStyles from '../file-tree-node.module.less';
import styles from '../file-tree.module.less';
import { FileTreeService } from '../file-tree.service';
import { FileTreeModelService } from './file-tree-model.service';
@Injectable()
export class DragAndDropService extends WithEventBus {
static MS_TILL_DRAGGED_OVER_EXPANDS = 500;
@Autowired(IFileTreeAPI)
private readonly fileTreeAPI: IFileTreeAPI;
@Autowired(ILogger)
private readonly logger: ILogger;
@Autowired(IMessageService)
private readonly messageService: IMessageService;
@Autowired(IFileTreeService)
private readonly fileTreeService: FileTreeService;
private toCancelNodeExpansion: DisposableCollection = new DisposableCollection();
private beingDraggedDec: Decoration = new Decoration(treeNodeStyles.mod_dragging);
private draggedOverDec: Decoration = new Decoration(treeNodeStyles.mod_dragover);
// 上一次拖拽进入的目录
private potentialParent: Directory | null;
// 开始拖拽的节点
private beingDraggedNodes: (File | Directory)[] = [];
private beingDraggedActiveUri: URI | undefined;
// 拖拽进入的节点
private draggedOverNode: Directory | File;
private dragOverTrigger = new ThrottledDelayer<void>(DragAndDropService.MS_TILL_DRAGGED_OVER_EXPANDS);
constructor(@Optional() private readonly model: FileTreeModelService) {
super();
this.model.decorations.addDecoration(this.beingDraggedDec);
this.model.decorations.addDecoration(this.draggedOverDec);
}
get root() {
return this.model.treeModel.root;
}
handleDragStart = (ev: React.DragEvent, node: File | Directory, activeUri?: URI) => {
ev.stopPropagation();
// React中的DragEnd事件可能不会触发,需要手动用Dom监听
// issue https://stackoverflow.com/a/24543568
ev.currentTarget.addEventListener(
'dragend',
(ev) => {
this.handleDragEnd(ev, node);
},
false,
);
let draggedNodes = this.model.selectedFiles;
let isDragWithSelectedNode = false;
for (const selected of draggedNodes) {
if (selected && selected.id === node.id) {
isDragWithSelectedNode = true;
}
}
if (!isDragWithSelectedNode) {
draggedNodes = [node];
}
this.beingDraggedNodes = draggedNodes;
this.beingDraggedActiveUri = activeUri;
const draggedFile = draggedNodes.find((node) => !Directory.is(node));
// 保证多选情况下找到首个文件
if (draggedFile) {
ev.dataTransfer.setData('uri', draggedFile.uri.toString());
}
draggedNodes.forEach((node) => {
// 添加拖拽样式
this.beingDraggedDec.addTarget(node, TargetMatchMode.Self);
});
if (ev.dataTransfer) {
let label: string;
if (draggedNodes.length === 1) {
label = activeUri ? activeUri.displayName : typeof node.name === 'string' ? node.name : '';
} else {
label = String(draggedNodes.length);
}
const dragImage = document.createElement('div');
dragImage.className = styles.file_tree_drag_image;
dragImage.textContent = label;
document.body.appendChild(dragImage);
ev.dataTransfer.setDragImage(dragImage, -10, -10);
setTimeout(() => document.body.removeChild(dragImage), 0);
}
};
handleDragEnter = (ev: React.DragEvent, node: File | Directory) => {
ev.stopPropagation();
ev.preventDefault();
};
handleDragLeave = (ev: React.DragEvent, node: File | Directory) => {
ev.preventDefault();
ev.stopPropagation();
this.toCancelNodeExpansion.dispose();
// 拖拽目标离开时,清除选中态
if (this.potentialParent) {
this.draggedOverDec.removeTarget(this.potentialParent);
// 通知视图更新
this.model.treeModel.dispatchChange();
}
};
handleDragOver = (ev: React.DragEvent, node: File | Directory) => {
ev.preventDefault();
ev.stopPropagation();
if (!this.toCancelNodeExpansion.disposed) {
return;
}
if (this.beingDraggedNodes.indexOf(node) >= 0) {
return;
}
this.draggedOverNode = node;
const newPotentialParent: Directory =
Directory.is(node) && (node as Directory).expanded ? (node as Directory) : (node.parent as Directory);
if (this.potentialParent !== newPotentialParent || !this.draggedOverDec.hasTarget(newPotentialParent)) {
if (this.potentialParent) {
this.draggedOverDec.removeTarget(this.potentialParent);
}
this.potentialParent = newPotentialParent;
this.draggedOverDec.addTarget(this.potentialParent, TargetMatchMode.SelfAndChildren);
// 通知视图更新
this.model.treeModel.dispatchChange();
}
if (this.potentialParent !== node && Directory.is(node)) {
this.dragOverTrigger.trigger(async () => {
if (!node.expanded) {
await (node as Directory).setExpanded(true);
// 确保当前仍在当前拖区域节点中
if (this.draggedOverNode === node) {
if (this.potentialParent) {
this.draggedOverDec.removeTarget(this.potentialParent);
}
this.potentialParent = node as Directory;
this.draggedOverDec.addTarget(this.potentialParent, TargetMatchMode.SelfAndChildren);
}
} else {
if (this.potentialParent) {
this.draggedOverDec.removeTarget(this.potentialParent);
}
this.potentialParent = node as Directory;
this.draggedOverDec.addTarget(this.potentialParent, TargetMatchMode.SelfAndChildren);
}
// 通知视图更新
this.model.treeModel.dispatchChange();
});
this.toCancelNodeExpansion.push(
Disposable.create(() => {
this.dragOverTrigger.cancel();
}),
);
}
};
handleDrop = async (ev: React.DragEvent, node?: File | Directory, activeUri?: URI) => {
this.eventBus.fire(
new FileTreeDropEvent({
event: ev.nativeEvent,
targetDir: activeUri
? activeUri.codeUri.path
: node && node instanceof File
? (node.parent as Directory)?.uri.codeUri.path
: node?.uri.codeUri.path,
}),
);
try {
ev.preventDefault();
ev.stopPropagation();
// 移除染色
ev.dataTransfer.dropEffect = 'copy';
let containing: File | Directory | null;
const isCompactFolderMove = !!this.beingDraggedActiveUri;
if (this.fileTreeService.isCompactMode && activeUri && !node?.uri.isEqual(activeUri)) {
containing = null;
} else if (node) {
containing = Directory.is(node) ? (node as Directory) : (node.parent as Directory);
} else {
containing = this.root as Directory;
}
let resources;
if (this.beingDraggedActiveUri) {
const compactNode = this.fileTreeService.getNodeByPathOrUri(this.beingDraggedActiveUri);
// 生成临时节点用于数据处理
resources = [
new Directory(
this.fileTreeService,
compactNode?.parent,
this.beingDraggedActiveUri,
this.beingDraggedActiveUri.displayName,
{
uri: this.beingDraggedActiveUri.toString(),
isDirectory: true,
lastModification: new Date().getTime(),
} as FileStat,
this.beingDraggedActiveUri.displayName,
),
];
} else {
resources = this.beingDraggedNodes;
}
if (resources.length > 0) {
const targetContainerUri = activeUri ? activeUri : (containing && containing.uri)!;
const resourcesCanBeMoved = resources.filter(
(resource: File | Directory) =>
resource && resource.parent && !(resource.parent as Directory).uri.isEqual(targetContainerUri),
);
if (resourcesCanBeMoved.length > 0) {
// 最小化移动文件
const errors = await this.fileTreeAPI.mvFiles(
resourcesCanBeMoved.map((res) => res.uri),
targetContainerUri,
);
if (errors && errors.length > 0) {
errors.forEach((error) => {
this.messageService.error(error);
});
} else if (!errors) {
return;
} else {
if (containing) {
// 这里不能直接使用this.beingDraggedActiveUri做判断,因为需要等待上面移动文件成功后,此时dropEnd事件可能已经执行完了
if (this.fileTreeService.isCompactMode && isCompactFolderMove) {
// 当从压缩目录移动子节点到其他容器时
for (const target of resourcesCanBeMoved) {
this.fileTreeService.refresh(target.parent as Directory);
}
this.fileTreeService.refresh(containing as Directory);
} else {
// 非压缩目录模式情况
for (const target of resourcesCanBeMoved) {
const to = containing.uri.resolve(target.name);
this.fileTreeService.moveNodeByPath(
target.parent as Directory,
containing,
target.name,
target.name,
target.type,
);
// 由于节点移动时默认仅更新节点路径
// 我们需要自己更新额外的参数,如uri, filestat等
target.updateURI(to);
target.updateFileStat({
...target.filestat,
uri: to.toString(),
});
target.updateToolTip(this.fileTreeAPI.getReadableTooltip(to));
// 当重命名文件为文件夹时,刷新文件夹更新子文件路径
if (Directory.is(target)) {
this.fileTreeService.refresh(target as Directory);
}
}
}
} else if (node) {
if (this.fileTreeService.isCompactMode && isCompactFolderMove) {
// 从压缩目录子节点移动到压缩目录子节点下
for (const target of resourcesCanBeMoved) {
this.fileTreeService.refresh(target.parent as Directory);
}
} else {
// 当从普通目录移动到压缩目录子节点时
for (const target of resourcesCanBeMoved) {
this.fileTreeService.deleteAffectedNodeByPath(target.path);
}
}
// 否则,刷新模板节点的父节点
this.fileTreeService.refresh(node.parent as Directory);
}
}
}
}
if (node) {
this.beingDraggedDec.removeTarget(node);
}
if (this.potentialParent) {
this.draggedOverDec.removeTarget(this.potentialParent);
}
this.beingDraggedNodes.forEach((node) => {
// 添加拖拽样式
this.beingDraggedDec.removeTarget(node);
});
this.beingDraggedNodes = [];
this.beingDraggedActiveUri = undefined;
this.potentialParent = null;
// 通知视图更新
this.model.treeModel.dispatchChange();
if (!this.toCancelNodeExpansion.disposed) {
this.toCancelNodeExpansion.dispose();
}
} catch (e) {
this.logger.error(e);
}
};
handleDragEnd = (ev: React.DragEvent, node: File | Directory) => {
this.beingDraggedDec.removeTarget(node);
if (this.potentialParent) {
this.draggedOverDec.removeTarget(this.potentialParent);
}
this.beingDraggedNodes.forEach((node) => {
// 移除拖拽样式
this.beingDraggedDec.removeTarget(node);
});
this.beingDraggedNodes = [];
this.beingDraggedActiveUri = undefined;
this.potentialParent = null;
// 通知视图更新
this.model.treeModel.dispatchChange();
if (!this.toCancelNodeExpansion.disposed) {
this.toCancelNodeExpansion.dispose();
}
};
} | the_stack |
import * as TS from 'typescript'
import { SourceNode } from 'source-map'
import {
addUniquely,
dropLast,
flatMapArray,
stripNulls,
traverseArray,
} from '../../shared/array-utils'
import {
applicative2Either,
bimapEither,
Either,
flatMapEither,
foldEither,
forEachRight,
isLeft,
left,
mapEither,
right,
traverseEither,
} from '../../shared/either'
import {
ArbitraryJSBlock,
arbitraryJSBlock,
isJSXArbitraryBlock,
isJSXAttributeValue,
isJSXElement,
isJSXTextBlock,
JSXArbitraryBlock,
jsxArbitraryBlock,
JSXArrayElement,
jsxArraySpread,
jsxArrayValue,
JSXAttribute,
jsxAttributeFunctionCall,
jsxAttributeNestedArray,
jsxAttributeNestedObject,
jsxAttributeOtherJavaScript,
JSXAttributeOtherJavaScript,
JSXAttributes,
jsxAttributeValue,
jsxElement,
JSXElementChild,
JSXElementChildren,
JSXElementName,
jsxElementName,
JSXProperty,
jsxPropertyAssignment,
jsxSpreadAssignment,
jsxTextBlock,
ElementsWithin,
jsxFragment,
jsxElementNameEquals,
isIntrinsicElement,
clearAttributesUniqueIDs,
clearAttributesSourceMaps,
Comment,
WithComments,
BlockOrExpression,
simplifyAttributeIfPossible,
jsxAttributesEntry,
setJSXAttributesAttribute,
jsxAttributesSpread,
isIntrinsicElementFromString,
emptyComments,
ParsedComments,
parsedComments,
} from '../../shared/element-template'
import { maybeToArray, forceNotNull } from '../../shared/optional-utils'
import {
HighlightBounds,
Imports,
PropertyPath,
PropertyPathPart,
HighlightBoundsForUids,
} from '../../shared/project-file-types'
import {
generateConsistentUID,
generateUID,
getUtopiaIDFromJSXElement,
parseUID,
} from '../../shared/uid-utils'
import { fastForEach, RETURN_TO_PREPEND } from '../../shared/utils'
import {
transpileJavascriptFromCode,
transpileJavascript,
insertDataUIDsIntoCode,
} from './parser-printer-transpiling'
import * as PP from '../../shared/property-path'
import { prependToSourceString, ElementsWithinInPosition } from './parser-printer-utils'
import Hash from 'object-hash'
import { getComments, getTrailingComments } from './parser-printer-comments'
import { JSX_CANVAS_LOOKUP_FUNCTION_NAME } from '../../shared/dom-utils'
function inPositionToElementsWithin(elements: ElementsWithinInPosition): ElementsWithin {
let result: ElementsWithin = {}
fastForEach(elements, (element) => {
result[element.uid] = element.element
})
return result
}
function nodeArrayToArray<T extends TS.Node>(nodeArray: TS.NodeArray<T>): Array<T> {
return nodeArray.slice()
}
export function getPropertyNameText(
propertyName: TS.PropertyName,
file: TS.SourceFile,
): Either<string, string> {
if (TS.isIdentifier(propertyName)) {
return right(propertyName.getText(file))
} else if (TS.isStringLiteral(propertyName)) {
return right(propertyName.text)
} else if (TS.isNumericLiteral(propertyName)) {
return right(propertyName.text)
} else {
return left(`Cannot handle computed property names.`)
}
}
export function markedWithKeyword(node: TS.Node, keyword: TS.SyntaxKind): boolean {
if (node.modifiers == null) {
return false
} else {
return node.modifiers.some((modifier) => modifier.kind === keyword)
}
}
export function markedAsDefault(node: TS.Node): boolean {
return markedWithKeyword(node, TS.SyntaxKind.DefaultKeyword)
}
export function markedAsExported(node: TS.Node): boolean {
return markedWithKeyword(node, TS.SyntaxKind.ExportKeyword)
}
export function isExported(node: TS.Node): boolean {
if (TS.isExportAssignment(node)) {
return true
} else {
return markedAsExported(node)
}
}
function parseArrayLiteralExpression(
sourceFile: TS.SourceFile,
sourceText: string,
filename: string,
imports: Imports,
topLevelNames: Array<string>,
propsObjectName: string | null,
literal: TS.ArrayLiteralExpression,
existingHighlightBounds: Readonly<HighlightBoundsForUids>,
alreadyExistingUIDs: Set<string>,
): Either<string, WithParserMetadata<JSXAttribute>> {
let arrayContents: Array<JSXArrayElement> = []
let highlightBounds = existingHighlightBounds
let propsUsed: Array<string> = []
let definedElsewhere: Array<string> = []
// Get comments attached to the square bracket.
let openSquareBracketComments: ParsedComments = emptyComments
const firstChild = literal.getChildAt(0, sourceFile)
if (firstChild != null && firstChild.kind === TS.SyntaxKind.OpenBracketToken) {
openSquareBracketComments = getComments(sourceText, firstChild)
}
let firstProp: boolean = true
for (const literalElement of literal.elements) {
// Capture the comments around the entire entry.
let elementComments = getComments(sourceText, literalElement)
if (firstProp) {
elementComments = parsedComments(
[...openSquareBracketComments.trailingComments, ...elementComments.leadingComments],
elementComments.trailingComments,
)
}
if (TS.isSpreadElement(literalElement)) {
const subExpression = parseAttributeExpression(
sourceFile,
sourceText,
filename,
imports,
topLevelNames,
propsObjectName,
literalElement.expression,
existingHighlightBounds,
alreadyExistingUIDs,
[],
)
if (isLeft(subExpression)) {
return subExpression
} else {
highlightBounds = subExpression.value.highlightBounds
propsUsed.push(...subExpression.value.propsUsed)
definedElsewhere.push(...subExpression.value.definedElsewhere)
arrayContents.push(jsxArraySpread(subExpression.value.value, elementComments))
}
} else {
const subExpression = parseAttributeExpression(
sourceFile,
sourceText,
filename,
imports,
topLevelNames,
propsObjectName,
literalElement,
highlightBounds,
alreadyExistingUIDs,
[],
)
if (isLeft(subExpression)) {
return subExpression
} else {
highlightBounds = subExpression.value.highlightBounds
propsUsed.push(...subExpression.value.propsUsed)
definedElsewhere.push(...subExpression.value.definedElsewhere)
const subExpressionValue: JSXAttribute = subExpression.value.value
arrayContents.push(jsxArrayValue(subExpressionValue, elementComments))
}
}
}
return right(
withParserMetadata(
jsxAttributeNestedArray(arrayContents, emptyComments),
highlightBounds,
propsUsed,
definedElsewhere,
),
)
}
function parseObjectLiteralExpression(
sourceFile: TS.SourceFile,
sourceText: string,
filename: string,
imports: Imports,
topLevelNames: Array<string>,
propsObjectName: string | null,
literal: TS.ObjectLiteralExpression,
existingHighlightBounds: Readonly<HighlightBoundsForUids>,
alreadyExistingUIDs: Set<string>,
): Either<string, WithParserMetadata<JSXAttribute>> {
let contents: Array<JSXProperty> = []
let highlightBounds = existingHighlightBounds
let propsUsed: Array<string> = []
let definedElsewhere: Array<string> = []
// Get comments attached to the open brace.
let openBraceComments: ParsedComments = emptyComments
const firstChild = literal.getChildAt(0, sourceFile)
if (firstChild != null && firstChild.kind === TS.SyntaxKind.OpenBraceToken) {
openBraceComments = getComments(sourceText, firstChild)
}
let firstProp: boolean = true
for (const literalProp of literal.properties) {
// Capture the comments around the entire entry.
let propComments = getComments(sourceText, literalProp)
if (firstProp) {
propComments = parsedComments(
[...openBraceComments.trailingComments, ...propComments.leadingComments],
propComments.trailingComments,
)
}
if (TS.isPropertyAssignment(literalProp) || TS.isShorthandPropertyAssignment(literalProp)) {
// The colon in the middle might have comments attached to it, we should try to grab those.
const colonToken = literalProp
.getChildren(sourceFile)
.find((node) => node.kind === TS.SyntaxKind.ColonToken)
const colonTokenComments =
colonToken == null ? emptyComments : getComments(sourceText, colonToken)
const initializer = TS.isPropertyAssignment(literalProp)
? literalProp.initializer
: literalProp.name
const subExpression = parseAttributeExpression(
sourceFile,
sourceText,
filename,
imports,
topLevelNames,
propsObjectName,
initializer,
highlightBounds,
alreadyExistingUIDs,
colonTokenComments.trailingComments,
)
if (isLeft(subExpression)) {
return subExpression
} else {
const possibleKey = getPropertyNameText(literalProp.name, sourceFile)
if (isLeft(possibleKey)) {
return possibleKey
} else {
const key = possibleKey.value
const subExpressionValue: JSXAttribute = subExpression.value.value
const keyComments = getComments(sourceText, literalProp.name)
contents.push(jsxPropertyAssignment(key, subExpressionValue, propComments, keyComments))
highlightBounds = subExpression.value.highlightBounds
propsUsed.push(...subExpression.value.propsUsed)
definedElsewhere.push(...subExpression.value.definedElsewhere)
}
}
} else if (TS.isSpreadAssignment(literalProp)) {
const subExpression = parseAttributeExpression(
sourceFile,
sourceText,
filename,
imports,
topLevelNames,
propsObjectName,
literalProp.expression,
highlightBounds,
alreadyExistingUIDs,
[],
)
if (isLeft(subExpression)) {
return subExpression
} else {
const subExpressionValue = subExpression.value.value
contents.push(jsxSpreadAssignment(subExpressionValue, propComments))
highlightBounds = subExpression.value.highlightBounds
propsUsed.push(...subExpression.value.propsUsed)
definedElsewhere.push(...subExpression.value.definedElsewhere)
}
}
// First prop reset after everything has been handled.
firstProp = false
}
return right(
withParserMetadata(
jsxAttributeNestedObject(contents, emptyComments),
highlightBounds,
propsUsed,
definedElsewhere,
),
)
}
interface PropertyAccessDescriptor {
identifier: string
property: PropertyPath
}
export function parsePropertyPathLikeExpression(
sourceFile: TS.SourceFile,
expression: TS.Expression,
): Either<string, PropertyAccessDescriptor> {
function innerParse(
inner: TS.Expression,
pathSoFar: Array<PropertyPathPart>,
): Either<string, PropertyAccessDescriptor> {
if (TS.isPropertyAccessExpression(inner)) {
const prop = inner.name.getText(sourceFile)
return innerParse(inner.expression, [prop, ...pathSoFar])
} else if (TS.isElementAccessExpression(inner)) {
if (TS.isNumericLiteral(inner.argumentExpression)) {
try {
const int = Number.parseInt(inner.argumentExpression.getText(sourceFile))
return innerParse(inner.expression, [int, ...pathSoFar])
} catch {
return left(`Index argument wasn't an integer.`)
}
} else if (TS.isStringLiteral(inner.argumentExpression)) {
const prop = inner.argumentExpression.getText(sourceFile)
return innerParse(inner.expression, [prop, ...pathSoFar])
} else {
return left(`Unhandled element access expression.`)
}
} else if (TS.isIdentifier(inner)) {
return right({
identifier: inner.getText(sourceFile),
property: PP.create(pathSoFar),
})
} else {
return left(`Unhandled expression type.`)
}
}
return innerParse(expression, [])
}
function turnCodeSnippetIntoSourceMapNodes(
fileName: string,
startLine: number,
startChar: number,
sourceCode: string,
nodeIsExported: boolean,
): typeof SourceNode {
const LetterOrNumber = /[a-zA-Z0-9]/
const NewLine = /\n/
const FunctionStart = /^ *\(/
let nodes: Array<typeof SourceNode> = []
let currentLine = startLine
let currentCol = startChar
let bufferStartLine = currentLine
let bufferStartChar = currentCol
let currentStringBuffer = ''
let exportFound = false
let defaultFound = false
let lastKeywordWasExport = false
let i = 0
function flushBuffer() {
// We should ignore the first "export" and "default" keywords we find if the node is exported
const strippingExport = nodeIsExported && !exportFound && currentStringBuffer === 'export'
const strippingDefault =
lastKeywordWasExport && nodeIsExported && !defaultFound && currentStringBuffer === 'default'
lastKeywordWasExport =
strippingExport || (lastKeywordWasExport && currentStringBuffer.trim().length === 0)
if (strippingExport) {
exportFound = true
} else if (strippingDefault) {
defaultFound = true
} else {
// When there's an `export default function()` we strip off the `export default`, but without
// that it becomes an invalid chunk of JavaScript without a name so add in a default one.
if (
exportFound &&
defaultFound &&
currentStringBuffer === 'function' &&
FunctionStart.test(sourceCode.substr(i))
) {
currentStringBuffer = 'function utopia_defaultFunctionName'
}
const node = new SourceNode(
bufferStartLine + 1,
bufferStartChar + 1,
fileName,
currentStringBuffer,
currentStringBuffer,
)
nodes.push(node)
}
currentStringBuffer = ''
bufferStartLine = currentLine
bufferStartChar = currentCol
}
function newLine() {
currentLine += 1
currentCol = 0
}
for (; i < sourceCode.length; i++) {
const currentChar = sourceCode[i]
// if the current char is not a letter or number, make a cut and push the buffer to a source node
if (
LetterOrNumber.exec(currentChar) == null ||
(currentStringBuffer.length === 1 && LetterOrNumber.exec(currentStringBuffer[0]) == null)
) {
flushBuffer()
}
currentCol += 1
if (NewLine.exec(currentChar) != null) {
newLine()
}
currentStringBuffer = currentStringBuffer.concat(currentChar)
}
flushBuffer()
return new SourceNode(startLine + 1, startChar + 1, fileName, [nodes])
}
interface ExpressionAndText<E extends TS.Node> {
expression: E | undefined
text: string
startPos: number
endPos: number
}
function createExpressionAndText<E extends TS.Node>(
expression: E | undefined,
text: string,
startPos: number,
endPos: number,
): ExpressionAndText<E> {
return {
expression: expression,
text: text,
startPos: startPos,
endPos: endPos,
}
}
function parseOtherJavaScript<E extends TS.Node, T>(
sourceFile: TS.SourceFile,
sourceText: string,
filename: string,
expressionsAndTexts: Array<ExpressionAndText<E>>,
imports: Imports,
topLevelNames: Array<string>,
initialPropsObjectName: string | null,
existingHighlightBounds: Readonly<HighlightBoundsForUids>,
alreadyExistingUIDs: Set<string>,
trailingCode: string,
create: (
code: string,
definedWithin: Array<string>,
definedElsewhere: Array<string>,
fileNode: typeof SourceNode,
parsedElementsWithin: ElementsWithinInPosition,
) => Either<string, T>,
): Either<string, WithParserMetadata<T>> {
if (expressionsAndTexts.length === 0) {
throw new Error('Unable to deal with a collection of zero expressions.')
} else {
let startLineShift: number = 0
let startColumnShift: number = 0
let lastBlockEndLine: number = 1
let propsObjectName = initialPropsObjectName // nullified if re-defined within
let definedWithin: Array<string> = []
let definedElsewhere: Array<string> = []
let propsUsed: Array<string> = []
function pushToDefinedWithinIfNotThere(name: string): void {
if (!definedWithin.includes(name)) {
definedWithin.push(name)
if (propsObjectName === name) {
propsObjectName = null
}
}
}
function addBindingNameToDefinedWithin(name: TS.BindingName): void {
if (TS.isIdentifier(name)) {
pushToDefinedWithinIfNotThere(name.getText(sourceFile))
} else if (TS.isObjectBindingPattern(name)) {
for (const element of name.elements) {
addBindingNameToDefinedWithin(element.name)
}
} else if (TS.isArrayBindingPattern(name)) {
for (const element of name.elements) {
if (TS.isBindingElement(element)) {
addBindingNameToDefinedWithin(element.name)
}
}
}
}
function pushToDefinedElsewhereIfNotThere(inScope: Array<string>, name: string): void {
if (!inScope.includes(name) && !definedElsewhere.includes(name)) {
definedElsewhere.push(name)
}
}
function addIfDefinedElsewhere(
inScope: Array<string>,
nodeToCheck: TS.Node,
nodeIsJSXElement: boolean,
): boolean {
if (TS.isIdentifier(nodeToCheck)) {
const nameToAdd = nodeToCheck.getText(sourceFile)
if (nodeIsJSXElement) {
if (!isIntrinsicElementFromString(nameToAdd)) {
pushToDefinedElsewhereIfNotThere(inScope, nameToAdd)
return true
}
} else {
pushToDefinedElsewhereIfNotThere(inScope, nameToAdd)
return true
}
}
return false
}
function pushToPropsUsedIfNotThere(name: string): void {
if (!propsUsed.includes(name)) {
propsUsed.push(name)
}
}
function isPropsObject(nodeToCheck: TS.Identifier): boolean {
return propsObjectName != null && nodeToCheck.getText(sourceFile) === propsObjectName
}
function addIfPropsUsed(nodeToCheck: TS.LeftHandSideExpression): void {
if (TS.isPropertyAccessExpression(nodeToCheck)) {
if (TS.isIdentifier(nodeToCheck.expression)) {
if (isPropsObject(nodeToCheck.expression)) {
const nameToAdd = nodeToCheck.name.getText(sourceFile)
if (nameToAdd !== 'children') {
// Exclude children
pushToPropsUsedIfNotThere(nameToAdd)
}
}
} else {
addIfPropsUsed(nodeToCheck.expression)
}
} else if (TS.isCallExpression(nodeToCheck) || TS.isElementAccessExpression(nodeToCheck)) {
addIfPropsUsed(nodeToCheck.expression)
}
}
let parsedElementsWithin: ElementsWithinInPosition = []
let highlightBounds = existingHighlightBounds
function addToParsedElementsWithin(
currentScope: Array<string>,
node: TS.JsxElement | TS.JsxSelfClosingElement,
): void {
const parseResult = parseOutJSXElements(
sourceFile,
sourceText,
filename,
[node],
imports,
topLevelNames,
propsObjectName,
highlightBounds,
alreadyExistingUIDs,
)
forEachRight(parseResult, (success) => {
// Be conservative with this for the moment.
if (success.value.length === 1) {
const firstChild = success.value[0]
if (isJSXElement(firstChild.value)) {
const uid = getUtopiaIDFromJSXElement(firstChild.value)
parsedElementsWithin.push({
uid: uid,
element: firstChild.value,
startLine: firstChild.startLine - startLineShift,
startColumn:
firstChild.startLine - 1 === startLineShift
? firstChild.startColumn - startColumnShift
: firstChild.startColumn,
})
highlightBounds = success.highlightBounds
fastForEach(success.definedElsewhere, (val) =>
pushToDefinedElsewhereIfNotThere(currentScope, val),
)
}
}
})
}
function addToInScope(currentScope: Array<string>, node: TS.Node): Array<string> {
function addBindingElement(
currentScopeInner: Array<string>,
bindingElement: TS.BindingElement,
): Array<string> {
return addUniquely(currentScopeInner, bindingElement.name.getText(sourceFile))
}
function addBindingName(
currentScopeInner: Array<string>,
bindingName: TS.BindingName,
): Array<string> {
if (TS.isIdentifier(bindingName)) {
return addUniquely(currentScopeInner, bindingName.getText(sourceFile))
} else if (TS.isObjectBindingPattern(bindingName)) {
return bindingName.elements.reduce((working, element) => {
return addBindingName(working, element.name)
}, currentScopeInner)
} else {
// ArrayBindingPattern.
return bindingName.elements.reduce((working, element) => {
if (TS.isBindingElement(element)) {
return addBindingElement(working, element)
} else {
return working
}
}, currentScopeInner)
}
}
function addVariableStatement(
currentScopeInner: Array<string>,
statement: TS.VariableStatement,
): Array<string> {
return statement.declarationList.declarations.reduce((working, declaration) => {
return addBindingName(working, declaration.name)
}, currentScopeInner)
}
function addStatement(
currentScopeInner: Array<string>,
statement: TS.Statement,
): Array<string> {
if (TS.isFunctionLike(statement) && statement.name != null) {
return addUniquely(currentScopeInner, statement.name.getText(sourceFile))
} else if (TS.isVariableStatement(statement)) {
return addVariableStatement(currentScopeInner, statement)
} else {
return currentScopeInner
}
}
if (TS.isBlock(node)) {
return node.statements.reduce((working, statement) => {
return addStatement(working, statement)
}, currentScope)
} else if (TS.isFunctionLike(node)) {
return node.parameters.reduce(
(working, parameter) => addBindingName(working, parameter.name),
currentScope,
)
} else if (TS.isClassDeclaration(node)) {
return node.members.reduce((working, member) => {
if (member.name == null) {
return working
} else {
return addUniquely(working, member.name.getText(sourceFile))
}
}, currentScope)
} else if (TS.isCaseClause(node)) {
return node.statements.reduce((working, statement) => {
return addStatement(working, statement)
}, currentScope)
} else if (
TS.isForStatement(node) ||
TS.isForInStatement(node) ||
TS.isForOfStatement(node)
) {
if (node.initializer == null) {
return currentScope
} else {
if (TS.isVariableDeclarationList(node.initializer)) {
return node.initializer.declarations.reduce((working, declaration) => {
return addBindingName(working, declaration.name)
}, currentScope)
} else {
return currentScope
}
}
} else {
return currentScope
}
}
const transformer = (outermostScope: Array<string>) => {
return (context: TS.TransformationContext) => {
const walkTree = (insideJSXElement: boolean, scope: Array<string>) => {
return (node: TS.Node) => {
let innerInsideJSXElement = insideJSXElement
if (TS.isArrayLiteralExpression(node)) {
fastForEach(node.elements, (e) => addIfDefinedElsewhere(scope, e, false))
} else if (TS.isAsExpression(node)) {
addIfDefinedElsewhere(scope, node.expression, false)
} else if (TS.isAssertionExpression(node)) {
addIfDefinedElsewhere(scope, node.expression, false)
} else if (TS.isAwaitExpression(node)) {
addIfDefinedElsewhere(scope, node.expression, false)
} else if (TS.isBinaryExpression(node)) {
addIfDefinedElsewhere(scope, node.left, false)
addIfDefinedElsewhere(scope, node.right, false)
} else if (TS.isCallExpression(node)) {
addIfDefinedElsewhere(scope, node.expression, false)
fastForEach(node.arguments, (a) => addIfDefinedElsewhere(scope, a, false))
} else if (TS.isConditionalExpression(node)) {
addIfDefinedElsewhere(scope, node.condition, false)
addIfDefinedElsewhere(scope, node.whenTrue, false)
addIfDefinedElsewhere(scope, node.whenFalse, false)
} else if (TS.isDecorator(node)) {
addIfDefinedElsewhere(scope, node.expression, false)
} else if (TS.isDeleteExpression(node)) {
addIfDefinedElsewhere(scope, node.expression, false)
} else if (TS.isElementAccessExpression(node)) {
addIfDefinedElsewhere(scope, node.expression, false)
addIfDefinedElsewhere(scope, node.argumentExpression, false)
} else if (TS.isExpressionStatement(node)) {
addIfDefinedElsewhere(scope, node.expression, false)
} else if (TS.isJsxExpression(node)) {
// If there's some JSX, then it's implied we will transform this
// into code that will need React.
pushToDefinedElsewhereIfNotThere(scope, 'React')
if (node.expression != null) {
addIfDefinedElsewhere(scope, node.expression, false)
}
} else if (TS.isJsxElement(node)) {
// Since this function will also walk inside this element,
// prevent this from being reapplied within this element.
if (!innerInsideJSXElement) {
addToParsedElementsWithin(scope, node)
innerInsideJSXElement = true
}
// If there's some JSX, then it's implied we will transform this
// into code that will need React.
pushToDefinedElsewhereIfNotThere(scope, 'React')
addIfDefinedElsewhere(scope, node.openingElement.tagName, true)
} else if (TS.isJsxSelfClosingElement(node)) {
// Since this function will also walk inside this element,
// prevent this from being reapplied within this element.
if (!innerInsideJSXElement) {
addToParsedElementsWithin(scope, node)
innerInsideJSXElement = true
}
// If there's some JSX, then it's implied we will transform this
// into code that will need React.
pushToDefinedElsewhereIfNotThere(scope, 'React')
addIfDefinedElsewhere(scope, node.tagName, true)
} else if (TS.isJsxOpeningElement(node)) {
// If there's some JSX, then it's implied we will transform this
// into code that will need React.
pushToDefinedElsewhereIfNotThere(scope, 'React')
addIfDefinedElsewhere(scope, node.tagName, true)
} else if (TS.isNewExpression(node)) {
addIfDefinedElsewhere(scope, node.expression, false)
if (node.arguments != null) {
fastForEach(node.arguments, (a) => addIfDefinedElsewhere(scope, a, false))
}
} else if (TS.isNonNullExpression(node)) {
addIfDefinedElsewhere(scope, node.expression, false)
} else if (TS.isObjectLiteralExpression(node)) {
fastForEach(node.properties, (p) => addIfDefinedElsewhere(scope, p, false))
} else if (TS.isParenthesizedExpression(node)) {
addIfDefinedElsewhere(scope, node.expression, false)
} else if (TS.isPostfixUnaryExpression(node)) {
addIfDefinedElsewhere(scope, node.operand, false)
} else if (TS.isPrefixUnaryExpression(node)) {
addIfDefinedElsewhere(scope, node.operand, false)
} else if (TS.isPropertyAccessExpression(node)) {
// This is the one we want
const expressionDefinedElsewhere = addIfDefinedElsewhere(
scope,
node.expression,
false,
)
if (expressionDefinedElsewhere) {
addIfPropsUsed(node)
}
} else if (
TS.isSpreadAssignment(node) ||
TS.isSpreadElement(node) ||
TS.isJsxSpreadAttribute(node)
) {
addIfDefinedElsewhere(scope, node.expression, false)
} else if (TS.isTaggedTemplateExpression(node)) {
addIfDefinedElsewhere(scope, node, false)
} else if (TS.isTemplateExpression(node)) {
fastForEach(node.templateSpans, (s) =>
addIfDefinedElsewhere(scope, s.expression, false),
)
} else if (TS.isTypeOfExpression(node)) {
addIfDefinedElsewhere(scope, node.expression, false)
} else if (TS.isVariableDeclaration(node) && node.initializer != null) {
addIfDefinedElsewhere(scope, node.initializer, false)
} else if (TS.isVoidExpression(node)) {
addIfDefinedElsewhere(scope, node.expression, false)
} else if (TS.isYieldExpression(node)) {
if (node.expression != null) {
addIfDefinedElsewhere(scope, node.expression, false)
}
}
const newScope = addToInScope(scope, node)
TS.visitEachChild(node, walkTree(innerInsideJSXElement, newScope), context)
return node
}
}
return (n: TS.Node) => TS.visitNode(n, walkTree(false, outermostScope))
}
}
let expressionsText: Array<string> = []
let expressionsNodes: Array<typeof SourceNode> = []
for (const expressionAndText of expressionsAndTexts) {
// Update the code offsets used when locating elements within
const startPosition = TS.getLineAndCharacterOfPosition(sourceFile, expressionAndText.startPos)
const endPosition = TS.getLineAndCharacterOfPosition(sourceFile, expressionAndText.endPos)
const shiftedBlockStartLine = startPosition.line - lastBlockEndLine
const column = startPosition.character - 1
if (shiftedBlockStartLine > 0) {
startLineShift += shiftedBlockStartLine
}
startColumnShift = column
lastBlockEndLine = endPosition.line
const expression = expressionAndText.expression
if (expression != null) {
addIfDefinedElsewhere([], expression, false)
const expressionText = expressionAndText.text
if (expressionText.length > 0) {
const { line, character } = TS.getLineAndCharacterOfPosition(
sourceFile,
expressionAndText.startPos,
)
const expressionNode = turnCodeSnippetIntoSourceMapNodes(
sourceFile.fileName,
line,
character,
expressionAndText.text,
isExported(expression),
)
expressionsNodes.push(expressionNode)
}
expressionsText.push(expressionText)
if (TS.isFunctionLike(expression)) {
if (expression.name != null) {
pushToDefinedWithinIfNotThere(expression.name.getText(sourceFile))
}
} else if (TS.isVariableStatement(expression)) {
for (const declaration of expression.declarationList.declarations) {
addBindingNameToDefinedWithin(declaration.name)
}
} else if (TS.isClassDeclaration(expression)) {
if (expression.name != null) {
pushToDefinedWithinIfNotThere(expression.name.getText(sourceFile))
}
}
TS.transform(expression, [transformer(definedWithin)])
}
}
expressionsText.push(trailingCode)
// Helpfully it appears that in JSX elements the start and end are
// offset by 1, meaning that if we use them to get the text
// the string is total nonsense.
const code = expressionsText.join('')
const fileNode = new SourceNode(null, null, sourceFile.fileName, expressionsNodes)
fileNode.setSourceContent(sourceFile.fileName, sourceFile.text)
// Filter definedElsewhere to exclude anything in definedWithin as for example
// one arbitrary block may use something from another arbitrary block in the
// same chunk of arbitrary nodes.
definedElsewhere = definedElsewhere.filter((e) => {
return !definedWithin.includes(e)
})
// Filter propsUsed to exclude anything in definedWithin as for example
// one arbitrary block may use something from another arbitrary block in the
// same chunk of arbitrary nodes.
propsUsed = propsUsed.filter((e) => {
return !definedWithin.includes(e)
})
return mapEither(
(created) => withParserMetadata(created, highlightBounds, propsUsed, definedElsewhere),
create(code, definedWithin, definedElsewhere, fileNode, parsedElementsWithin),
)
}
}
export function parseAttributeOtherJavaScript(
sourceFile: TS.SourceFile,
sourceText: string,
filename: string,
imports: Imports,
topLevelNames: Array<string>,
propsObjectName: string | null,
expression: TS.Node,
existingHighlightBounds: Readonly<HighlightBoundsForUids>,
alreadyExistingUIDs: Set<string>,
): Either<string, WithParserMetadata<JSXAttributeOtherJavaScript>> {
const expressionAndText = createExpressionAndText(
expression,
expression.getText(sourceFile),
expression.getStart(sourceFile, false),
expression.getEnd(),
)
return parseOtherJavaScript(
sourceFile,
sourceText,
filename,
[expressionAndText],
imports,
topLevelNames,
propsObjectName,
existingHighlightBounds,
alreadyExistingUIDs,
'',
(code, _, definedElsewhere, fileSourceNode, parsedElementsWithin) => {
const { code: codeFromFile, map } = fileSourceNode.toStringWithSourceMap({ file: filename })
const rawMap = JSON.parse(map.toString())
const transpileEither = transpileJavascriptFromCode(
sourceFile.fileName,
sourceFile.text,
codeFromFile,
rawMap,
parsedElementsWithin,
true,
)
return mapEither((transpileResult) => {
const prependedWithReturn = prependToSourceString(
sourceFile.fileName,
sourceFile.text,
transpileResult.code,
transpileResult.sourceMap,
RETURN_TO_PREPEND,
'',
)
// Sneak the function in here if something needs to use it to display
// the element on the canvas.
let innerDefinedElsewhere = definedElsewhere
if (Object.keys(parsedElementsWithin).length > 0) {
innerDefinedElsewhere = [...innerDefinedElsewhere, JSX_CANVAS_LOOKUP_FUNCTION_NAME]
}
return jsxAttributeOtherJavaScript(
code,
prependedWithReturn.code,
innerDefinedElsewhere,
prependedWithReturn.sourceMap,
inPositionToElementsWithin(parsedElementsWithin),
)
}, transpileEither)
},
)
}
function parseJSXArbitraryBlock(
sourceFile: TS.SourceFile,
sourceText: string,
filename: string,
imports: Imports,
topLevelNames: Array<string>,
propsObjectName: string | null,
jsxExpression: TS.JsxExpression,
existingHighlightBounds: Readonly<HighlightBoundsForUids>,
alreadyExistingUIDs: Set<string>,
): Either<string, WithParserMetadata<JSXArbitraryBlock>> {
// Remove the braces around the expression
const expressionFullText = jsxExpression.getFullText(sourceFile).slice(1, -1)
const expressionAndText = createExpressionAndText(
jsxExpression.expression,
expressionFullText,
jsxExpression.getFullStart() + 1,
jsxExpression.getEnd() + 2,
)
return parseOtherJavaScript(
sourceFile,
sourceText,
filename,
[expressionAndText],
imports,
topLevelNames,
propsObjectName,
existingHighlightBounds,
alreadyExistingUIDs,
'',
(code, _definedWithin, definedElsewhere, _fileSourceNode, parsedElementsWithin) => {
if (code === '') {
return right(
jsxArbitraryBlock(
expressionFullText,
expressionFullText,
'return undefined',
definedElsewhere,
null,
inPositionToElementsWithin(parsedElementsWithin),
),
)
} else {
const dataUIDFixed = insertDataUIDsIntoCode(
expressionFullText,
parsedElementsWithin,
true,
false,
sourceFile.fileName,
)
return flatMapEither((dataUIDFixResult) => {
const transpileEither = transpileJavascriptFromCode(
sourceFile.fileName,
sourceFile.text,
dataUIDFixResult.code,
dataUIDFixResult.sourceMap,
parsedElementsWithin,
true,
)
return mapEither((transpileResult) => {
const returnPrepended = prependToSourceString(
sourceFile.fileName,
sourceFile.text,
transpileResult.code,
transpileResult.sourceMap,
RETURN_TO_PREPEND,
'',
)
// Sneak the function in here if something needs to use it to display
// the element on the canvas.
let innerDefinedElsewhere = definedElsewhere
if (Object.keys(parsedElementsWithin).length > 0) {
innerDefinedElsewhere = [...innerDefinedElsewhere, JSX_CANVAS_LOOKUP_FUNCTION_NAME]
}
return jsxArbitraryBlock(
expressionFullText,
dataUIDFixResult.code,
returnPrepended.code,
innerDefinedElsewhere,
returnPrepended.sourceMap,
inPositionToElementsWithin(parsedElementsWithin),
)
}, transpileEither)
}, dataUIDFixed)
}
},
)
}
export function parseAttributeExpression(
sourceFile: TS.SourceFile,
sourceText: string,
filename: string,
imports: Imports,
topLevelNames: Array<string>,
propsObjectName: string | null,
expression: TS.Expression,
existingHighlightBounds: Readonly<HighlightBoundsForUids>,
alreadyExistingUIDs: Set<string>,
trailingCommentsFromPriorToken: Array<Comment>,
): Either<string, WithParserMetadata<JSXAttribute>> {
let comments = getComments(sourceText, expression)
if (trailingCommentsFromPriorToken.length > 0) {
comments = parsedComments(
[...trailingCommentsFromPriorToken, ...comments.leadingComments],
comments.trailingComments,
)
}
if (TS.isArrayLiteralExpression(expression)) {
return parseArrayLiteralExpression(
sourceFile,
sourceText,
filename,
imports,
topLevelNames,
propsObjectName,
expression,
existingHighlightBounds,
alreadyExistingUIDs,
)
} else if (TS.isCallExpression(expression)) {
// Parse the case that an attribute invokes a special case function.
// Then we parse out the parameters passed to the function.
// Commented out as the style of this is likely to be re-used but we're not using it right now.
if (TS.isPropertyAccessExpression(expression.expression)) {
// if (TS.isIdentifier(expression.expression)) {
const propertyAccess = expression.expression
const leftHandSide = propertyAccess.expression
const identifier = propertyAccess.name
if (leftHandSide.getText(sourceFile) === 'UtopiaUtils') {
let highlightBounds = existingHighlightBounds
let parsedArgumentAttributes: Array<JSXAttribute> = []
let propsUsed: Array<string> = []
let definedElsewhere: Array<string> = []
for (const argument of expression.arguments) {
const parsedArgument = parseAttributeExpression(
sourceFile,
sourceText,
filename,
imports,
topLevelNames,
propsObjectName,
argument,
highlightBounds,
alreadyExistingUIDs,
[],
)
if (isLeft(parsedArgument)) {
return left(`Error parsing function expression: ${parsedArgument.value}`)
} else {
parsedArgumentAttributes.push(parsedArgument.value.value)
highlightBounds = parsedArgument.value.highlightBounds
propsUsed.push(...parsedArgument.value.propsUsed)
definedElsewhere.push(...parsedArgument.value.definedElsewhere)
}
}
return right(
withParserMetadata(
jsxAttributeFunctionCall(identifier.getText(sourceFile), parsedArgumentAttributes),
highlightBounds,
propsUsed,
definedElsewhere,
),
)
}
}
return parseAttributeOtherJavaScript(
sourceFile,
sourceText,
filename,
imports,
topLevelNames,
propsObjectName,
expression,
existingHighlightBounds,
alreadyExistingUIDs,
)
} else if (
TS.isElementAccessExpression(expression) ||
TS.isPropertyAccessExpression(expression)
) {
return parseAttributeOtherJavaScript(
sourceFile,
sourceText,
filename,
imports,
topLevelNames,
propsObjectName,
expression,
existingHighlightBounds,
alreadyExistingUIDs,
)
} else if (
TS.isIdentifier(expression) &&
expression.originalKeywordKind === TS.SyntaxKind.UndefinedKeyword
) {
return right(
withParserMetadata(jsxAttributeValue(undefined, comments), existingHighlightBounds, [], []),
)
} else if (TS.isNumericLiteral(expression)) {
return right(
withParserMetadata(
jsxAttributeValue(Number.parseFloat(expression.getText(sourceFile)), comments),
existingHighlightBounds,
[],
[],
),
)
} else if (TS.isObjectLiteralExpression(expression)) {
return parseObjectLiteralExpression(
sourceFile,
sourceText,
filename,
imports,
topLevelNames,
propsObjectName,
expression,
existingHighlightBounds,
alreadyExistingUIDs,
)
} else if (TS.isPrefixUnaryExpression(expression)) {
// Cater for negative numbers, because of course they're done in a weird way.
const operator = expression.operator
if (operator === TS.SyntaxKind.MinusToken) {
const operand = expression.operand
if (TS.isNumericLiteral(operand)) {
return right(
withParserMetadata(
jsxAttributeValue(Number.parseFloat(operand.getText(sourceFile)) * -1, comments),
existingHighlightBounds,
[],
[],
),
)
}
}
return parseAttributeOtherJavaScript(
sourceFile,
sourceText,
filename,
imports,
topLevelNames,
propsObjectName,
expression,
existingHighlightBounds,
alreadyExistingUIDs,
)
} else if (TS.isStringLiteral(expression)) {
return right(
withParserMetadata(
jsxAttributeValue(expression.text, comments),
existingHighlightBounds,
[],
[],
),
)
} else {
switch (expression.kind) {
case TS.SyntaxKind.TrueKeyword:
return right(
withParserMetadata(jsxAttributeValue(true, comments), existingHighlightBounds, [], []),
)
case TS.SyntaxKind.FalseKeyword:
return right(
withParserMetadata(jsxAttributeValue(false, comments), existingHighlightBounds, [], []),
)
case TS.SyntaxKind.NullKeyword:
return right(
withParserMetadata(jsxAttributeValue(null, comments), existingHighlightBounds, [], []),
)
default:
return parseAttributeOtherJavaScript(
sourceFile,
sourceText,
filename,
imports,
topLevelNames,
propsObjectName,
expression,
existingHighlightBounds,
alreadyExistingUIDs,
)
}
}
}
function getAttributeExpression(
sourceFile: TS.SourceFile,
sourceText: string,
filename: string,
imports: Imports,
topLevelNames: Array<string>,
propsObjectName: string | null,
initializer: TS.StringLiteral | TS.JsxExpression,
existingHighlightBounds: Readonly<HighlightBoundsForUids>,
alreadyExistingUIDs: Set<string>,
): Either<string, WithParserMetadata<JSXAttribute>> {
if (TS.isStringLiteral(initializer)) {
const comments = getComments(sourceText, initializer)
return right(
withParserMetadata(
jsxAttributeValue(initializer.text, comments),
existingHighlightBounds,
[],
[],
),
)
} else if (TS.isJsxExpression(initializer)) {
// Need to handle trailing comments on the open brace,
// passing them down to be the handled elsewhere.
let openBraceComments: ParsedComments = emptyComments
const firstChild = initializer.getChildAt(0, sourceFile)
if (firstChild != null && firstChild.kind === TS.SyntaxKind.OpenBraceToken) {
openBraceComments = getComments(sourceText, firstChild)
}
// Handle the expression itself.
if (initializer.expression == null) {
return right(
withParserMetadata(
jsxAttributeOtherJavaScript('null', 'null', [], null, {}),
existingHighlightBounds,
[],
[],
),
)
} else {
return parseAttributeExpression(
sourceFile,
sourceText,
filename,
imports,
topLevelNames,
propsObjectName,
initializer.expression,
existingHighlightBounds,
alreadyExistingUIDs,
openBraceComments.trailingComments,
)
}
} else {
throw new Error(`Unhandled initializer case: ${initializer}`)
}
}
function parseElementProps(
sourceFile: TS.SourceFile,
sourceText: string,
filename: string,
imports: Imports,
topLevelNames: Array<string>,
propsObjectName: string | null,
attributes: TS.JsxAttributes,
existingHighlightBounds: Readonly<HighlightBoundsForUids>,
alreadyExistingUIDs: Set<string>,
leadingCommentsAgainstClosingToken: Array<Comment>,
): Either<string, WithParserMetadata<JSXAttributes>> {
let result: JSXAttributes = []
let highlightBounds = existingHighlightBounds
let propsUsed = []
let definedElsewhere = []
// Maintain this so that we can still use early returns.
let propIndex: number = 0
for (const prop of attributes.properties) {
let propComments = getComments(sourceText, prop)
if (propIndex === attributes.properties.length - 1) {
propComments = parsedComments(propComments.leadingComments, [
...propComments.trailingComments,
...leadingCommentsAgainstClosingToken,
])
}
if (TS.isJsxSpreadAttribute(prop)) {
const attributeResult = parseAttributeExpression(
sourceFile,
sourceText,
filename,
imports,
topLevelNames,
propsObjectName,
prop.expression,
highlightBounds,
alreadyExistingUIDs,
[],
)
if (isLeft(attributeResult)) {
return attributeResult
} else {
result.push(
jsxAttributesSpread(
simplifyAttributeIfPossible(attributeResult.value.value),
propComments,
),
)
highlightBounds = attributeResult.value.highlightBounds
propsUsed.push(...attributeResult.value.propsUsed)
definedElsewhere.push(...attributeResult.value.definedElsewhere)
}
} else if (TS.isJsxAttribute(prop)) {
if (prop.initializer == null) {
result.push(
jsxAttributesEntry(
prop.name.getText(sourceFile),
jsxAttributeValue(true, emptyComments),
propComments,
),
)
} else {
const attributeResult = getAttributeExpression(
sourceFile,
sourceText,
filename,
imports,
topLevelNames,
propsObjectName,
prop.initializer,
highlightBounds,
alreadyExistingUIDs,
)
if (isLeft(attributeResult)) {
return attributeResult
} else {
result.push(
jsxAttributesEntry(
prop.name.getText(sourceFile),
simplifyAttributeIfPossible(attributeResult.value.value),
propComments,
),
)
highlightBounds = attributeResult.value.highlightBounds
propsUsed.push(...attributeResult.value.propsUsed)
definedElsewhere.push(...attributeResult.value.definedElsewhere)
}
}
} else {
return left(`Invalid attribute found.`)
}
propIndex += 1
}
return right(withParserMetadata(result, highlightBounds, propsUsed, definedElsewhere))
}
type TSTextOrExpression = TS.JsxText | TS.JsxExpression
type TSJSXElement = TS.JsxElement | TS.JsxSelfClosingElement
type ElementsToParse = Array<
TSJSXElement | TSTextOrExpression | TS.JsxOpeningFragment | TS.JsxClosingFragment | TS.JsxFragment
>
function pullOutElementsToParse(nodes: Array<TS.Node>): Either<string, ElementsToParse> {
let result: ElementsToParse = []
for (let index = 0; index < nodes.length; index++) {
const node = nodes[index]
if (
TS.isJsxElement(node) ||
TS.isJsxSelfClosingElement(node) ||
TS.isJsxText(node) ||
TS.isJsxExpression(node) ||
TS.isJsxFragment(node)
) {
result.push(node)
} else {
return left(`Invalid content in JSX.`)
}
}
return right(result)
}
export interface WithParserMetadata<T> {
value: T
highlightBounds: Readonly<HighlightBoundsForUids>
propsUsed: Array<string>
definedElsewhere: Array<string>
}
interface SuccessfullyParsedElement {
value: JSXElementChild
startLine: number
startColumn: number
}
function successfullyParsedElement(
sourceFile: TS.SourceFile,
originatingElement: TS.Node,
value: JSXElementChild,
): SuccessfullyParsedElement {
const startPosition = TS.getLineAndCharacterOfPosition(
sourceFile,
originatingElement.getStart(sourceFile, false),
)
return {
value: value,
startLine: startPosition.line,
startColumn: startPosition.character,
}
}
export function withParserMetadata<T>(
value: T,
highlightBounds: Readonly<HighlightBoundsForUids>,
propsUsed: Array<string>,
definedElsewhere: Array<string>,
): WithParserMetadata<T> {
return {
value: value,
highlightBounds: highlightBounds,
propsUsed: propsUsed,
definedElsewhere: definedElsewhere,
}
}
type ParseElementsResult = Either<string, WithParserMetadata<Array<SuccessfullyParsedElement>>>
function isSpacingTextBlock(element: JSXElementChild): boolean {
if (isJSXTextBlock(element)) {
return element.text.trim().length === 0
} else {
return false
}
}
function neighbourCandidateForIgnoring(element: SuccessfullyParsedElement | undefined): boolean {
return element === undefined || isJSXElement(element.value) || isJSXArbitraryBlock(element.value)
}
function clearUnnecessarySpacingElements(
elements: Array<SuccessfullyParsedElement>,
): Array<SuccessfullyParsedElement> {
let result: Array<SuccessfullyParsedElement> = []
for (let index = 0; index < elements.length; index++) {
const element = elements[index]
let includeElement: boolean = true
if (isSpacingTextBlock(element.value)) {
const onLeft = elements[index - 1]
const onRight = elements[index + 1]
if (neighbourCandidateForIgnoring(onLeft) && neighbourCandidateForIgnoring(onRight)) {
includeElement = false
}
}
if (includeElement) {
result.push(element)
}
}
return result
}
function parseJSXElementName(
sourceFile: TS.SourceFile,
tagName: TS.JsxTagNameExpression,
): Either<string, JSXElementName> {
if (TS.isIdentifier(tagName)) {
return right(jsxElementName(tagName.getText(sourceFile), []))
} else if (TS.isPropertyAccessExpression(tagName)) {
let expressionParts: Array<string> = []
function walkTree(expr: TS.JsxTagNameExpression | TS.PrivateIdentifier): void {
if (TS.isIdentifier(expr)) {
expressionParts.push(expr.getText(sourceFile))
} else if (TS.isPropertyAccessExpression(expr)) {
walkTree(expr.expression)
walkTree(expr.name)
}
}
walkTree(tagName)
if (expressionParts.length === 0) {
return left('Unable to parse JSX property access.')
} else {
const [baseVariable, ...remainder] = expressionParts
return right(jsxElementName(baseVariable, remainder))
}
} else {
return left('Unable to handle ThisExpression.')
}
}
function buildHighlightBounds(
sourceFile: TS.SourceFile,
boundingElement: TS.Node,
uid: string,
): HighlightBounds {
const startPosition = TS.getLineAndCharacterOfPosition(
sourceFile,
boundingElement.getStart(sourceFile, false),
)
const endPosition = TS.getLineAndCharacterOfPosition(sourceFile, boundingElement.getEnd())
return {
startCol: startPosition.character,
startLine: startPosition.line,
endCol: endPosition.character,
endLine: endPosition.line,
uid: uid,
}
}
interface UpdateUIDResult {
uid: string
attributes: WithParserMetadata<JSXAttributes>
}
function forciblyUpdateDataUID(
sourceFile: TS.SourceFile,
originatingElement: TS.Node,
name: JSXElementName | string,
props: JSXAttributes,
existingHighlightBounds: Readonly<HighlightBoundsForUids>,
alreadyExistingUIDs: Set<string>,
): UpdateUIDResult {
const hash = Hash({
fileName: sourceFile.fileName,
name: name,
props: clearAttributesSourceMaps(clearAttributesUniqueIDs(props)),
})
const uid = generateConsistentUID(alreadyExistingUIDs, hash)
alreadyExistingUIDs.add(uid)
const updatedProps = setJSXAttributesAttribute(
props,
'data-uid',
jsxAttributeValue(uid, emptyComments),
)
return {
uid: uid,
attributes: withParserMetadata(
updatedProps,
{
...existingHighlightBounds,
[uid]: buildHighlightBounds(sourceFile, originatingElement, uid),
},
[],
[],
),
}
}
function createJSXElementAllocatingUID(
sourceFile: TS.SourceFile,
originatingElement: TS.Node,
name: JSXElementName | string,
props: JSXAttributes,
children: JSXElementChildren,
existingHighlightBounds: Readonly<HighlightBoundsForUids>,
alreadyExistingUIDs: Set<string>,
): WithParserMetadata<SuccessfullyParsedElement> {
const dataUIDAttribute = parseUID(props)
const { uid: newUID, attributes: updatedProps } = foldEither(
(_) =>
forciblyUpdateDataUID(
sourceFile,
originatingElement,
name,
props,
existingHighlightBounds,
alreadyExistingUIDs,
),
(uid) => {
// This implies a duplicate UID, so we should replace it.
if (uid in existingHighlightBounds || alreadyExistingUIDs.has(uid)) {
return forciblyUpdateDataUID(
sourceFile,
originatingElement,
name,
props,
existingHighlightBounds,
alreadyExistingUIDs,
)
} else {
alreadyExistingUIDs.add(uid)
return {
uid: uid,
attributes: withParserMetadata(
props,
{
...existingHighlightBounds,
[uid]: buildHighlightBounds(sourceFile, originatingElement, uid),
},
[],
[],
),
}
}
},
dataUIDAttribute,
)
const startPosition = TS.getLineAndCharacterOfPosition(
sourceFile,
originatingElement.getStart(sourceFile, false),
)
return withParserMetadata(
{
value: jsxElement(name, newUID, updatedProps.value, children),
startLine: startPosition.line,
startColumn: startPosition.character,
},
updatedProps.highlightBounds,
[],
[],
)
}
export function parseOutJSXElements(
sourceFile: TS.SourceFile,
sourceText: string,
filename: string,
nodesToParse: Array<TS.Node>,
imports: Imports,
topLevelNames: Array<string>,
propsObjectName: string | null,
existingHighlightBounds: Readonly<HighlightBoundsForUids>,
alreadyExistingUIDs: Set<string>,
): ParseElementsResult {
let highlightBounds = existingHighlightBounds
let propsUsed: Array<string> = []
let definedElsewhere: Array<string> = []
function innerParse(nodes: Array<TS.Node>): Either<string, Array<SuccessfullyParsedElement>> {
// First parse to extract the nodes we really want into a sensible form
// and fail if there's anything unexpected.
return flatMapEither((toParse) => {
// Handle the two different cases of either an element or a bunch of JSX inner content.
let parsedNodes: Array<SuccessfullyParsedElement> = []
let fragmentDepth: number = 0
let fragmentChildren: { [key: number]: Array<JSXElementChild> } = {}
let fragmentStart: { [key: number]: TS.JsxOpeningFragment } = {}
function addParsedElement(addElement: SuccessfullyParsedElement): void {
if (fragmentDepth === 0) {
parsedNodes.push(addElement)
} else {
let fragmentArray: Array<JSXElementChild> = fragmentChildren[fragmentDepth]
if (fragmentArray == null) {
fragmentArray = [addElement.value]
fragmentChildren[fragmentDepth] = fragmentArray
} else {
fragmentArray.push(addElement.value)
}
}
}
for (const elem of toParse) {
switch (elem.kind) {
case TS.SyntaxKind.JsxFragment: {
const possibleFragment = produceFragmentFromJsxFragment(elem)
if (isLeft(possibleFragment)) {
return possibleFragment
} else {
addParsedElement(possibleFragment.value)
}
break
}
case TS.SyntaxKind.JsxElement: {
const possibleElement = produceElementFromTSElement(elem)
if (isLeft(possibleElement)) {
return possibleElement
} else {
const parsedElement = possibleElement.value.value
if (isJSXElement(parsedElement) && isReactFragmentName(parsedElement.name, imports)) {
addParsedElement({
...possibleElement.value,
value: jsxFragment(parsedElement.children, true),
})
} else {
addParsedElement(possibleElement.value)
}
}
break
}
case TS.SyntaxKind.JsxSelfClosingElement: {
const possibleElement = produceElementFromTSElement(elem)
if (isLeft(possibleElement)) {
return possibleElement
} else {
const parsedElement = possibleElement.value.value
if (isJSXElement(parsedElement) && isReactFragmentName(parsedElement.name, imports)) {
addParsedElement({
...possibleElement.value,
value: jsxFragment(parsedElement.children, true),
})
} else {
addParsedElement(possibleElement.value)
}
}
break
}
case TS.SyntaxKind.JsxExpression: {
const possibleExpression = produceArbitraryBlockFromJsxExpression(elem)
if (isLeft(possibleExpression)) {
return possibleExpression
} else {
addParsedElement(possibleExpression.value)
}
break
}
case TS.SyntaxKind.JsxText: {
const possibleText = produceTextFromJsxText(elem)
if (isLeft(possibleText)) {
return possibleText
} else {
addParsedElement(possibleText.value)
}
break
}
case TS.SyntaxKind.JsxOpeningFragment: {
fragmentDepth += 1
fragmentStart[fragmentDepth] = elem
break
}
case TS.SyntaxKind.JsxClosingFragment: {
if (fragmentDepth === 0) {
return left('Too many closed fragments.')
} else {
const childrenOfFragment: Array<JSXElementChild> =
fragmentChildren[fragmentDepth] ?? []
const start = forceNotNull(
'Fragment start should exist.',
fragmentStart[fragmentDepth],
)
delete fragmentChildren[fragmentDepth]
delete fragmentStart[fragmentDepth]
fragmentDepth -= 1
addParsedElement(
successfullyParsedElement(
sourceFile,
start,
jsxFragment(childrenOfFragment, false),
),
)
}
break
}
default:
const _exhaustiveCheck: never = elem
throw new Error(`Unhandled elem type ${JSON.stringify(elem)}`)
}
}
if (fragmentDepth === 0) {
return right(clearUnnecessarySpacingElements(parsedNodes))
} else {
return left('Not enough closed fragments.')
}
}, pullOutElementsToParse(nodes))
}
function produceFragmentFromJsxFragment(
fragment: TS.JsxFragment,
): Either<string, SuccessfullyParsedElement> {
// Parse the children.
const parsedChildren = mapEither((children) => {
return children.map((c) => c.value)
}, innerParse(nodeArrayToArray(fragment.children)))
// Create the containing fragment.
return mapEither((children) => {
return successfullyParsedElement(sourceFile, fragment, jsxFragment(children, false))
}, parsedChildren)
}
function produceTextFromJsxText(tsText: TS.JsxText): Either<string, SuccessfullyParsedElement> {
return right(successfullyParsedElement(sourceFile, tsText, jsxTextBlock(tsText.text)))
}
function produceArbitraryBlockFromJsxExpression(
tsExpression: TS.JsxExpression,
): Either<string, SuccessfullyParsedElement> {
const result = parseJSXArbitraryBlock(
sourceFile,
sourceText,
filename,
imports,
topLevelNames,
propsObjectName,
tsExpression,
highlightBounds,
alreadyExistingUIDs,
)
return bimapEither(
(failure) => failure,
(success) => {
highlightBounds = success.highlightBounds
propsUsed.push(...success.propsUsed)
definedElsewhere.push(...success.definedElsewhere)
return successfullyParsedElement(sourceFile, tsExpression, success.value)
},
result,
)
}
function produceElementFromTSElement(
tsElement: TSJSXElement,
): Either<string, SuccessfullyParsedElement> {
let attributes: TS.JsxAttributes
let tagName: TS.JsxTagNameExpression
let children: Either<string, Array<JSXElementChild>> = right([])
let commentsFromAfterAttributes: ParsedComments = emptyComments
switch (tsElement.kind) {
case TS.SyntaxKind.JsxElement:
attributes = tsElement.openingElement.attributes
tagName = tsElement.openingElement.tagName
// Parse the children.
children = mapEither((parsedChildren) => {
return parsedChildren.map((c) => c.value)
}, innerParse(nodeArrayToArray(tsElement.children)))
// Capture comments against '>' as that should follow the attributes.
tsElement.openingElement.getChildren(sourceFile).forEach((child) => {
if (child.kind === TS.SyntaxKind.GreaterThanToken) {
commentsFromAfterAttributes = getComments(sourceText, child)
}
})
break
case TS.SyntaxKind.JsxSelfClosingElement:
attributes = tsElement.attributes
tagName = tsElement.tagName
// Capture comments against '/' as that should follow the attributes.
tsElement.getChildren(sourceFile).forEach((child) => {
if (child.kind === TS.SyntaxKind.SlashToken) {
commentsFromAfterAttributes = getComments(sourceText, child)
}
})
break
default:
const _exhaustiveCheck: never = tsElement
throw new Error(`Unhandled element type ${JSON.stringify(tsElement)}`)
}
return flatMapEither((childElems) => {
// Attributes of the current element.
const parsedAttributes = parseElementProps(
sourceFile,
sourceText,
filename,
imports,
topLevelNames,
propsObjectName,
attributes,
highlightBounds,
alreadyExistingUIDs,
commentsFromAfterAttributes.leadingComments,
)
// Construct the element.
return flatMapEither((attrs) => {
highlightBounds = attrs.highlightBounds
propsUsed.push(...attrs.propsUsed)
definedElsewhere.push(...attrs.definedElsewhere)
return flatMapEither((elementName) => {
if (isJsxNameKnown(elementName, topLevelNames, imports)) {
const parsedElement = createJSXElementAllocatingUID(
sourceFile,
tsElement,
elementName,
attrs.value,
childElems,
highlightBounds,
alreadyExistingUIDs,
)
highlightBounds = parsedElement.highlightBounds
return right(parsedElement.value)
} else {
return left(`Unknown JSX element name: ${JSON.stringify(elementName)}`)
}
}, parseJSXElementName(sourceFile, tagName))
}, parsedAttributes)
}, children)
}
const flattened = flatMapArray(
(nodeToParse) => flattenOutAnnoyingContainers(sourceFile, nodeToParse),
nodesToParse,
)
let result: Either<string, Array<SuccessfullyParsedElement>>
if (flattened.length === 0) {
result = innerParse(nodesToParse)
} else {
result = innerParse(flattened)
}
return mapEither((elements) => {
return withParserMetadata(elements, highlightBounds, propsUsed, definedElsewhere)
}, result)
}
export const CanvasMetadataName = 'canvasMetadata'
function isJsxNameKnown(
name: JSXElementName,
knownElements: Array<string>,
imports: Imports,
): boolean {
if (isIntrinsicElement(name)) {
return true
} else {
const importsArray = Object.values(imports)
const knownImportedNames = stripNulls(
flatMapArray(
(imp) => [
imp.importedWithName,
imp.importedAs,
...imp.importedFromWithin.map((i) => i.alias),
],
importsArray,
),
)
const knownNames = knownElements.concat(knownImportedNames as string[])
const result = knownNames.includes(name.baseVariable)
return result
}
}
function isReactFragmentName(name: JSXElementName, imports: Imports): boolean {
const possibleReactImport = imports['react']
if (possibleReactImport == null) {
return false
} else {
if (possibleReactImport.importedAs != null) {
if (
jsxElementNameEquals(name, jsxElementName(possibleReactImport.importedAs, ['Fragment']))
) {
return true
}
}
if (possibleReactImport.importedWithName != null) {
if (
jsxElementNameEquals(
name,
jsxElementName(possibleReactImport.importedWithName, ['Fragment']),
)
) {
return true
}
}
const fromWithin = possibleReactImport.importedFromWithin.find(
(within) => within.name === 'Fragment',
)
if (fromWithin != null) {
if (jsxElementNameEquals(name, jsxElementName(fromWithin.alias, []))) {
return true
}
}
return false
}
}
export function flattenOutAnnoyingContainers(
sourceFile: TS.SourceFile,
node: TS.Node,
): Array<TS.Node> {
let nodesToReturn: Array<TS.Node> = []
if (node.kind === TS.SyntaxKind.SyntaxList || node.kind === TS.SyntaxKind.Block) {
nodesToReturn = node.getChildren(sourceFile)
} else if (TS.isParenthesizedExpression(node)) {
nodesToReturn = [node.expression]
} else if (TS.isReturnStatement(node)) {
nodesToReturn = maybeToArray(node.expression)
} else if (TS.isNewExpression(node)) {
nodesToReturn = [node.expression]
} else {
// Escape out here.
return [node]
}
return flatMapArray(
(nodeToReturn) => flattenOutAnnoyingContainers(sourceFile, nodeToReturn),
nodesToReturn,
)
}
export function parseArbitraryNodes(
sourceFile: TS.SourceFile,
sourceText: string,
filename: string,
arbitraryNodes: Array<TS.Node>,
imports: Imports,
topLevelNames: Array<string>,
propsObjectName: string | null,
existingHighlightBounds: Readonly<HighlightBoundsForUids>,
alreadyExistingUIDs: Set<string>,
rootLevel: boolean,
trailingCode: string,
useFullText: boolean,
): Either<string, WithParserMetadata<ArbitraryJSBlock>> {
const expressionsAndTexts = arbitraryNodes.map((node) => {
return createExpressionAndText(
node,
useFullText ? node.getFullText(sourceFile) : node.getText(sourceFile),
useFullText ? node.getFullStart() : node.getStart(sourceFile, false),
node.getEnd(),
)
})
return parseOtherJavaScript(
sourceFile,
sourceText,
filename,
expressionsAndTexts,
imports,
topLevelNames,
propsObjectName,
existingHighlightBounds,
alreadyExistingUIDs,
trailingCode,
(code, definedWithin, definedElsewhere, fileSourceNode, parsedElementsWithin) => {
const definedWithinFields = definedWithin.map((within) => `${within}: ${within}`).join(', ')
const definedWithCode = `return { ${definedWithinFields} };`
const transpileEither = transpileJavascript(
sourceFile.fileName,
sourceFile.text,
fileSourceNode,
parsedElementsWithin,
false,
)
const dataUIDFixed = insertDataUIDsIntoCode(
code,
parsedElementsWithin,
false,
rootLevel,
sourceFile.fileName,
)
return applicative2Either(
(transpileResult, dataUIDFixResult) => {
const transpiled = `${transpileResult.code}\n${definedWithCode}`
return arbitraryJSBlock(
code,
transpiled,
definedWithin,
[...definedElsewhere, JSX_CANVAS_LOOKUP_FUNCTION_NAME],
transpileResult.sourceMap,
inPositionToElementsWithin(parsedElementsWithin),
)
},
transpileEither,
dataUIDFixed,
)
},
)
}
export interface FunctionContents {
arbitraryJSBlock: ArbitraryJSBlock | null
blockOrExpression: BlockOrExpression
elements: Array<SuccessfullyParsedElement>
returnStatementComments: ParsedComments
}
function functionContents(
jsBlock: ArbitraryJSBlock | null,
blockOrExpression: BlockOrExpression,
elements: Array<SuccessfullyParsedElement>,
returnStatementComments: ParsedComments,
): FunctionContents {
return {
arbitraryJSBlock: jsBlock,
blockOrExpression: blockOrExpression,
elements: elements,
returnStatementComments: returnStatementComments,
}
}
export function expressionTypeForExpression(expression: TS.Expression): BlockOrExpression {
return TS.isParenthesizedExpression(expression) ? 'parenthesized-expression' : 'expression'
}
export function liftParsedElementsIntoFunctionContents(
blockOrExpression: BlockOrExpression,
parsedElements: ParseElementsResult,
): Either<string, WithParserMetadata<FunctionContents>> {
return mapEither((parsed) => {
return withParserMetadata(
functionContents(null, blockOrExpression, parsed.value, emptyComments),
parsed.highlightBounds,
parsed.propsUsed,
parsed.definedElsewhere,
)
}, parsedElements)
}
export function parseOutFunctionContents(
sourceFile: TS.SourceFile,
sourceText: string,
filename: string,
imports: Imports,
topLevelNames: Array<string>,
propsObjectName: string | null,
arrowFunctionBody: TS.ConciseBody,
existingHighlightBounds: Readonly<HighlightBoundsForUids>,
alreadyExistingUIDs: Set<string>,
): Either<string, WithParserMetadata<FunctionContents>> {
let highlightBounds = existingHighlightBounds
if (TS.isBlock(arrowFunctionBody)) {
if (arrowFunctionBody.statements.length === 0) {
return left('No body for component.')
} else {
const possibleBlockExpressions: TS.Node[] = dropLast(
nodeArrayToArray(arrowFunctionBody.statements),
)
const possibleElement = arrowFunctionBody.statements[arrowFunctionBody.statements.length - 1]!
let jsBlock: ArbitraryJSBlock
let propsUsed: Array<string> = []
let definedElsewhere: Array<string> = []
const returnStatementComments = parsedComments(
[],
getTrailingComments(sourceText, possibleElement),
)
const returnStatementPrefixCode = extractPrefixedCode(possibleElement, sourceFile)
if (possibleBlockExpressions.length > 0) {
const parseResult = parseArbitraryNodes(
sourceFile,
sourceText,
filename,
possibleBlockExpressions,
imports,
topLevelNames,
propsObjectName,
highlightBounds,
alreadyExistingUIDs,
false,
returnStatementPrefixCode,
true,
)
if (isLeft(parseResult)) {
return parseResult
} else {
highlightBounds = parseResult.value.highlightBounds
jsBlock = parseResult.value.value
propsUsed = parseResult.value.propsUsed
definedElsewhere = parseResult.value.definedElsewhere
}
} else {
jsBlock = arbitraryJSBlock(
returnStatementPrefixCode,
returnStatementPrefixCode,
[],
[],
null,
{},
)
}
let declared: Array<string> = [...topLevelNames]
if (jsBlock != null) {
declared.push(...jsBlock.definedWithin)
}
const parsedElements = parseOutJSXElements(
sourceFile,
sourceText,
filename,
[possibleElement],
imports,
declared,
propsObjectName,
highlightBounds,
alreadyExistingUIDs,
)
return mapEither((parsed) => {
return withParserMetadata(
functionContents(jsBlock, 'block', parsed.value, returnStatementComments),
parsed.highlightBounds,
propsUsed.concat(parsed.propsUsed),
definedElsewhere.concat(parsed.definedElsewhere),
)
}, parsedElements)
}
} else {
const parsedElements = parseOutJSXElements(
sourceFile,
sourceText,
filename,
[arrowFunctionBody],
imports,
topLevelNames,
propsObjectName,
highlightBounds,
alreadyExistingUIDs,
)
return liftParsedElementsIntoFunctionContents(
expressionTypeForExpression(arrowFunctionBody),
parsedElements,
)
}
}
export function extractPrefixedCode(node: TS.Node, sourceFile: TS.SourceFile): string {
// Attempt to capture everything between this and the last node
const nodeText = node.getText(sourceFile) ?? ''
const nodeFullText = node.getFullText(sourceFile) ?? ''
const prefixedText = nodeFullText.slice(0, nodeFullText.lastIndexOf(nodeText))
return prefixedText
} | the_stack |
import {
FillQuoteTransformerLimitOrderInfo,
FillQuoteTransformerOrderType,
FillQuoteTransformerRfqOrderInfo,
} from '@0x/protocol-utils';
import { MarketOperation } from '@0x/types';
import { BigNumber } from '@0x/utils';
import { NativeOrderWithFillableAmounts, RfqFirmQuoteValidator, RfqRequestOpts } from '../../types';
import { QuoteRequestor, V4RFQIndicativeQuoteMM } from '../../utils/quote_requestor';
import { ExtendedQuoteReportSources, PriceComparisonsReport, QuoteReport } from '../quote_report_generator';
import { CollapsedPath } from './path';
import { SourceFilters } from './source_filters';
/**
* Order domain keys: chainId and exchange
*/
export interface OrderDomain {
chainId: number;
exchangeAddress: string;
}
/**
* Common exception messages thrown by aggregation logic.
*/
export enum AggregationError {
NoOptimalPath = 'NO_OPTIMAL_PATH',
EmptyOrders = 'EMPTY_ORDERS',
NotERC20AssetData = 'NOT_ERC20ASSET_DATA',
NoBridgeForSource = 'NO_BRIDGE_FOR_SOURCE',
}
/**
* DEX sources to aggregate.
*/
export enum ERC20BridgeSource {
Native = 'Native',
Uniswap = 'Uniswap',
UniswapV2 = 'Uniswap_V2',
Eth2Dai = 'Eth2Dai',
Kyber = 'Kyber',
Curve = 'Curve',
LiquidityProvider = 'LiquidityProvider',
MultiBridge = 'MultiBridge',
Balancer = 'Balancer',
BalancerV2 = 'Balancer_V2',
Cream = 'CREAM',
Bancor = 'Bancor',
MakerPsm = 'MakerPsm',
MStable = 'mStable',
Mooniswap = 'Mooniswap',
MultiHop = 'MultiHop',
Shell = 'Shell',
Swerve = 'Swerve',
SnowSwap = 'SnowSwap',
SushiSwap = 'SushiSwap',
Dodo = 'DODO',
DodoV2 = 'DODO_V2',
CryptoCom = 'CryptoCom',
Linkswap = 'Linkswap',
KyberDmm = 'KyberDMM',
Smoothy = 'Smoothy',
Component = 'Component',
Saddle = 'Saddle',
XSigma = 'xSigma',
UniswapV3 = 'Uniswap_V3',
CurveV2 = 'Curve_V2',
Lido = 'Lido',
ShibaSwap = 'ShibaSwap',
AaveV2 = 'Aave_V2',
Compound = 'Compound',
// BSC only
PancakeSwap = 'PancakeSwap',
PancakeSwapV2 = 'PancakeSwap_V2',
BakerySwap = 'BakerySwap',
Nerve = 'Nerve',
Belt = 'Belt',
Ellipsis = 'Ellipsis',
ApeSwap = 'ApeSwap',
CafeSwap = 'CafeSwap',
CheeseSwap = 'CheeseSwap',
JulSwap = 'JulSwap',
ACryptos = 'ACryptoS',
// Polygon only
QuickSwap = 'QuickSwap',
ComethSwap = 'ComethSwap',
Dfyn = 'Dfyn',
WaultSwap = 'WaultSwap',
Polydex = 'Polydex',
FirebirdOneSwap = 'FirebirdOneSwap',
JetSwap = 'JetSwap',
IronSwap = 'IronSwap',
// Avalanche
Pangolin = 'Pangolin',
TraderJoe = 'TraderJoe',
// Celo only
UbeSwap = 'UbeSwap',
// Fantom
SpiritSwap = 'SpiritSwap',
SpookySwap = 'SpookySwap',
Beethovenx = 'Beethovenx',
MorpheusSwap = 'MorpheusSwap',
}
export type SourcesWithPoolsCache =
| ERC20BridgeSource.Balancer
| ERC20BridgeSource.BalancerV2
| ERC20BridgeSource.Beethovenx
| ERC20BridgeSource.Cream;
// tslint:disable: enum-naming
/**
* Curve contract function selectors.
*/
export enum CurveFunctionSelectors {
None = '0x00000000',
exchange = '0x3df02124',
exchange_underlying = '0xa6417ed6',
get_dy_underlying = '0x07211ef7',
get_dx_underlying = '0x0e71d1b9',
get_dy = '0x5e0d443f', // get_dy(int128,int128,uint256)
get_dx = '0x67df02ca',
get_dy_uint256 = '0x556d6e9f', // get_dy(uint256,uint256,uint256)
exchange_underlying_uint256 = '0x65b2489b', // exchange_underlying(uint256,uint256,uint256,uint256)
// Curve V2
exchange_v2 = '0x5b41b908',
exchange_underlying_v2 = '0x65b2489b',
get_dy_v2 = '0x556d6e9f',
get_dy_underlying_v2 = '0x85f11d1e',
// Smoothy
swap_uint256 = '0x5673b02d', // swap(uint256,uint256,uint256,uint256)
get_swap_amount = '0x45cf2ef6', // getSwapAmount(uint256,uint256,uint256)
// Nerve BSC, Saddle Mainnet
swap = '0x91695586', // swap(uint8,uint8,uint256,uint256,uint256)
calculateSwap = '0xa95b089f', // calculateSwap(uint8,uint8,uint256)
}
// tslint:enable: enum-naming
/**
* Configuration info on a Curve pool.
*/
export interface CurveInfo {
exchangeFunctionSelector: CurveFunctionSelectors;
sellQuoteFunctionSelector: CurveFunctionSelectors;
buyQuoteFunctionSelector: CurveFunctionSelectors;
poolAddress: string;
tokens: string[];
metaTokens: string[] | undefined;
gasSchedule: number;
}
/**
* Configuration for a specific PSM vault
*/
export interface PsmInfo {
psmAddress: string;
ilkIdentifier: string;
gemTokenAddress: string;
}
/**
* Configuration for a Lido deployment
*/
export interface LidoInfo {
stEthToken: string;
wethToken: string;
}
/**
* Configuration info for a Balancer V2 pool.
*/
export interface BalancerV2PoolInfo {
poolId: string;
vault: string;
}
export interface AaveV2Info {
lendingPool: string;
aToken: string;
underlyingToken: string;
}
// Internal `fillData` field for `Fill` objects.
export interface FillData {}
// `FillData` for native fills. Represents a single native order
export type NativeRfqOrderFillData = FillQuoteTransformerRfqOrderInfo;
export type NativeLimitOrderFillData = FillQuoteTransformerLimitOrderInfo;
export type NativeFillData = NativeRfqOrderFillData | NativeLimitOrderFillData;
// Represents an individual DEX sample from the sampler contract
export interface DexSample<TFillData extends FillData = FillData> {
source: ERC20BridgeSource;
fillData: TFillData;
input: BigNumber;
output: BigNumber;
}
export interface CurveFillData extends FillData {
fromTokenIdx: number;
toTokenIdx: number;
pool: CurveInfo;
}
export interface BalancerFillData extends FillData {
poolAddress: string;
}
export interface BalancerV2FillData extends FillData {
vault: string;
poolId: string;
}
export interface UniswapV2FillData extends FillData {
tokenAddressPath: string[];
router: string;
}
export interface ShellFillData extends FillData {
poolAddress: string;
}
export interface LiquidityProviderFillData extends FillData {
poolAddress: string;
gasCost: number;
}
export interface BancorFillData extends FillData {
path: string[];
networkAddress: string;
}
export interface KyberFillData extends FillData {
hint: string;
reserveId: string;
networkProxy: string;
}
export interface MooniswapFillData extends FillData {
poolAddress: string;
}
export interface DODOFillData extends FillData {
poolAddress: string;
isSellBase: boolean;
helperAddress: string;
}
export interface GenericRouterFillData extends FillData {
router: string;
}
export interface MultiHopFillData extends FillData {
firstHopSource: SourceQuoteOperation;
secondHopSource: SourceQuoteOperation;
intermediateToken: string;
}
export interface MakerPsmExtendedData {
isSellOperation: boolean;
takerToken: string;
}
export type MakerPsmFillData = FillData & MakerPsmExtendedData & PsmInfo;
export interface HopInfo {
sourceIndex: BigNumber;
returnData: string;
}
export interface UniswapV3FillData extends FillData {
tokenAddressPath: string[];
router: string;
pathAmounts: Array<{ uniswapPath: string; inputAmount: BigNumber }>;
}
export interface KyberDmmFillData extends UniswapV2FillData {
poolsPath: string[];
}
export interface FinalUniswapV3FillData extends Omit<UniswapV3FillData, 'uniswapPaths'> {
// The uniswap-encoded path that can fll the maximum input amount.
uniswapPath: string;
}
export interface LidoFillData extends FillData {
stEthTokenAddress: string;
takerToken: string;
}
export interface AaveV2FillData extends FillData {
lendingPool: string;
aToken: string;
underlyingToken: string;
takerToken: string;
}
export interface CompoundFillData extends FillData {
cToken: string;
takerToken: string;
makerToken: string;
}
/**
* Represents a node on a fill path.
*/
export interface Fill<TFillData extends FillData = FillData> {
// basic data for every fill
source: ERC20BridgeSource;
// TODO jacob people seem to agree that orderType here is more readable
type: FillQuoteTransformerOrderType; // should correspond with TFillData
fillData: TFillData;
// Unique ID of the original source path this fill belongs to.
// This is generated when the path is generated and is useful to distinguish
// paths that have the same `source` IDs but are distinct (e.g., Curves).
sourcePathId: string;
// See `SOURCE_FLAGS`.
flags: bigint;
// Input fill amount (taker asset amount in a sell, maker asset amount in a buy).
input: BigNumber;
// Output fill amount (maker asset amount in a sell, taker asset amount in a buy).
output: BigNumber;
// The output fill amount, ajdusted by fees.
adjustedOutput: BigNumber;
// Fill that must precede this one. This enforces certain fills to be contiguous.
parent?: Fill;
// The index of the fill in the original path.
index: number;
}
/**
* Represents continguous fills on a path that have been merged together.
*/
export interface CollapsedFill<TFillData extends FillData = FillData> {
source: ERC20BridgeSource;
type: FillQuoteTransformerOrderType; // should correspond with TFillData
fillData: TFillData;
// Unique ID of the original source path this fill belongs to.
// This is generated when the path is generated and is useful to distinguish
// paths that have the same `source` IDs but are distinct (e.g., Curves).
sourcePathId: string;
/**
* Total input amount (sum of `subFill`s)
*/
input: BigNumber;
/**
* Total output amount (sum of `subFill`s)
*/
output: BigNumber;
/**
* Quantities of all the fills that were collapsed.
*/
subFills: Array<{
input: BigNumber;
output: BigNumber;
}>;
}
/**
* A `CollapsedFill` wrapping a native order.
*/
export interface NativeCollapsedFill extends CollapsedFill<NativeFillData> {}
export interface OptimizedMarketOrderBase<TFillData extends FillData = FillData> {
source: ERC20BridgeSource;
fillData: TFillData;
type: FillQuoteTransformerOrderType; // should correspond with TFillData
makerToken: string;
takerToken: string;
makerAmount: BigNumber; // The amount we wish to buy from this order, e.g inclusive of any previous partial fill
takerAmount: BigNumber; // The amount we wish to fill this for, e.g inclusive of any previous partial fill
fills: CollapsedFill[];
}
export interface OptimizedMarketBridgeOrder<TFillData extends FillData = FillData>
extends OptimizedMarketOrderBase<TFillData> {
type: FillQuoteTransformerOrderType.Bridge;
fillData: TFillData;
sourcePathId: string;
}
export interface OptimizedLimitOrder extends OptimizedMarketOrderBase<NativeLimitOrderFillData> {
type: FillQuoteTransformerOrderType.Limit;
fillData: NativeLimitOrderFillData;
}
export interface OptimizedRfqOrder extends OptimizedMarketOrderBase<NativeRfqOrderFillData> {
type: FillQuoteTransformerOrderType.Rfq;
fillData: NativeRfqOrderFillData;
}
/**
* Optimized orders to fill.
*/
export type OptimizedMarketOrder =
| OptimizedMarketBridgeOrder<FillData>
| OptimizedMarketOrderBase<NativeLimitOrderFillData>
| OptimizedMarketOrderBase<NativeRfqOrderFillData>;
export interface GetMarketOrdersRfqOpts extends RfqRequestOpts {
quoteRequestor?: QuoteRequestor;
firmQuoteValidator?: RfqFirmQuoteValidator;
}
export type FeeEstimate = (fillData: FillData) => number | BigNumber;
export type FeeSchedule = Partial<{ [key in ERC20BridgeSource]: FeeEstimate }>;
export type ExchangeProxyOverhead = (sourceFlags: bigint) => BigNumber;
/**
* Options for `getMarketSellOrdersAsync()` and `getMarketBuyOrdersAsync()`.
*/
export interface GetMarketOrdersOpts {
/**
* Liquidity sources to exclude. Default is none.
*/
excludedSources: ERC20BridgeSource[];
/**
* Liquidity sources to exclude when used to calculate the cost of the route.
* Default is none.
*/
excludedFeeSources: ERC20BridgeSource[];
/**
* Liquidity sources to include. Default is none, which allows all supported
* sources that aren't excluded by `excludedSources`.
*/
includedSources: ERC20BridgeSource[];
/**
* Complexity limit on the search algorithm, i.e., maximum number of
* nodes to visit. Default is 1024.
*/
runLimit: number;
/**
* When generating bridge orders, we use
* sampled rate * (1 - bridgeSlippage)
* as the rate for calculating maker/taker asset amounts.
* This should be a small positive number (e.g., 0.0005) to make up for
* small discrepancies between samples and truth.
* Default is 0.0005 (5 basis points).
*/
bridgeSlippage: number;
/**
* The maximum price slippage allowed in the fallback quote. If the slippage
* between the optimal quote and the fallback quote is greater than this
* percentage, no fallback quote will be provided.
*/
maxFallbackSlippage: number;
/**
* Number of samples to take for each DEX quote.
*/
numSamples: number;
/**
* The exponential sampling distribution base.
* A value of 1 will result in evenly spaced samples.
* > 1 will result in more samples at lower sizes.
* < 1 will result in more samples at higher sizes.
* Default: 1.25.
*/
sampleDistributionBase: number;
/**
* Number of samples to use when creating fill curves with neon-router
*/
neonRouterNumSamples: number;
/**
* Fees for each liquidity source, expressed in gas.
*/
feeSchedule: FeeSchedule;
/**
* Estimated gas consumed by each liquidity source.
*/
gasSchedule: FeeSchedule;
exchangeProxyOverhead: ExchangeProxyOverhead;
/**
* Whether to pad the quote with a redundant fallback quote using different
* sources. Defaults to `true`.
*/
allowFallback: boolean;
/**
* Options for RFQT such as takerAddress, intent on filling
*/
rfqt?: GetMarketOrdersRfqOpts;
/**
* Whether to generate a quote report
*/
shouldGenerateQuoteReport: boolean;
/**
* Whether to include price comparison data in the quote
*/
shouldIncludePriceComparisonsReport: boolean;
/**
* Token addresses with a list of adjacent intermediary tokens to consider
* hopping to. E.g DAI->USDC via an adjacent token WETH
*/
tokenAdjacencyGraph: TokenAdjacencyGraph;
/**
* Gas price to use for quote
*/
gasPrice: BigNumber;
/**
* Sampler metrics for recording data on the sampler service and operations
*/
samplerMetrics?: SamplerMetrics;
}
export interface SamplerMetrics {
/**
* Logs the gas information performed during a sampler call.
*
* @param data.gasBefore The gas remaining measured before any operations have been performed
* @param data.gasAfter The gas remaining measured after all operations have been performed
*/
logGasDetails(data: { gasBefore: BigNumber; gasAfter: BigNumber }): void;
/**
* Logs the block number
*
* @param blockNumber block number of the sampler call
*/
logBlockNumber(blockNumber: BigNumber): void;
}
/**
* A composable operation the be run in `DexOrderSampler.executeAsync()`.
*/
export interface BatchedOperation<TResult> {
encodeCall(): string;
handleCallResults(callResults: string): TResult;
handleRevert(callResults: string): TResult;
}
export interface SourceQuoteOperation<TFillData extends FillData = FillData> extends BatchedOperation<BigNumber[]> {
readonly source: ERC20BridgeSource;
fillData: TFillData;
}
export interface OptimizerResult {
optimizedOrders: OptimizedMarketOrder[];
sourceFlags: bigint;
liquidityDelivered: CollapsedFill[] | DexSample<MultiHopFillData>;
marketSideLiquidity: MarketSideLiquidity;
adjustedRate: BigNumber;
unoptimizedPath?: CollapsedPath;
takerAmountPerEth: BigNumber;
makerAmountPerEth: BigNumber;
}
export interface OptimizerResultWithReport extends OptimizerResult {
quoteReport?: QuoteReport;
extendedQuoteReportSources?: ExtendedQuoteReportSources;
priceComparisonsReport?: PriceComparisonsReport;
}
export type MarketDepthSide = Array<Array<DexSample<FillData>>>;
export interface MarketDepth {
bids: MarketDepthSide;
asks: MarketDepthSide;
makerTokenDecimals: number;
takerTokenDecimals: number;
}
export interface MarketSideLiquidity {
side: MarketOperation;
inputAmount: BigNumber;
inputToken: string;
outputToken: string;
outputAmountPerEth: BigNumber;
inputAmountPerEth: BigNumber;
quoteSourceFilters: SourceFilters;
makerTokenDecimals: number;
takerTokenDecimals: number;
quotes: RawQuotes;
isRfqSupported: boolean;
}
export interface RawQuotes {
nativeOrders: NativeOrderWithFillableAmounts[];
rfqtIndicativeQuotes: V4RFQIndicativeQuoteMM[];
twoHopQuotes: Array<DexSample<MultiHopFillData>>;
dexQuotes: Array<Array<DexSample<FillData>>>;
}
export interface TokenAdjacencyGraph {
[token: string]: string[];
default: string[];
}
export interface LiquidityProviderRegistry {
[address: string]: {
tokens: string[];
gasCost: number | ((takerToken: string, makerToken: string) => number);
};
}
export interface GenerateOptimizedOrdersOpts {
runLimit?: number;
bridgeSlippage?: number;
maxFallbackSlippage?: number;
excludedSources?: ERC20BridgeSource[];
feeSchedule: FeeSchedule;
exchangeProxyOverhead?: ExchangeProxyOverhead;
allowFallback?: boolean;
shouldBatchBridgeOrders?: boolean;
gasPrice: BigNumber;
neonRouterNumSamples: number;
}
export interface ComparisonPrice {
wholeOrder: BigNumber | undefined;
}
export interface KyberSamplerOpts {
networkProxy: string;
hintHandler: string;
weth: string;
} | the_stack |
import Dygraph, { dygraphs } from 'dygraphs';
function demo() {
const g14 = new Dygraph(document.getElementById('div_g14')!, 'data', {
rollPeriod: 14,
errorBars: true,
labelsSeparateLines: true,
});
}
function twoAxes() {
const data = [] as number[][];
const g = new Dygraph(document.getElementById('demodiv')!, data, {
labels: ['Date', 'Y1', 'Y2', 'Y3', 'Y4'],
series: {
Y3: {
axis: 'y2',
},
Y4: {
axis: 'y2',
},
},
axes: {
y2: {
// set axis-related properties here
labelsKMB: true,
},
y: {
axisLabelWidth: 60,
},
},
ylabel: 'Primary y-axis',
y2label: 'Secondary y-axis',
});
const g2 = new Dygraph(document.getElementById('demodiv_y2_primary')!, data, {
labels: ['Date', 'Y1', 'Y2', 'Y3', 'Y4'],
ylabel: 'Primary y-axis',
y2label: 'Secondary y-axis',
series: {
Y3: {
axis: 'y2',
},
Y4: {
axis: 'y2',
},
},
axes: {
y: {
// set axis-related properties here
drawGrid: false,
independentTicks: false,
},
y2: {
// set axis-related properties here
labelsKMB: true,
drawGrid: true,
independentTicks: true,
},
},
});
const g3 = new Dygraph(document.getElementById('demodiv_two_grids')!, data, {
labels: ['Date', 'Y1', 'Y2', 'Y3', 'Y4'],
ylabel: 'Primary y-axis',
y2label: 'Secondary y-axis',
series: {
Y3: {
axis: 'y2',
},
Y4: {
axis: 'y2',
},
},
axes: {
y2: {
// set axis-related properties here
labelsKMB: true,
drawGrid: true,
independentTicks: true,
gridLinePattern: [2, 2],
},
},
});
const g4 = new Dygraph(document.getElementById('demodiv_one')!, data, {
labels: ['Date', 'Y1', 'Y2', 'Y3', 'Y4'],
labelsKMB: true,
ylabel: 'Primary y-axis',
y2label: 'Secondary y-axis',
});
const g5 = new Dygraph(document.getElementById('demodiv_one_right')!, data, {
labels: ['Date', 'Y1', 'Y2', 'Y3', 'Y4'],
ylabel: 'Primary y-axis',
y2label: 'Secondary y-axis',
series: {
Y1: {
axis: 'y2',
},
Y2: {
axis: 'y2',
},
Y3: {
axis: 'y2',
},
Y4: {
axis: 'y2',
},
},
axes: {
y: {
// set axis-related properties here
drawGrid: false,
independentTicks: false,
},
y2: {
// set axis-related properties here
labelsKMB: true,
drawGrid: true,
independentTicks: true,
},
},
});
function update(el: HTMLInputElement) {
g.updateOptions({ fillGraph: el.checked });
g2.updateOptions({ fillGraph: el.checked });
g3.updateOptions({ fillGraph: el.checked });
g4.updateOptions({ fillGraph: el.checked });
g5.updateOptions({ fillGraph: el.checked });
}
}
function perSeries() {
const data = '1234';
const g = new Dygraph(document.getElementById('demodiv')!, data, {
strokeWidth: 2,
series: {
parabola: {
strokeWidth: 0.0,
drawPoints: true,
pointSize: 4,
highlightCircleSize: 6,
},
line: {
strokeWidth: 1.0,
drawPoints: true,
pointSize: 1.5,
},
'sine wave': {
strokeWidth: 3,
highlightCircleSize: 10,
},
'sine wave2': {
strokePattern: [10, 2, 5, 2],
strokeWidth: 2,
highlightCircleSize: 3,
},
},
});
const g2 = new Dygraph(document.getElementById('demodiv2')!, data, {
legend: 'always',
strokeWidth: 2,
series: {
parabola: {
strokePattern: null,
drawPoints: true,
pointSize: 4,
highlightCircleSize: 6,
},
line: {
strokePattern: Dygraph.DASHED_LINE,
strokeWidth: 1.0,
drawPoints: true,
pointSize: 1.5,
},
'another line': {
strokePattern: [25, 5],
},
'sine wave': {
strokePattern: Dygraph.DOTTED_LINE,
strokeWidth: 3,
highlightCircleSize: 10,
},
'sine wave2': {
strokePattern: Dygraph.DOT_DASH_LINE,
strokeWidth: 2,
highlightCircleSize: 3,
},
},
});
const g3 = new Dygraph(document.getElementById('demodiv3')!, data, {
strokeWidth: 2,
series: {
parabola: {
strokeWidth: 0.0,
drawPoints: true,
pointSize: 4,
highlightCircleSize: 6,
},
line: {
strokeWidth: 1.0,
drawPoints: true,
pointSize: 1.5,
},
'sine wave': {
strokeWidth: 3,
highlightCircleSize: 10,
},
'sine wave2': {
strokePattern: [10, 2, 5, 2],
strokeWidth: 2,
highlightCircleSize: 3,
},
},
});
}
function highlightedRegion() {
const highlight_start = 0;
const highlight_end = 0;
const g = new Dygraph(document.getElementById('div_g')!, [], {
labels: ['X', 'Est.', 'Actual'],
animatedZooms: true,
underlayCallback: (canvas, area, g) => {
const bottom_left = g.toDomCoords(highlight_start, -20);
const top_right = g.toDomCoords(highlight_end, +20);
const left = bottom_left[0];
const right = top_right[0];
canvas.fillStyle = 'rgba(255, 255, 102, 1.0)';
canvas.fillRect(left, area.y, right - left, area.h);
},
});
}
function makeGraph(className: string, numSeries: number, numRows: number, isStacked: boolean) {
const div = document.createElement('div');
div.className = className;
div.style.display = 'inline-block';
document.body.appendChild(div);
const labels = ['x'];
for (let i = 0; i < numSeries; ++i) {
let label = '' + i;
label = `s${'000'.substr(label.length)}${label}`;
labels[i + 1] = label;
}
const g = new Dygraph(div, 'data', {
width: 480,
height: 320,
labels: labels.slice(),
stackedGraph: isStacked,
highlightCircleSize: 2,
strokeWidth: 1,
strokeBorderWidth: isStacked ? null : 1,
highlightSeriesOpts: {
strokeWidth: 3,
strokeBorderWidth: 1,
highlightCircleSize: 5,
},
});
g.setSelection(false, 's005');
}
function linearRegressionAddSeries() {
let orig_colors = [] as string[];
const g = new Dygraph(document.getElementById('demodiv')!, 'data', {
labels: ['X', 'Y1', 'Y2'],
drawPoints: true,
strokeWidth: 0.0,
drawCallback: (g, is_initial) => {
if (!is_initial) return;
orig_colors = g.getColors();
},
});
}
function callbacks() {
const s = document.getElementById('status')!;
let g = new Dygraph(document.getElementById('demodiv')!, 'data');
const pts_info = (e: MouseEvent, x: number, pts: readonly dygraphs.Point[], row?: number) => {
let str = `(${x}) `;
for (let i = 0; i < pts.length; i++) {
const p = pts[i];
if (i) str += ', ';
str += `${p.name}: ${p.yval}`;
}
const { offsetX, offsetY } = e;
const dataXY = g.toDataCoords(offsetX, offsetY);
str += `, (${offsetX}, ${offsetY})`;
str += ` -> (${dataXY[0]}, ${dataXY[1]})`;
str += `, row #${row}`;
return str;
};
g = new Dygraph(document.getElementById('div_g')!, 'NoisyData', {
rollPeriod: 7,
showRoller: true,
errorBars: true,
highlightCallback: (e, x, pts, row) => {
s.innerHTML += `<b>Highlight</b> ${pts_info(e, x, pts, row)}<br/>`;
},
unhighlightCallback: e => {
s.innerHTML += '<b>Unhighlight</b><br/>';
},
clickCallback: (e, x, pts) => {
s.innerHTML += `<b>Click</b> ${pts_info(e, x, pts)}<br/>`;
},
pointClickCallback: (e, p) => {
s.innerHTML += `<b>Point Click</b> ${p.name}: ${p.x}<br/>`;
},
zoomCallback: (minX, maxX, yRanges) => {
s.innerHTML += `<b>Zoom</b> [${minX}, ${maxX}, [${yRanges}]]<br/>`;
},
drawCallback: g => {
s.innerHTML += `<b>Draw</b> [${g.xAxisRange()}]<br/>`;
},
});
}
function valueAxisFormatters() {
function formatDate(d: Date) {
const yyyy = d.getFullYear();
const mm = d.getMonth() + 1;
const dd = d.getDate();
return `${yyyy}-${(mm < 10 ? '0' : '') + mm + (dd < 10 ? '0' : '') + dd}`;
}
const g = new Dygraph(document.getElementById('demodiv')!, 'data', {
labels: ['Date', 'Y1', 'Y2', 'Y3', 'Y4'],
width: 640,
height: 350,
series: {
Y3: { axis: 'y2' },
Y4: { axis: 'y2' },
},
axes: {
x: {
valueFormatter: ms => {
return `xvf(${formatDate(new Date(ms))})`;
},
axisLabelFormatter: d => {
return `xalf(${formatDate(d as Date)})`;
},
pixelsPerLabel: 100,
axisLabelWidth: 100,
},
y: {
valueFormatter: y => {
return `yvf(${y.toPrecision(2)})`;
},
axisLabelFormatter: y => {
return `yalf(${(y as number).toPrecision(2)})`;
},
axisLabelWidth: 100,
},
y2: {
valueFormatter: y2 => {
return `y2vf(${y2.toPrecision(2)})`;
},
axisLabelFormatter: y2 => {
return `y2alf(${(y2 as number).toPrecision(2)})`;
},
},
},
});
}
function annotation() {
const eventDiv = document.getElementById('events')!;
function nameAnnotation(ann: dygraphs.Annotation) {
return `(${ann.series}, ${ann.x})`;
}
const annotations = [] as dygraphs.Annotation[];
let graph_initialized = false;
const g = new Dygraph(
document.getElementById('g_div')!,
() => {
const zp = (x: number) => {
if (x < 10) return '0' + x;
else return '' + x;
};
let r = 'date,parabola,line,another line,sine wave\n';
for (let i = 1; i <= 31; i++) {
r += '200610' + zp(i);
r += ',' + 10 * (i * (31 - i));
r += ',' + 10 * (8 * i);
r += ',' + 10 * (250 - 8 * i);
r += ',' + 10 * (125 + 125 * Math.sin(0.3 * i));
r += '\n';
}
return r;
},
{
rollPeriod: 1,
showRoller: true,
width: 480,
height: 320,
drawCallback: (g, is_initial) => {
if (is_initial) {
graph_initialized = true;
if (annotations.length > 0) {
g.setAnnotations(annotations);
}
}
const anns = g.annotations();
let html = '';
anns.forEach(ann => {
const name = nameAnnotation(ann);
html += `<span id='${name}'>`;
html += `${name}: ${ann.shortText || '(icon)'}`;
html += ` -> ${ann.text}</span><br/>`;
});
document.getElementById('list')!.innerHTML = html;
},
},
);
let last_ann = 0;
for (let x = 10; x < 15; x += 2) {
annotations.push({
series: 'sine wave',
x: '200610' + x,
shortText: '' + x,
text: 'Stock Market Crash ' + x,
});
last_ann = x;
}
annotations.push({
series: 'another line',
x: '20061013',
icon: 'dollar.png',
width: 18,
height: 23,
tickHeight: 4,
text: 'Another one',
cssClass: 'annotation',
clickHandler: () => {
document.getElementById('events')!.innerHTML += 'special handler<br/>';
},
});
annotations.push({
series: 'parabola',
x: '20061012',
shortText: 'P',
text: 'Parabola Annotation at same x-coord',
});
if (graph_initialized) {
g.setAnnotations(annotations);
}
function add() {
const x = last_ann + 2;
const annnotations = g.annotations();
annotations.push({
series: 'line',
x: '200610' + x,
shortText: '' + x,
text: 'Line ' + x,
tickHeight: 10,
});
last_ann = x;
g.setAnnotations(annotations);
}
function bottom(el: HTMLInputElement) {
let to_bottom = true;
if (el.value !== 'Shove to bottom') to_bottom = false;
const anns = g.annotations();
anns.map(ann => {
ann.attachAtBottom = to_bottom;
return ann;
});
g.setAnnotations(anns);
el.value = to_bottom ? 'Lift back up' : 'Shove to bottom';
}
let saveBg = '';
let num = 0;
g.updateOptions({
annotationClickHandler: (ann, point, dg, event) => {
eventDiv.innerHTML += `click: ${nameAnnotation(ann)} <br/>`;
},
annotationDblClickHandler: (ann, point, dg, event) => {
eventDiv.innerHTML += `dblclick: ${nameAnnotation(ann)} <br/>`;
},
annotationMouseOverHandler: (ann, point, dg, event) => {
document.getElementById(nameAnnotation(ann))!.style.fontWeight = 'bold';
saveBg = ann.div!.style.backgroundColor;
ann.div!.style.backgroundColor = '#ddd';
},
annotationMouseOutHandler: (ann, point, dg, event) => {
document.getElementById(nameAnnotation(ann))!.style.fontWeight = 'normal';
ann.div!.style.backgroundColor = saveBg;
},
pointClickCallback: (event, p) => {
// Check if the point is already annotated.
if (p.annotation) return;
// If not, add one.
const ann = {
series: p.name,
xval: p.xval,
shortText: '' + num,
text: 'Annotation #' + num,
};
const anns = g.annotations();
anns.push(ann);
g.setAnnotations(anns);
num++;
},
});
}
function valueRangeTest() {
new Dygraph(document.getElementById('valueRange-test')!, [], {
axes: {
x: { valueRange: [0, 100] },
y: { valueRange: [0, null] },
y2: { valueRange: null },
},
});
}
function resize() {
const d = new Dygraph(document.getElementById('demo')!, 'dummy-data', {});
d.resize();
d.resize(300, 200);
} | the_stack |
* @module Rendering
*/
import { assert } from "@itwin/core-bentley";
import { AuxChannel, AuxChannelData, Point2d, Range3d } from "@itwin/core-geometry";
import {
ColorIndex, EdgeArgs, Feature, FeatureIndex, FeatureIndexType, FeatureTable, FillFlags, LinePixels, MeshEdges, MeshPolyline, MeshPolylineList,
OctEncodedNormal, PolylineData, PolylineEdgeArgs, PolylineFlags, QParams3d, QPoint3dList, RenderMaterial, RenderTexture, SilhouetteEdgeArgs,
} from "@itwin/core-common";
import { InstancedGraphicParams } from "../../InstancedGraphicParams";
import { RenderGraphic } from "../../RenderGraphic";
import { RenderSystem } from "../../RenderSystem";
import { ColorMap } from "../ColorMap";
import { DisplayParams } from "../DisplayParams";
import { Triangle, TriangleList } from "../Primitives";
import { VertexKeyProps } from "../VertexKey";
/* Information needed to draw a set of indexed polylines using a shared vertex buffer.
* @internal
*/
export class PolylineArgs {
public colors = new ColorIndex();
public features = new FeatureIndex();
public width = 0;
public linePixels = LinePixels.Solid;
public flags: PolylineFlags;
public points: QPoint3dList;
public polylines: PolylineData[];
public pointParams: QParams3d;
public constructor(points: QPoint3dList = new QPoint3dList(QParams3d.fromRange(Range3d.createNull())),
polylines: PolylineData[] = [], pointParams?: QParams3d, is2d = false, isPlanar = false) {
this.points = points;
this.polylines = polylines;
if (undefined === pointParams) {
this.pointParams = QParams3d.fromRange(Range3d.createNull());
} else {
this.pointParams = pointParams;
}
this.flags = new PolylineFlags(is2d, isPlanar);
}
public get isValid(): boolean { return this.polylines.length !== 0; }
public reset(): void {
this.flags.initDefaults();
this.points = new QPoint3dList(QParams3d.fromRange(Range3d.createNull()));
this.polylines = [];
this.colors.reset();
this.features.reset();
}
public init(mesh: Mesh) {
this.reset();
if (undefined === mesh.polylines)
return;
this.width = mesh.displayParams.width;
this.linePixels = mesh.displayParams.linePixels;
this.flags.is2d = mesh.is2d;
this.flags.isPlanar = mesh.isPlanar;
this.flags.isDisjoint = Mesh.PrimitiveType.Point === mesh.type;
if (DisplayParams.RegionEdgeType.Outline === mesh.displayParams.regionEdgeType) {
// This polyline is behaving as the edges of a region surface.
if (undefined === mesh.displayParams.gradient || mesh.displayParams.gradient.isOutlined)
this.flags.setIsNormalEdge();
else
this.flags.setIsOutlineEdge(); // edges only displayed if fill undisplayed...
}
mesh.polylines.forEach((polyline) => {
const indexedPolyline = new PolylineData();
if (indexedPolyline.init(polyline)) { this.polylines.push(indexedPolyline); }
});
if (!this.isValid) { return false; }
this.finishInit(mesh);
return true;
}
public finishInit(mesh: Mesh) {
this.pointParams = mesh.points.params;
this.points = mesh.points;
mesh.colorMap.toColorIndex(this.colors, mesh.colors);
mesh.toFeatureIndex(this.features);
}
}
/** The vertices of the edges are shared with those of the surface
* @internal
*/
export class MeshArgsEdges {
public edges = new EdgeArgs();
public silhouettes = new SilhouetteEdgeArgs();
public polylines = new PolylineEdgeArgs();
public width = 0;
public linePixels = LinePixels.Solid;
public clear(): void {
this.edges.clear();
this.silhouettes.clear();
this.polylines.clear();
this.width = 0;
this.linePixels = LinePixels.Solid;
}
public get isValid(): boolean { return this.edges.isValid || this.silhouettes.isValid || this.polylines.isValid; }
}
/* A carrier of information needed to describe a triangle mesh and its edges.
* @internal
*/
export class MeshArgs {
public edges = new MeshArgsEdges();
public vertIndices?: number[];
public points?: QPoint3dList;
public normals?: OctEncodedNormal[];
public textureUv?: Point2d[];
public texture?: RenderTexture;
public colors = new ColorIndex();
public features = new FeatureIndex();
public material?: RenderMaterial;
public fillFlags = FillFlags.None;
public isPlanar = false;
public is2d = false;
public hasBakedLighting = false;
public isVolumeClassifier = false;
public hasFixedNormals = false;
public auxChannels?: ReadonlyArray<AuxChannel>;
public clear() {
this.edges.clear();
this.vertIndices = undefined;
this.points = undefined;
this.normals = undefined;
this.textureUv = undefined;
this.texture = undefined;
this.colors.reset();
this.features.reset();
this.material = undefined;
this.fillFlags = FillFlags.None;
this.isPlanar = this.is2d = this.hasBakedLighting = this.isVolumeClassifier = this.hasFixedNormals = false;
this.auxChannels = undefined;
}
public init(mesh: Mesh): boolean {
this.clear();
if (undefined === mesh.triangles || mesh.triangles.isEmpty)
return false;
assert(0 < mesh.points.length);
this.vertIndices = mesh.triangles.indices;
this.points = mesh.points;
if (!mesh.displayParams.ignoreLighting && 0 < mesh.normals.length)
this.normals = mesh.normals;
if (0 < mesh.uvParams.length)
this.textureUv = mesh.uvParams;
mesh.colorMap.toColorIndex(this.colors, mesh.colors);
mesh.toFeatureIndex(this.features);
this.material = mesh.displayParams.material;
if (undefined !== mesh.displayParams.textureMapping)
this.texture = mesh.displayParams.textureMapping.texture;
this.fillFlags = mesh.displayParams.fillFlags;
this.isPlanar = mesh.isPlanar;
this.is2d = mesh.is2d;
this.hasBakedLighting = (true === mesh.hasBakedLighting);
this.isVolumeClassifier = (true === mesh.isVolumeClassifier);
this.edges.width = mesh.displayParams.width;
this.edges.linePixels = mesh.displayParams.linePixels;
this.auxChannels = mesh.auxChannels;
const meshEdges = mesh.edges;
if (undefined === meshEdges)
return true;
this.edges.edges.init(mesh.edges);
this.edges.silhouettes.init(mesh.edges);
const polylines: PolylineData[] = [];
meshEdges.polylines.forEach((meshPolyline: MeshPolyline) => {
const polyline = new PolylineData();
if (polyline.init(meshPolyline)) { polylines.push(polyline); }
});
this.edges.polylines.init(polylines);
return true;
}
}
/** @internal */
export class MeshGraphicArgs {
public polylineArgs = new PolylineArgs();
public meshArgs: MeshArgs = new MeshArgs();
}
/** @internal */
export class Mesh {
private readonly _data: TriangleList | MeshPolylineList;
public readonly points: QPoint3dList;
public readonly normals: OctEncodedNormal[] = [];
public readonly uvParams: Point2d[] = [];
public readonly colorMap: ColorMap = new ColorMap(); // used to be called ColorTable
public colors: number[] = [];
public edges?: MeshEdges;
public readonly features?: Mesh.Features;
public readonly type: Mesh.PrimitiveType;
public readonly is2d: boolean;
public readonly isPlanar: boolean;
public readonly hasBakedLighting: boolean;
public readonly isVolumeClassifier: boolean;
public displayParams: DisplayParams;
private _auxChannels?: AuxChannel[];
private constructor(props: Mesh.Props) {
const { displayParams, features, type, range, is2d, isPlanar } = props;
this._data = Mesh.PrimitiveType.Mesh === type ? new TriangleList() : new MeshPolylineList();
this.displayParams = displayParams;
this.features = features;
this.type = type;
this.is2d = is2d;
this.isPlanar = isPlanar;
this.hasBakedLighting = (true === props.hasBakedLighting);
this.isVolumeClassifier = (true === props.isVolumeClassifier);
this.points = new QPoint3dList(QParams3d.fromRange(range));
}
public static create(props: Mesh.Props): Mesh { return new Mesh(props); }
public get triangles(): TriangleList | undefined {
return Mesh.PrimitiveType.Mesh === this.type ? this._data as TriangleList : undefined;
}
public get polylines(): MeshPolylineList | undefined {
return Mesh.PrimitiveType.Mesh !== this.type ? this._data as MeshPolylineList : undefined;
}
public get auxChannels(): ReadonlyArray<AuxChannel> | undefined {
return this._auxChannels;
}
public addAuxChannels(channels: ReadonlyArray<AuxChannel>, srcIndex: number): void {
// The native version of this function appears to assume that all polyfaces added to the Mesh will have
// the same number + type of aux channels.
// ###TODO We should really produce a separate Mesh for each unique combination. For now just bail on mismatch.
if (this._auxChannels) {
if (this._auxChannels.length !== channels.length)
return;
for (let i = 0; i < channels.length; i++) {
const src = channels[i];
const dst = this._auxChannels[i];
if (src.dataType !== dst.dataType || src.name !== dst.name || src.inputName !== dst.inputName)
return;
}
}
if (!this._auxChannels) {
// Copy the channels, leaving each AuxData's values array empty.
this._auxChannels = channels.map((x) => new AuxChannel(x.data.map((y) => new AuxChannelData(y.input, [])), x.dataType, x.name, x.inputName));
}
// Append the value at srcIndex from each source channel's data to our channels.
for (let channelIndex = 0; channelIndex < channels.length; channelIndex++) {
const srcChannel = channels[channelIndex];
const dstChannel = this._auxChannels[channelIndex];
const dstIndex = dstChannel.valueCount;
for (let dataIndex = 0; dataIndex < srcChannel.data.length; dataIndex++) {
const dstData = dstChannel.data[dataIndex];
dstData.copyValues(srcChannel.data[dataIndex], dstIndex, srcIndex, dstChannel.entriesPerValue);
}
}
}
public toFeatureIndex(index: FeatureIndex): void {
if (undefined !== this.features)
this.features.toFeatureIndex(index);
}
public getGraphics(args: MeshGraphicArgs, system: RenderSystem, instances?: InstancedGraphicParams): RenderGraphic | undefined {
if (undefined !== this.triangles && this.triangles.length !== 0) {
if (args.meshArgs.init(this))
return system.createTriMesh(args.meshArgs, instances);
} else if (undefined !== this.polylines && this.polylines.length !== 0 && args.polylineArgs.init(this)) {
return system.createIndexedPolylines(args.polylineArgs, instances);
}
return undefined;
}
public addPolyline(poly: MeshPolyline): void {
const { type, polylines } = this;
assert(Mesh.PrimitiveType.Polyline === type || Mesh.PrimitiveType.Point === type);
assert(undefined !== polylines);
if (Mesh.PrimitiveType.Polyline === type && poly.indices.length < 2)
return;
if (undefined !== polylines)
polylines.push(poly);
}
public addTriangle(triangle: Triangle): void {
const { triangles, type } = this;
assert(Mesh.PrimitiveType.Mesh === type);
assert(undefined !== triangles);
if (undefined !== triangles)
triangles.addTriangle(triangle);
}
public addVertex(props: VertexKeyProps): number {
const { position, normal, uvParam, fillColor } = props;
this.points.push(position);
if (undefined !== normal)
this.normals.push(normal);
if (undefined !== uvParam)
this.uvParams.push(uvParam);
// Don't allocate color indices until we have non-uniform colors
if (0 === this.colorMap.length) {
this.colorMap.insert(fillColor);
assert(this.colorMap.isUniform);
assert(0 === this.colorMap.indexOf(fillColor));
} else if (!this.colorMap.isUniform || !this.colorMap.hasColor(fillColor)) {
// Back-fill uniform value (index=0) for existing vertices if previously uniform
if (0 === this.colors.length)
this.colors.length = this.points.length - 1;
this.colors.push(this.colorMap.insert(fillColor));
assert(!this.colorMap.isUniform);
}
return this.points.length - 1;
}
}
/** @internal */
export namespace Mesh { // eslint-disable-line no-redeclare
export enum PrimitiveType {
Mesh, // eslint-disable-line @typescript-eslint/no-shadow
Polyline,
Point,
}
export class Features {
public readonly table: FeatureTable;
public indices: number[] = [];
public uniform = 0;
public initialized = false;
public constructor(table: FeatureTable) { this.table = table; }
public add(feat: Feature, numVerts: number): void {
const index = this.table.insert(feat);
if (!this.initialized) {
// First feature - uniform.
this.uniform = index;
this.initialized = true;
} else if (0 < this.indices.length) {
// Already non-uniform
this.indices.push(index);
} else {
// Second feature - back-fill uniform for existing verts
while (this.indices.length < numVerts - 1)
this.indices.push(this.uniform);
this.indices.push(index);
}
}
public setIndices(indices: number[]) {
this.indices.length = 0;
this.uniform = 0;
this.initialized = 0 < indices.length;
assert(0 < indices.length);
if (1 === indices.length)
this.uniform = indices[0];
else if (1 < indices.length)
this.indices = indices;
}
public toFeatureIndex(index: FeatureIndex): void {
if (!this.initialized) {
index.type = FeatureIndexType.Empty;
} else if (this.indices.length === 0) {
index.type = FeatureIndexType.Uniform;
index.featureID = this.uniform;
} else {
index.type = FeatureIndexType.NonUniform;
index.featureIDs = new Uint32Array(this.indices);
}
}
}
export interface Props {
displayParams: DisplayParams;
features?: Mesh.Features;
type: Mesh.PrimitiveType;
range: Range3d;
is2d: boolean;
isPlanar: boolean;
hasBakedLighting?: boolean;
isVolumeClassifier?: boolean;
}
}
/** @internal */
export class MeshList extends Array<Mesh> {
public readonly features?: FeatureTable;
public readonly range?: Range3d;
constructor(features?: FeatureTable, range?: Range3d) {
super();
this.features = features;
this.range = range;
}
} | the_stack |
import * as Web3 from "web3";
// Utils
import { BigNumber } from "../../utils/bignumber";
import { NULL_ADDRESS } from "../../utils/constants";
import { SignatureUtils } from "../../utils/signature_utils";
import { applyNetworkDefaults } from "../../utils/transaction_utils";
import { Web3Utils } from "../../utils/web3_utils";
// APIs
import { ContractsAPI } from "../apis";
// Types
import { DebtOrderData, TxData } from "../types";
// Wrappers
import {
DebtKernelContract,
DebtOrderDataWrapper,
DebtTokenContract,
ERC20Contract,
TokenTransferProxyContract,
} from "../wrappers";
const BLOCK_TIME_ESTIMATE_SECONDS = 14;
export class OrderAssertions {
private web3Utils: Web3Utils;
private readonly contracts: ContractsAPI;
public constructor(web3: Web3, contracts: ContractsAPI) {
this.web3Utils = new Web3Utils(web3);
this.contracts = contracts;
}
/*
Validity Invariants
*/
// principal >= debtor fee
public validDebtorFee(debtOrderData: DebtOrderData, errorMessage: string) {
if (debtOrderData.principalAmount.lt(debtOrderData.debtorFee)) {
throw new Error(errorMessage);
}
}
// If no underwriter is specified, underwriter fees must be 0
public validUnderwriterFee(debtOrderData: DebtOrderData, errorMessage: string) {
if (
(!debtOrderData.underwriter || debtOrderData.underwriter === NULL_ADDRESS) &&
debtOrderData.underwriterFee.gt(0)
) {
throw new Error(errorMessage);
}
}
// If no relayer is specified, relayer fees must be 0
public validRelayerFee(debtOrderData: DebtOrderData, errorMessage: string) {
if (
(!debtOrderData.relayer || debtOrderData.relayer === NULL_ADDRESS) &&
debtOrderData.relayerFee.gt(0)
) {
throw new Error(errorMessage);
}
}
// creditorFee + debtorFee == relayerFee + underwriterFee
public validFees(debtOrderData: DebtOrderData, errorMessage: string) {
const feesContributed = debtOrderData.creditorFee.plus(debtOrderData.debtorFee);
const feesDistributed = debtOrderData.relayerFee.plus(debtOrderData.underwriterFee);
if (!feesContributed.eq(feesDistributed)) {
throw new Error(errorMessage);
}
}
// Debt order must not be expired
public async notExpired(debtOrderData: DebtOrderData, errorMessage: string) {
const latestBlockTime = await this.web3Utils.getCurrentBlockTime();
const approximateNextBlockTime = latestBlockTime + BLOCK_TIME_ESTIMATE_SECONDS;
if (debtOrderData.expirationTimestampInSec.lt(approximateNextBlockTime)) {
throw new Error(errorMessage);
}
}
// Debt cannot already have been issued
public async notAlreadyIssuedAsync(
debtOrderData: DebtOrderData,
debtToken: DebtTokenContract,
errorMessage: string,
) {
debtOrderData = await applyNetworkDefaults(debtOrderData, this.contracts);
const debtOrderDataWrapped = new DebtOrderDataWrapper(debtOrderData);
const orderIssued = await debtToken.exists.callAsync(
new BigNumber(debtOrderDataWrapped.getIssuanceCommitmentHash()),
);
if (orderIssued) {
throw new Error(errorMessage);
}
}
/**
* If the given DebtOrder is cancelled, throws the given errorMessage.
*
* @param {debtOrderData} DebtOrderData
* @param {DebtKernelContract} debtKernel
* @param {string} errorMessage
* @returns {Promise<void>}
*/
public async debtOrderNotCancelledAsync(
debtOrderData: DebtOrderData,
debtKernel: DebtKernelContract,
errorMessage: string,
): Promise<void> {
const orderCancelled = await this.isCancelled(debtOrderData, debtKernel);
if (orderCancelled) {
throw new Error(errorMessage);
}
}
// Issuance cannot have been cancelled
public async issuanceNotCancelledAsync(
debtOrderData: DebtOrderData,
debtKernel: DebtKernelContract,
errorMessage: string,
) {
debtOrderData = await applyNetworkDefaults(debtOrderData, this.contracts);
const debtOrderDataWrapped = new DebtOrderDataWrapper(debtOrderData);
if (
await debtKernel.issuanceCancelled.callAsync(
debtOrderDataWrapped.getIssuanceCommitmentHash(),
)
) {
throw new Error(errorMessage);
}
}
public senderAuthorizedToCancelOrder(
debtOrderData: DebtOrderData,
transactionOptions: TxData,
errorMessage: string,
) {
if (debtOrderData.debtor !== transactionOptions.from) {
throw new Error(errorMessage);
}
}
public senderAuthorizedToCancelIssuance(
debtOrderData: DebtOrderData,
transactionOptions: TxData,
errorMessage: string,
) {
if (
debtOrderData.debtor !== transactionOptions.from &&
debtOrderData.underwriter !== transactionOptions.from
) {
throw new Error(errorMessage);
}
}
/*
Consensuality Invariants
*/
// If message sender not debtor, debtor signature must be valid
public async validDebtorSignature(
debtOrderData: DebtOrderData,
transactionOptions: TxData,
errorMessage: string,
) {
const debtOrderDataWrapped = new DebtOrderDataWrapper(debtOrderData);
if (transactionOptions.from !== debtOrderData.debtor) {
if (
!SignatureUtils.isValidSignature(
debtOrderDataWrapped.getDebtorCommitmentHash(),
debtOrderData.debtorSignature,
debtOrderData.debtor,
)
) {
throw new Error(errorMessage);
}
}
}
// If message sender not creditor, creditor signature must be valid
public async validCreditorSignature(
debtOrderData: DebtOrderData,
transactionOptions: TxData,
errorMessage: string,
) {
debtOrderData = await applyNetworkDefaults(debtOrderData, this.contracts);
const debtOrderDataWrapped = new DebtOrderDataWrapper(debtOrderData);
if (transactionOptions.from !== debtOrderData.creditor) {
if (
!SignatureUtils.isValidSignature(
debtOrderDataWrapped.getCreditorCommitmentHash(),
debtOrderData.creditorSignature,
debtOrderData.creditor,
)
) {
throw new Error(errorMessage);
}
}
}
// If message sender not underwriter AND underwriter exists, underwriter signature must be valid
public async validUnderwriterSignature(
debtOrderData: DebtOrderData,
transactionOptions: TxData,
errorMessage: string,
) {
debtOrderData = await applyNetworkDefaults(debtOrderData, this.contracts);
const debtOrderDataWrapped = new DebtOrderDataWrapper(debtOrderData);
if (transactionOptions.from !== debtOrderData.underwriter) {
if (
!SignatureUtils.isValidSignature(
debtOrderDataWrapped.getUnderwriterCommitmentHash(),
debtOrderData.underwriterSignature,
debtOrderData.underwriter,
)
) {
throw new Error(errorMessage);
}
}
}
/*
External invariants
*/
// Creditor balance > principal + fee
public async sufficientCreditorBalanceAsync(
debtOrderData: DebtOrderData,
principalToken: ERC20Contract,
errorMessage: string,
) {
const creditorBalance = await principalToken.balanceOf.callAsync(debtOrderData.creditor);
if (creditorBalance.lt(debtOrderData.principalAmount.plus(debtOrderData.creditorFee))) {
throw new Error(errorMessage);
}
}
// Creditor Allowance to TokenTransferProxy >= principal + creditorFee
public async sufficientCreditorAllowanceAsync(
debtOrderData: DebtOrderData,
principalToken: ERC20Contract,
tokenTransferProxy: TokenTransferProxyContract,
errorMessage: string,
) {
const creditorAllowance = await principalToken.allowance.callAsync(
debtOrderData.creditor,
tokenTransferProxy.address,
);
if (creditorAllowance.lt(debtOrderData.principalAmount.plus(debtOrderData.creditorFee))) {
throw new Error(errorMessage);
}
}
/*
For collateralized debt orders.
*/
public async sufficientCollateralizerAllowanceAsync(
debtOrderData: DebtOrderData,
collateralToken: ERC20Contract,
collateralAmount: BigNumber,
tokenTransferProxy: TokenTransferProxyContract,
errorMessage: string,
) {
const collateralizerAllowance = await collateralToken.allowance.callAsync(
debtOrderData.debtor,
tokenTransferProxy.address,
);
if (collateralizerAllowance.lt(collateralAmount)) {
throw new Error(errorMessage);
}
}
public async sufficientCollateralizerBalanceAsync(
debtOrderData: DebtOrderData,
collateralToken: ERC20Contract,
collateralAmount: BigNumber,
errorMessage: string,
) {
const collateralizerBalance = await collateralToken.balanceOf.callAsync(
debtOrderData.debtor,
);
if (collateralizerBalance.lt(collateralAmount)) {
throw new Error(errorMessage);
}
}
/**
* Given a DebtOrder instance, eventually returns true if that DebtOrder has
* been cancelled. Returns false otherwise.
*
* @example
* await dharma.order.isCancelled(debtOrder, debtKernel);
* => false
*
* @param {DebtOrderData} debtOrderData
* @param {DebtKernelContract} debtKernel
* @returns {Promise<boolean>}
*/
private async isCancelled(
debtOrderData: DebtOrderData,
debtKernel: DebtKernelContract,
): Promise<boolean> {
debtOrderData = await applyNetworkDefaults(debtOrderData, this.contracts);
const debtOrderWrapped = new DebtOrderDataWrapper(debtOrderData);
return debtKernel.debtOrderCancelled.callAsync(debtOrderWrapped.getDebtorCommitmentHash());
}
} | the_stack |
import { Variant } from 'js-slang/dist/types';
import { Grading, GradingOverview } from '../../../../features/grading/GradingTypes';
import {
Assessment,
AssessmentOverview,
AssessmentStatuses,
GradingStatuses
} from '../../../assessment/AssessmentTypes';
import { Notification } from '../../../notificationBadge/NotificationBadgeTypes';
import { defaultSession, GameState, Role, Story } from '../../ApplicationTypes';
import { LOG_OUT } from '../../types/CommonsTypes';
import {
SessionState,
SET_ADMIN_PANEL_COURSE_REGISTRATIONS,
SET_ASSESSMENT_CONFIGURATIONS,
SET_COURSE_CONFIGURATION,
SET_COURSE_REGISTRATION,
SET_GITHUB_ACCESS_TOKEN,
SET_TOKENS,
SET_USER,
UPDATE_ASSESSMENT,
UPDATE_ASSESSMENT_OVERVIEWS,
UPDATE_GRADING,
UPDATE_GRADING_OVERVIEWS,
UPDATE_INFINITE_LOOP_ENCOUNTERED,
UPDATE_NOTIFICATIONS
} from '../../types/SessionTypes';
import { SessionsReducer } from '../SessionsReducer';
test('LOG_OUT works correctly on default session', () => {
const action = {
type: LOG_OUT,
payload: {}
};
const result: SessionState = SessionsReducer(defaultSession, action);
expect(result).toEqual(defaultSession);
});
test('SET_TOKEN sets accessToken and refreshToken correctly', () => {
const accessToken = 'access_token_test';
const refreshToken = 'refresh_token_test';
const action = {
type: SET_TOKENS,
payload: {
accessToken,
refreshToken
}
};
const result: SessionState = SessionsReducer(defaultSession, action);
expect(result).toEqual({
...defaultSession,
...action.payload
});
});
test('SET_USER works correctly', () => {
const payload = {
name: 'test student',
role: Role.Student,
courses: [
{
courseId: 1,
courseName: `CS1101 Programming Methodology (AY20/21 Sem 1)`,
courseShortName: `CS1101S`,
viewable: true
},
{
courseId: 2,
courseName: `CS2030S Programming Methodology II (AY20/21 Sem 2)`,
courseShortName: `CS2030S`,
viewable: true
}
]
};
const action = {
type: SET_USER,
payload
};
const result: SessionState = SessionsReducer(defaultSession, action);
expect(result).toEqual({
...defaultSession,
...payload
});
});
test('SET_COURSE_CONFIGURATION works correctly', () => {
const payload = {
courseName: `CS1101 Programming Methodology (AY20/21 Sem 1)`,
courseShortName: `CS1101S`,
viewable: true,
enableGame: true,
enableAchievements: true,
enableSourcecast: true,
sourceChapter: 1,
sourceVariant: 'default' as Variant,
moduleHelpText: 'Help text',
assessmentTypes: ['Missions', 'Quests', 'Paths', 'Contests', 'Others']
};
const action = {
type: SET_COURSE_CONFIGURATION,
payload
};
const result: SessionState = SessionsReducer(defaultSession, action);
expect(result).toEqual({
...defaultSession,
...payload
});
});
test('SET_COURSE_REGISTRATION works correctly', () => {
const payload = {
role: Role.Student,
group: '42D',
gameState: {
collectibles: {},
completed_quests: []
} as GameState,
courseId: 1,
grade: 1,
maxGrade: 10,
xp: 1,
story: {
story: '',
playStory: false
} as Story,
agreedToReseach: true
};
const action = {
type: SET_COURSE_REGISTRATION,
payload
};
const result: SessionState = SessionsReducer(defaultSession, action);
expect(result).toEqual({
...defaultSession,
...payload
});
});
test('SET_ASSESSMENT_CONFIGURATIONS works correctly', () => {
const payload = [
{
assessmentConfigId: 1,
type: 'Mission1',
buildHidden: false,
buildSolution: false,
isContest: false,
hoursBeforeEarlyXpDecay: 48,
earlySubmissionXp: 200
},
{
assessmentConfigId: 1,
type: 'Mission1',
buildHidden: false,
buildSolution: false,
isContest: false,
hoursBeforeEarlyXpDecay: 48,
earlySubmissionXp: 200
},
{
assessmentConfigId: 1,
type: 'Mission1',
buildHidden: false,
buildSolution: false,
isContest: false,
hoursBeforeEarlyXpDecay: 48,
earlySubmissionXp: 200
}
];
const action = {
type: SET_ASSESSMENT_CONFIGURATIONS,
payload
};
const result: SessionState = SessionsReducer(defaultSession, action);
expect(result).toEqual({
...defaultSession,
assessmentConfigurations: payload
});
});
test('SET_ADMIN_PANEL_COURSE_REGISTRATIONS works correctly', () => {
const payload = [
{
courseRegId: 1,
courseId: 1,
name: 'Bob',
role: Role.Student
},
{
courseRegId: 2,
courseId: 1,
name: 'Avenger',
role: Role.Staff
}
];
const action = {
type: SET_ADMIN_PANEL_COURSE_REGISTRATIONS,
payload
};
const result: SessionState = SessionsReducer(defaultSession, action);
expect(result).toEqual({
...defaultSession,
userCourseRegistrations: payload
});
});
test('SET_GITHUB_ACCESS_TOKEN works correctly', () => {
const token = 'githubAccessToken';
const action = {
type: SET_GITHUB_ACCESS_TOKEN,
payload: token
};
const result: SessionState = SessionsReducer(defaultSession, action);
expect(result).toEqual({
...defaultSession,
githubAccessToken: token
});
});
// Test Data for UPDATE_ASSESSMENT
const assessmentTest1: Assessment = {
type: 'Mission',
globalDeployment: undefined,
graderDeployment: undefined,
id: 1,
longSummary: 'long summary here',
missionPDF: 'www.google.com',
questions: [],
title: 'first assessment'
};
const assessmentTest2: Assessment = {
type: 'Contest',
globalDeployment: undefined,
graderDeployment: undefined,
id: 1,
longSummary: 'another long summary',
missionPDF: 'www.comp.nus.edu.sg',
questions: [],
title: 'updated first assessment'
};
const assessmentTest3: Assessment = {
type: 'Path',
globalDeployment: undefined,
graderDeployment: undefined,
id: 3,
longSummary: 'another long summary here',
missionPDF: 'www.yahoo.com',
questions: [],
title: 'path'
};
test('UPDATE_ASSESSMENT works correctly in inserting assessment', () => {
const action = {
type: UPDATE_ASSESSMENT,
payload: assessmentTest1
};
const resultMap: Map<number, Assessment> = SessionsReducer(defaultSession, action).assessments;
expect(resultMap.get(assessmentTest1.id)).toEqual(assessmentTest1);
});
test('UPDATE_ASSESSMENT works correctly in inserting assessment and retains old data', () => {
const assessments = new Map<number, Assessment>();
assessments.set(assessmentTest3.id, assessmentTest3);
const newDefaultSession: SessionState = {
...defaultSession,
assessments
};
const action = {
type: UPDATE_ASSESSMENT,
payload: assessmentTest2
};
const resultMap: Map<number, Assessment> = SessionsReducer(newDefaultSession, action).assessments;
expect(resultMap.get(assessmentTest2.id)).toEqual(assessmentTest2);
expect(resultMap.get(assessmentTest3.id)).toEqual(assessmentTest3);
});
test('UPDATE_ASSESSMENT works correctly in updating assessment', () => {
const assessments = new Map<number, Assessment>();
assessments.set(assessmentTest1.id, assessmentTest1);
const newDefaultSession = {
...defaultSession,
assessments
};
const action = {
type: UPDATE_ASSESSMENT,
payload: assessmentTest2
};
const resultMap: Map<number, Assessment> = SessionsReducer(newDefaultSession, action).assessments;
expect(resultMap.get(assessmentTest2.id)).toEqual(assessmentTest2);
});
// Test data for UPDATE_ASSESSMENT_OVERVIEWS
const assessmentOverviewsTest1: AssessmentOverview[] = [
{
type: 'Missions',
isManuallyGraded: true,
closeAt: 'test_string',
coverImage: 'test_string',
id: 0,
maxXp: 0,
openAt: 'test_string',
title: 'test_string',
shortSummary: 'test_string',
status: AssessmentStatuses.not_attempted,
story: null,
xp: 0,
gradingStatus: GradingStatuses.none
}
];
const assessmentOverviewsTest2: AssessmentOverview[] = [
{
type: 'Contests',
isManuallyGraded: true,
closeAt: 'test_string_0',
coverImage: 'test_string_0',
fileName: 'test_sting_0',
id: 1,
maxXp: 1,
openAt: 'test_string_0',
title: 'test_string_0',
shortSummary: 'test_string_0',
status: AssessmentStatuses.attempted,
story: null,
xp: 1,
gradingStatus: GradingStatuses.grading
}
];
test('UPDATE_ASSESSMENT_OVERVIEWS works correctly in inserting assessment overviews', () => {
const action = {
type: UPDATE_ASSESSMENT_OVERVIEWS,
payload: assessmentOverviewsTest1
};
const result: SessionState = SessionsReducer(defaultSession, action);
expect(result).toEqual({
...defaultSession,
assessmentOverviews: assessmentOverviewsTest1
});
});
test('UPDATE_ASSESSMENT_OVERVIEWS works correctly in updating assessment overviews', () => {
const newDefaultSession = {
...defaultSession,
assessmentOverviews: assessmentOverviewsTest1
};
const assessmentOverviewsPayload = [...assessmentOverviewsTest2, ...assessmentOverviewsTest1];
const action = {
type: UPDATE_ASSESSMENT_OVERVIEWS,
payload: assessmentOverviewsPayload
};
const result: SessionState = SessionsReducer(newDefaultSession, action);
expect(result).toEqual({
...defaultSession,
assessmentOverviews: assessmentOverviewsPayload
});
});
// Test data for UPDATE_GRADING
const gradingTest1: Grading = [
{
question: jest.genMockFromModule('../../../../features/grading/GradingTypes'),
student: {
name: 'test student',
id: 234
},
grade: {
xp: 100,
xpAdjustment: 0,
comments: 'Well done. Please try the quest!'
}
}
];
const gradingTest2: Grading = [
{
question: jest.genMockFromModule('../../../../features/grading/GradingTypes'),
student: {
name: 'another test student',
id: 345
},
grade: {
xp: 500,
xpAdjustment: 20,
comments: 'Good job! All the best for the finals.'
}
}
];
test('UPDATE_GRADING works correctly in inserting gradings', () => {
const submissionId = 23;
const action = {
type: UPDATE_GRADING,
payload: {
submissionId,
grading: gradingTest1
}
};
const gradingMap: Map<number, Grading> = SessionsReducer(defaultSession, action).gradings;
expect(gradingMap.get(submissionId)).toEqual(gradingTest1);
});
test('UPDATE_GRADING works correctly in inserting gradings and retains old data', () => {
const submissionId1 = 45;
const submissionId2 = 56;
const gradings = new Map<number, Grading>();
gradings.set(submissionId1, gradingTest1);
const newDefaultSession = {
...defaultSession,
gradings
};
const action = {
type: UPDATE_GRADING,
payload: {
submissionId: submissionId2,
grading: gradingTest2
}
};
const gradingMap: Map<number, Grading> = SessionsReducer(newDefaultSession, action).gradings;
expect(gradingMap.get(submissionId1)).toEqual(gradingTest1);
expect(gradingMap.get(submissionId2)).toEqual(gradingTest2);
});
test('UPDATE_GRADING works correctly in updating gradings', () => {
const submissionId = 23;
const gradings = new Map<number, Grading>();
gradings.set(submissionId, gradingTest1);
const newDefaultSession = {
...defaultSession,
gradings
};
const action = {
type: UPDATE_GRADING,
payload: {
submissionId,
grading: gradingTest2
}
};
const gradingMap: Map<number, Grading> = SessionsReducer(newDefaultSession, action).gradings;
expect(gradingMap.get(submissionId)).toEqual(gradingTest2);
});
// UPDATE_GRADING_OVERVIEWS test data
const gradingOverviewTest1: GradingOverview[] = [
{
assessmentId: 1,
assessmentName: 'test assessment',
assessmentType: 'Contests',
initialXp: 0,
xpBonus: 100,
xpAdjustment: 50,
currentXp: 50,
maxXp: 500,
studentId: 100,
studentName: 'test student',
submissionId: 1,
submissionStatus: 'attempting',
groupName: 'group',
gradingStatus: 'excluded',
questionCount: 0,
gradedCount: 6
}
];
const gradingOverviewTest2: GradingOverview[] = [
{
assessmentId: 2,
assessmentName: 'another assessment',
assessmentType: 'Quests',
initialXp: 20,
xpBonus: 250,
xpAdjustment: 100,
currentXp: 300,
maxXp: 1000,
studentId: 20,
studentName: 'another student',
submissionId: 2,
submissionStatus: 'attempted',
groupName: 'another group',
gradingStatus: 'excluded',
questionCount: 6,
gradedCount: 0
}
];
test('UPDATE_GRADING_OVERVIEWS works correctly in inserting grading overviews', () => {
const action = {
type: UPDATE_GRADING_OVERVIEWS,
payload: gradingOverviewTest1
};
const result: SessionState = SessionsReducer(defaultSession, action);
expect(result.gradingOverviews).toEqual(gradingOverviewTest1);
});
test('UPDATE_GRADING_OVERVIEWS works correctly in updating grading overviews', () => {
const newDefaultSession = {
...defaultSession,
gradingOverviews: gradingOverviewTest1
};
const gradingOverviewsPayload = [...gradingOverviewTest2, ...gradingOverviewTest1];
const action = {
type: UPDATE_GRADING_OVERVIEWS,
payload: gradingOverviewsPayload
};
const result: SessionState = SessionsReducer(newDefaultSession, action);
expect(result.gradingOverviews).toEqual(gradingOverviewsPayload);
});
test('UPDATE_INFINITE_LOOP_ENCOUNTERED works correctly in updating had infinite loop flag', () => {
const newDefaultSession = {
...defaultSession,
hadPreviousInfiniteLoop: false
};
const action = {
type: UPDATE_INFINITE_LOOP_ENCOUNTERED
};
const result: SessionState = SessionsReducer(newDefaultSession, action);
expect(result.hadPreviousInfiniteLoop).toEqual(true);
});
test('UPDATE_NOTIFICATIONS works correctly in updating notifications', () => {
const notifications: Notification[] = [
{
id: 1,
type: 'new',
assessment_id: 1,
assessment_type: 'Mission',
assessment_title: 'The Secret to Streams'
},
{
id: 2,
type: 'new',
assessment_id: 2,
assessment_type: 'Sidequest',
assessment_title: 'A sample Sidequest'
}
];
const action = {
type: UPDATE_NOTIFICATIONS,
payload: notifications
};
const result: SessionState = SessionsReducer(defaultSession, action);
expect(result.notifications).toEqual(notifications);
}); | the_stack |
"use strict";
// Typescript imports
import Rect = require("./rect");
import Css = require("./css");
import BlokAdapter = require("./blok-adapter");
import Blok = require("./blok");
import BlokUserSettings = require("./blok-user-settings");
import BlokContainer = require("./blok-container");
import BlokContainerUserSettings = require("./blok-container-user-settings");
import Utils = require("./utils");
// npm imports
var JSON2: any = require("JSON2");
/**
* Raise an event to be handled by the CEP layer indicating that there has been
* an unhandled exception.
*
* @param ex The raw exception object
*/
function raiseException(ex) {
var xLib = new ExternalObject("lib:\PlugPlugExternalObject");
var eventObj = new CSXSEvent();
eventObj.type = "com.westonthayer.bloks.events.JsxExceptionRaised";
eventObj.data = JSON2.stringify(ex);
eventObj.dispatch();
}
/**
* Verify that there is a Document object to work with. Returns false
* if Illustrator doesn't have any documents in focus.
*/
function isActiveDocumentPresent(): boolean {
try {
let doc = app.activeDocument;
return true;
}
catch (ex) {
if (ex.message === "No such element") {
return false;
}
else {
raiseException(ex);
}
}
}
/** Check to see if the given PageItem is the root art of a Symbol. */
function isPageItemSymbolRoot(pageItem: any): boolean {
return pageItem.parent &&
pageItem.parent.parent &&
pageItem.parent.parent.name === "Symbol Editing Mode";
}
// Global variables
var bloksToBeInvalidated = []; // A cache of Bloks to call invalidate() on when its possible to do so
var lastSelection; // Tracks the most recent result of app.activeDocument.selection
export function checkSelectionForRelayout(): void {
try {
if (isActiveDocumentPresent()) {
let sel = app.activeDocument.selection;
if (sel.length === 1) {
let pageItem = sel[0];
if (pageItem) { // can be undefined when text ranges are selected
if (BlokAdapter.shouldBlokBeAttached(pageItem)) {
let blok = BlokAdapter.getBlok(pageItem);
if (blok) {
blok.checkForRelayout(lastSelection);
}
}
else if (BlokAdapter.isBlokContainerAttached(pageItem)) {
let blokContainer = BlokAdapter.getBlokContainer(pageItem);
blokContainer.checkForRelayout(lastSelection);
}
else if (isPageItemSymbolRoot(pageItem)) {
// We're editing a Symbol. Special cases to make this important scenario work
let symName = pageItem.parent.name;
// Use the document's list of symbols to find the Bloks that wrap the symbol
for (let i = 0; i < app.activeDocument.symbolItems.length; i++) {
let symItem = app.activeDocument.symbolItems[i];
if (symItem.symbol.name === symName && BlokAdapter.shouldBlokBeAttached(symItem)) {
let blok = BlokAdapter.getBlok(symItem);
// Illustrator will refuse to run layout because we're in Symbol Editing Mode, so make a
// list of Bloks to invalidate the next chance we get
bloksToBeInvalidated.push(blok);
}
}
}
}
}
else {
// Ensure we're not in any sort of mode where invalidation would fail
if (app.activeDocument.activeLayer.name !== "Isolation Mode" &&
(app.activeDocument.activeLayer.parent &&
app.activeDocument.activeLayer.parent.name !== "Symbol Editing Mode")) {
// Don't call invalidate on Bloks that share the same root BlokContainer since
// that's wasted work
let roots = [];
bloksToBeInvalidated.forEach((blok: Blok) => {
let root = blok.getRootContainer();
let alreadyInvalid = false;
roots.forEach((r: BlokContainer) => {
if (r.equals(root)) {
alreadyInvalid = true;
}
});
if (!alreadyInvalid) {
roots.push(root);
blok.invalidate();
}
});
// Clear the list
bloksToBeInvalidated.splice(0, bloksToBeInvalidated.length);
}
}
lastSelection = sel;
}
}
catch (ex) {
raiseException(ex);
}
}
export function relayoutSelection(): void {
try {
let sel = app.activeDocument.selection;
if (sel.length === 1) {
let pageItem = sel[0];
if (BlokAdapter.shouldBlokBeAttached(pageItem)) {
let blok = BlokAdapter.getBlok(pageItem);
if (blok) {
blok.invalidate();
}
}
else if (BlokAdapter.isBlokContainerAttached(pageItem)) {
let blokContainer = BlokAdapter.getBlokContainer(pageItem);
blokContainer.invalidate();
}
}
}
catch (ex) {
raiseException(ex);
}
}
/**
*
* @param settings
*/
export function updateSelectedBlok(settings: BlokUserSettings): void {
try {
let sel = app.activeDocument.selection;
if (sel.length === 1) {
let pageItem = sel[0];
if (BlokAdapter.shouldBlokBeAttached(pageItem)) {
let blok = BlokAdapter.getBlok(pageItem, settings);
blok.invalidate();
}
else if (isPageItemSymbolRoot(pageItem)) {
let symName = pageItem.parent.name;
let blok: Blok = undefined;
// Use the document's list of symbols to find the Bloks that wrap the symbol
for (let i = 0; i < app.activeDocument.symbolItems.length; i++) {
let symItem = app.activeDocument.symbolItems[i];
if (symItem.symbol.name === symName && BlokAdapter.shouldBlokBeAttached(symItem)) {
if (!blok) {
blok = BlokAdapter.getBlok(pageItem, settings, true);
}
let symBlok = BlokAdapter.getBlok(symItem, blok.getUserSettings());
bloksToBeInvalidated.push(symBlok);
}
}
}
else {
throw new Error("We're not updating a Blok!");
}
}
else {
throw new Error("Can only update one Blok at a time!");
}
}
catch (ex) {
raiseException(ex);
}
}
export function updateSelectedBlokContainer(settings: BlokContainerUserSettings): void {
try {
let sel = app.activeDocument.selection;
if (sel.length === 1) {
let pageItem = sel[0];
if (!BlokAdapter.isBlokContainerAttached(pageItem)) {
throw new Error("We're not updating a BlokContainer!");
}
let blokContainer = BlokAdapter.getBlokContainer(pageItem, settings);
blokContainer.invalidate();
}
else {
throw new Error("Can only update one BlokContainer at a time!");
}
}
catch (ex) {
raiseException(ex);
}
}
/**
* Group the current selection and turn it into a BlokContainer.
*
* @param settings - user settings for the container. Child items will take their current dimensions
*/
export function createBlokContainerFromSelection(settings: BlokContainerUserSettings): void {
try {
let sel = app.activeDocument.selection;
if (sel.length > 1) {
// Find the correct Z order, since adding a new group will put it on top
// The Illustrator behavior is to insert the group in place of the highest
// selected item
let z = 0;
let par = sel[0].parent; // since zOrderPosition is broken, use the parent's order
sel.forEach((pageItem) => {
// Loop last to first (low z to high z)
for (let i = par.pageItems.length - 1; i >= 0; i--) {
if (pageItem === par.pageItems[i]) {
// invert i so that it maps to z positioning (where 0 is lowest)
let invI = Math.abs(i - (par.pageItems.length - 1));
if (invI > z) {
z = invI;
}
}
}
});
z -= sel.length - 1;
// Add the new group at the hightest z position
let groupPageItem = par.groupItems.add();
groupPageItem.name = "<BlokGroup>";
sel.forEach((pageItem) => {
pageItem.move(groupPageItem, ElementPlacement.PLACEATEND);
});
// Now fix the z order
groupPageItem.zOrder(ZOrderMethod.SENDTOBACK);
for (let i = 0; i < z; i++) {
groupPageItem.zOrder(ZOrderMethod.BRINGFORWARD);
}
let blokContainer = BlokAdapter.getBlokContainer(groupPageItem, settings);
blokContainer.invalidate();
}
else {
throw new Error("Must have multiple items selected to group them!");
}
}
catch (ex) {
raiseException(ex);
}
}
/**
* Check the active document's current selection and report back what
* Bloks can do with it.
*
* @returns a JSON string with two properties:
* action: number - a single option of what Bloks can do
* 0 - no operations available. Either there's nothing selected,
* or there's just a single non-Blok object selected, or
* a Blok child could be in Isolation Mode
* 1 - a Blok container is selected, we can modify it
* 2 - a Blok child is selected, we can modify it
* 3 - multiple objects are selected, we can create a Blok container
* blok: the properties of the selected Blok, if there is one. Otherwise undefined
*/
export function getActionsFromSelection(): { action: number, blok: any } {
try {
let ret = {
action: 0,
blok: undefined
};
if (isActiveDocumentPresent()) {
let selection = app.activeDocument.selection;
if (selection.length === 0) {
// No operations available
}
else if (selection.length === 1) {
let pageItem = selection[0];
if (pageItem) { // can be undefined for text ranges
if (BlokAdapter.shouldBlokBeAttached(pageItem)) {
let blok = BlokAdapter.getBlok(pageItem);
if (blok) {
ret.action = 2;
ret.blok = blok.getUserSettings();
ret.blok.parentBlokContainer = blok.getContainer().getUserSettings();
if (pageItem.typename === "TextFrame" && pageItem.kind === TextType.AREATEXT) {
ret.blok.isAreaText = true;
}
}
}
else if (BlokAdapter.isBlokContainerAttached(pageItem)) {
let blokContainer = BlokAdapter.getBlokContainer(pageItem);
ret.action = 1;
ret.blok = blokContainer.getUserSettings();
if (pageItem.parent && BlokAdapter.isBlokContainerAttached(pageItem.parent)) {
ret.blok.isAlsoChild = true;
ret.blok.parentBlokContainer = blokContainer.getContainer().getUserSettings();
}
}
else if (isPageItemSymbolRoot(pageItem)) {
let symName = pageItem.parent.name;
// Use the document's list of symbols to find the Bloks that wrap the symbol
for (let i = 0; i < app.activeDocument.symbolItems.length; i++) {
let symItem = app.activeDocument.symbolItems[i];
if (symItem.symbol.name === symName) {
if (BlokAdapter.shouldBlokBeAttached(symItem)) {
let blok = BlokAdapter.getBlok(pageItem, undefined, true);
ret.action = 2;
ret.blok = blok.getUserSettings();
//ret.blok.parentBlokContainer = blok.getContainer().getUserSettings();
if (pageItem.typename === "TextFrame" && pageItem.kind === TextType.AREATEXT) {
ret.blok.isAreaText = true;
}
break;
}
}
}
}
else {
// Can't do anything with just a single non-Blok item
}
}
}
else {
// The only thing you can do with multiple items is group them
ret.action = 3;
}
}
return JSON2.stringify(ret);
}
catch (ex) {
raiseException(ex);
}
}
/**
* Look for PageItems with ".spacer" in their name and change their opacity.
*
* @param opacity - the new opacity value
*/
function changeSpacerOpacity(opacity: number): void {
try {
let pageItems = app.activeDocument.pageItems;
for (let i = 0; i < pageItems.length; i++) {
let pageItem = pageItems[i];
let name = pageItem.name;
if (!name && pageItem.symbol) {
name = pageItem.symbol.name;
}
if (Utils.isKeyInString(name, ".spacer")) {
try {
pageItem.opacity = opacity;
}
catch (ex) {
if (ex.message === "Target layer cannot be modified") {
// That's OK, it's in Isolation Mode. We'll do what we can, the
// user can always exit Isolation Mode and try again.
}
else {
throw ex;
}
}
}
}
}
catch (ex) {
raiseException(ex);
}
}
export function hideSpacers(): void {
changeSpacerOpacity(0.0);
}
export function showSpacers(): void {
changeSpacerOpacity(100.0);
} | the_stack |
import { Subscription, Subject, Observable } from 'rxjs';
import {
IRange,
EChartMode,
} from '../../../controller/session/dependencies/timestamps/session.dependency.timestamps';
import { Session } from '../../../controller/session/session';
import { IPC } from '../../../services/service.electron.ipc';
import TabsSessionsService from '../../../services/service.sessions.tabs';
import EventsSessionService from '../../../services/standalone/service.events.session';
import ElectronIpcService from '../../../services/service.electron.ipc';
import * as Toolkit from 'chipmunk.client.toolkit';
export { EChartMode };
export interface IZoomEvent {
x: number;
width: number;
change: number;
}
export interface IMoveEvent {
width: number;
change: number;
}
export class DataService {
public readonly SCALED_ROW_HEIGHT: number = 50;
public readonly MAX_BAR_HEIGHT: number = 16;
public readonly MIN_BAR_HEIGHT: number = 2;
public readonly MIN_ZOOMING_PX: number = 20;
public readonly MIN_DISTANCE_SCALE_RATE: number = 0.5;
private _refs: number[] = [];
private _ranges: IRange[] = [];
private _subscriptions: { [key: string]: Subscription } = {};
private _sessionSubscriptions: { [key: string]: Subscription } = {};
private _logger: Toolkit.Logger = new Toolkit.Logger('MeasurementDataService');
private _session: Session | undefined;
private _mode: EChartMode = EChartMode.aligned;
private _offset: number = 1;
private _subjects: {
update: Subject<void>; // Updates happens in scope of session
change: Subject<void>; // Session was changed
zoom: Subject<void>;
mode: Subject<void>;
} = {
update: new Subject(),
change: new Subject(),
zoom: new Subject(),
mode: new Subject(),
};
constructor() {
this._subscriptions.onSessionChange =
EventsSessionService.getObservable().onSessionChange.subscribe(
this._onSessionChange.bind(this),
);
this._onSessionChange(TabsSessionsService.getActive());
}
destroy() {
Object.keys(this._subscriptions).forEach((key: string) => {
this._subscriptions[key].unsubscribe();
});
Object.keys(this._sessionSubscriptions).forEach((key: string) => {
this._sessionSubscriptions[key].unsubscribe();
});
}
public getObservable(): {
update: Observable<void>;
change: Observable<void>;
zoom: Observable<void>;
mode: Observable<void>;
} {
return {
update: this._subjects.update.asObservable(),
change: this._subjects.change.asObservable(),
zoom: this._subjects.zoom.asObservable(),
mode: this._subjects.mode.asObservable(),
};
}
public getMode(): EChartMode {
return this._mode;
}
public toggleMode() {
if (this._session === undefined) {
return;
}
this._session
.getTimestamp()
.setMode(this._mode === EChartMode.aligned ? EChartMode.scaled : EChartMode.aligned);
}
public getChartDataset(overview: boolean = false): {
datasets: any[];
labels: string[];
maxY?: number;
} {
if (overview) {
return this._getChartDatasetModeScale(true);
} else {
switch (this._mode) {
case EChartMode.aligned:
return this._getChartDatasetModeAlign();
case EChartMode.scaled:
return this._getChartDatasetModeScale();
}
}
}
public getRefs(): number[] {
return this._refs;
}
public getMinTimestamp(): number {
return this._session === undefined ? 0 : this._session.getTimestamp().getMinTimestamp();
}
public getMaxTimestamp(): number {
return this._session === undefined ? 0 : this._session.getTimestamp().getMaxTimestamp();
}
public getMaxDuration(): number {
return this._session === undefined ? 0 : this._getMaxDurationPerGroups();
}
public getMinXAxe(applyCursorOffset: boolean = true): number {
const cursor = this.getCursorState();
if (cursor === undefined) {
return 0;
}
const min = this.getMinTimestamp();
return min + (applyCursorOffset ? cursor.left : 0);
}
public getMaxXAxe(applyCursorOffset: boolean = true): number {
const cursor = this.getCursorState();
if (cursor === undefined) {
return 0;
}
const max = this.getMaxTimestamp() - this._offset;
return max - (applyCursorOffset ? cursor.right : 0);
}
public getRangesCount(): number {
return this._getComplitedRanges().length;
}
public getGroups(): Map<number, IRange[]> {
const groups: Map<number, IRange[]> = new Map();
this._getComplitedRanges().forEach((range: IRange) => {
const ranges: IRange[] = groups.has(range.group)
? (groups.get(range.group) as IRange[])
: [];
ranges.push(range);
groups.set(range.group, ranges);
});
groups.forEach((ranges: IRange[], groupId: number) => {
ranges = ranges.sort((a, b) => {
return a.start.position < b.start.position ? -1 : 1;
});
groups.set(groupId, ranges);
});
return groups;
}
public zoom(event: IZoomEvent) {
if (this._session === undefined) {
return;
}
const cursor = this.getCursorState();
if (cursor === undefined) {
return;
}
const point: number = event.x / event.width;
const duration: number = this.getMaxTimestamp() - this._offset - this.getMinTimestamp();
const limit: number = (duration / event.width) * this.MIN_ZOOMING_PX;
const minT = this.getMinTimestamp();
const maxT = this.getMaxTimestamp() - this._offset;
const min = minT + cursor.left;
const max = maxT - cursor.right;
const step = Math.abs(max - min) / event.width;
let left = cursor.left + event.change * point * step;
let right = cursor.right + event.change * (1 - point) * step;
if (minT + left < minT) {
left = 0;
}
if (maxT - right > maxT) {
right = 0;
}
if (maxT - right - (minT + left) < limit) {
const allowed = duration - limit;
right = allowed * (right / (right + left));
left = allowed - right;
}
this._session.getTimestamp().setZoomOffsets(left, right);
}
public setZoomOffsets(left: number, right: number) {
if (this._session === undefined) {
return;
}
this._session.getTimestamp().setZoomOffsets(left, right);
}
public move(event: IMoveEvent) {
const cursor = this.getCursorState();
if (cursor === undefined) {
return;
}
const minT = this.getMinTimestamp();
const maxT = this.getMaxTimestamp() - this._offset;
const min = minT + cursor.left;
const max = maxT - cursor.right;
const _left = cursor.left;
const _right = cursor.right;
const step = Math.abs(max - min) / event.width;
let left = cursor.left + event.change * step;
let right = cursor.right - event.change * step;
if (left < 0) {
left = 0;
right = cursor.right + _left;
} else if (maxT - right > maxT) {
right = 0;
left = cursor.left + _right;
}
this.setZoomOffsets(left, right);
}
public getCursorState():
| undefined
| {
left: number;
right: number;
} {
if (this._session === undefined) {
return undefined;
}
return this._session.getTimestamp().getCursorState();
}
public getDuration(): number {
return this.getMaxTimestamp() - this._offset - this.getMinTimestamp();
}
public getOptimizationState(): boolean {
if (this._session === undefined) {
return false;
}
return this._session.getTimestamp().getOptimization();
}
public toggleOptimizationState() {
if (this._session === undefined) {
return;
}
this._session
.getTimestamp()
.setOptimization(!this._session.getTimestamp().getOptimization());
}
public exportToCSV() {
const id: string = Toolkit.guid();
ElectronIpcService.request<IPC.TimestampExtractResponse>(
new IPC.TimestampExportCSVRequest({
id: id,
csv: this._getRangesAsCSV(),
}),
IPC.TimestampExportCSVResponse,
).then((response) => {
if (response.error) {
this._logger.warn(`Fail to export time ranges data due error: ${response.error}`);
}
});
}
public discover(update: boolean = false): Promise<void> {
return new Promise((resolve, reject) => {
if (this._session === undefined) {
return reject(new Error(this._logger.warn(`Session object isn't available`)));
}
this._session.getTimestamp().discover(update).then(resolve).catch(reject);
// TODO: Probably we should prevent multiple execution of discover feature - it doesn't make sence
// to start discove several times for same session.
});
}
private _getRangesAsCSV(): string {
const VALUE_DIV = ',';
const content: string[] = [
[
'Range #',
'Start Timestamp',
'End Timestamp',
'Duration',
'Start Row Number',
'End Row Number',
'Start Row',
'End Row',
].join(VALUE_DIV),
];
this.getGroups().forEach((ranges: IRange[], groupId: number) => {
ranges.forEach((range: IRange, index: number) => {
const values: string[] = [];
if (
range.end === undefined ||
range.start === undefined ||
range.start.timestamp === undefined ||
range.end.timestamp === undefined
) {
return;
}
values.push(index === 0 ? groupId.toString() : '');
values.push(
...[
range.start.timestamp.toString(),
range.end.timestamp.toString(),
range.duration.toString(),
range.start.position.toString(),
range.end.position.toString(),
`"${range.start.str.replace(/"/gi, '""')}"`,
`"${range.end.str.replace(/"/gi, '""')}"`,
],
);
content.push(values.join(VALUE_DIV));
});
});
return content.join('\n');
}
private _getChartDatasetModeAlign(): {
datasets: any[];
labels: string[];
maxY?: number;
} {
const labels: string[] = [];
const datasets: any[] = [];
const groups: Map<number, IRange[]> = this.getGroups();
let y: number = 1;
groups.forEach((ranges: IRange[], groupId: number) => {
let offset: number = 0;
ranges.forEach((range: IRange, index: number) => {
if (
range.end === undefined ||
range.start === undefined ||
range.start.position === undefined ||
range.end.position === undefined
) {
return;
}
const normalized = this._getNormalizedRange(range);
// y += 1;
const values: Array<{
x: number;
y: number;
duration?: number;
range?: boolean;
row?: number;
}> = [
{
x: offset,
y: y,
},
{
x: offset + normalized.duration,
y: y,
duration: normalized.duration,
row:
range.start.position < range.end.position
? range.start.position
: range.end.position,
range: true,
},
];
datasets.push({
data: values,
borderColor: range.color,
borderWidth: this.MAX_BAR_HEIGHT,
pointBackgroundColor: [range.color, range.color],
pointBorderColor: [range.color, range.color],
pointRadius: 0,
pointHoverRadius: 0,
fill: false,
tension: 0,
showLine: true,
range: range,
});
offset += normalized.duration;
});
y += 1;
});
return {
datasets: datasets,
labels: labels,
maxY: y,
};
}
private _getChartDatasetModeScale(overview: boolean = false): {
datasets: any[];
labels: string[];
maxY?: number;
} {
if (this._session === undefined) {
return { datasets: [], labels: [], maxY: 0 };
}
this._offset = 0;
const labels: string[] = [];
let datasets: any[] = [];
const groups: Map<number, IRange[]> = this.getGroups();
let y: number = 1;
let prev: any;
const params = {
distance: {
count: 0,
duration: 0,
middle: 0,
},
ranges: {
count: 0,
duration: 0,
middle: 0,
},
};
// Building datasets
groups.forEach((ranges: IRange[], groupId: number) => {
const borders = this._getGroupBorders(groupId);
if (prev !== undefined && ranges.length > 0) {
const values: Array<{ x: number; y: number; duration?: number }> = [
{
x: borders.max,
y: y - 0.5,
},
{
x: prev.min,
y: y - 0.5,
duration: Math.abs(borders.max - prev.min),
},
];
datasets.push({
data: values,
borderColor: '#999999',
borderWidth: overview ? 0 : 1,
pointBackgroundColor: ['#999999', '#999999'],
pointBorderColor: ['#999999', '#999999'],
pointRadius: 0,
pointHoverRadius: 0,
fill: false,
tension: 0,
showLine: !overview,
});
params.distance.count += 1;
params.distance.duration += values[1].duration as number;
}
let offset: number = borders.min;
ranges.forEach((range: IRange, index: number) => {
if (
range.end === undefined ||
range.start === undefined ||
range.start.position === undefined ||
range.end.position === undefined
) {
return;
}
const normalized = this._getNormalizedRange(range);
// y += 1;
const values: Array<{
x: number;
y: number;
duration?: number;
range?: boolean;
row?: number;
}> = [
{
x: offset,
y: y,
},
{
x: offset + normalized.duration,
y: y,
duration: normalized.duration,
row:
range.start.position < range.end.position
? range.start.position
: range.end.position,
range: true,
},
];
datasets.push({
data: values,
borderColor: range.color,
borderWidth: overview ? this.MIN_BAR_HEIGHT : this.MAX_BAR_HEIGHT,
pointBackgroundColor: [range.color, range.color],
pointBorderColor: [range.color, range.color],
pointRadius: 0,
pointHoverRadius: 0,
fill: false,
tension: 0,
showLine: true,
range: range,
});
offset += normalized.duration;
params.ranges.count += 1;
params.ranges.duration += values[1].duration as number;
});
prev = borders;
y += 1;
});
if (this._session.getTimestamp().getOptimization()) {
params.distance.middle = params.distance.duration / params.distance.count;
params.ranges.middle = params.ranges.duration / params.ranges.count;
const rate: number = params.ranges.middle / params.distance.middle;
if (rate < this.MIN_DISTANCE_SCALE_RATE) {
// Distances have to be optimized
const targetMiddle = params.ranges.middle / this.MIN_DISTANCE_SCALE_RATE;
const change = targetMiddle / params.distance.middle;
datasets.reverse();
datasets = datasets.map((dataset) => {
if (dataset.range !== undefined) {
dataset.data[0].x -= this._offset;
dataset.data[1].x -= this._offset;
} else {
dataset.data[0].x -= this._offset;
const move = Math.floor(dataset.data[1].duration * change);
dataset.data[1].x = dataset.data[0].x + move;
this._offset += dataset.data[1].duration - move;
dataset.optimized = true;
}
return dataset;
});
datasets.reverse();
}
}
return {
datasets: datasets,
labels: labels,
maxY: y,
};
}
private _getGroupBorders(group: number): { min: number; max: number; duration: number } {
let min: number = Infinity;
let max: number = -1;
this._getComplitedRanges().forEach((range: IRange) => {
if (
range.end === undefined ||
range.start === undefined ||
range.start.timestamp === undefined ||
range.end.timestamp === undefined
) {
return;
}
if (range.group !== group) {
return;
}
if (range.end.timestamp < min) {
min = range.end.timestamp;
}
if (range.start.timestamp < min) {
min = range.start.timestamp;
}
if (range.end.timestamp > max) {
max = range.end.timestamp;
}
if (range.start.timestamp > max) {
max = range.start.timestamp;
}
});
return { min: min, max: max, duration: Math.abs(max - min) };
}
private _getMaxDurationPerGroups(): number {
const groups = this.getGroups();
let duration = -1;
groups.forEach((_, groupId: number) => {
const borders = this._getGroupBorders(groupId);
if (duration < borders.duration) {
duration = borders.duration;
}
});
return duration;
}
private _getComplitedRanges(): IRange[] {
return this._ranges
.filter((range: IRange) => {
return range.end !== undefined;
})
.sort((a: IRange, b: IRange) => {
if (a.start.timestamp === undefined || b.start.timestamp === undefined) {
return 0;
}
return a.start.timestamp < b.start.timestamp ? 1 : -1;
});
}
private _getNormalizedRange(range: IRange): { min: number; max: number; duration: number } {
if (
range.end === undefined ||
range.start === undefined ||
range.start.timestamp === undefined ||
range.end.timestamp === undefined
) {
return { min: 0, max: 0, duration: 0 };
}
const result = {
min:
range.start.timestamp < range.end.timestamp
? range.start.timestamp
: range.end.timestamp,
max:
range.start.timestamp > range.end.timestamp
? range.start.timestamp
: range.end.timestamp,
duration: 0,
};
result.duration = Math.abs(result.max - result.min);
return result;
}
private _refresh(ranges?: IRange[], change: boolean = false) {
this._ranges =
ranges instanceof Array
? ranges
: this._session === undefined
? []
: this._session.getTimestamp().getRanges();
if (!change) {
this._subjects.update.next();
} else {
this._subjects.change.next();
}
}
private _onSessionChange(controller?: Session) {
Object.keys(this._sessionSubscriptions).forEach((key: string) => {
this._sessionSubscriptions[key].unsubscribe();
});
if (controller !== undefined) {
this._sessionSubscriptions.update = controller
.getTimestamp()
.getObservable()
.update.subscribe(this._onRangesUpdate.bind(this));
this._sessionSubscriptions.mode = controller
.getTimestamp()
.getObservable()
.mode.subscribe(this._onModeChange.bind(this));
this._sessionSubscriptions.zoom = controller
.getTimestamp()
.getObservable()
.zoom.subscribe(this._onZoom.bind(this));
this._sessionSubscriptions.optimization = controller
.getTimestamp()
.getObservable()
.optimization.subscribe(this._onOptimization.bind(this));
this._mode = controller.getTimestamp().getMode();
this._session = controller;
} else {
this._session = undefined;
}
this._refresh(undefined, true);
}
private _onRangesUpdate(ranges: IRange[]) {
this._refresh(ranges);
}
private _onModeChange(mode: EChartMode) {
this._mode = mode;
this._refresh(undefined, true);
this._subjects.mode.next();
}
private _onOptimization() {
this._refresh(undefined, true);
}
private _onZoom() {
this._subjects.zoom.next();
}
} | the_stack |
import {
Component,
OnInit,
OnDestroy,
DoCheck,
ViewEncapsulation,
ChangeDetectionStrategy,
Input,
ElementRef,
ChangeDetectorRef,
Optional,
Self,
Output,
EventEmitter,
TemplateRef,
ContentChild,
ContentChildren,
QueryList,
AfterViewInit,
ViewChild,
} from '@angular/core';
import { ControlValueAccessor, NgControl } from '@angular/forms';
import { MatFormFieldControl } from '@angular/material/form-field';
import { BooleanInput, coerceBooleanProperty } from '@angular/cdk/coercion';
import { FocusMonitor } from '@angular/cdk/a11y';
import { Subject, merge } from 'rxjs';
import { takeUntil, startWith } from 'rxjs/operators';
import {
MtxSelectOptionTemplateDirective,
MtxSelectLabelTemplateDirective,
MtxSelectHeaderTemplateDirective,
MtxSelectFooterTemplateDirective,
MtxSelectOptgroupTemplateDirective,
MtxSelectNotFoundTemplateDirective,
MtxSelectTypeToSearchTemplateDirective,
MtxSelectLoadingTextTemplateDirective,
MtxSelectMultiLabelTemplateDirective,
MtxSelectTagTemplateDirective,
MtxSelectLoadingSpinnerTemplateDirective,
} from './templates.directive';
import { MtxOptionComponent } from './option.component';
import { NgSelectComponent } from '@ng-select/ng-select';
export type DropdownPosition = 'bottom' | 'top' | 'auto';
export type AddTagFn = (term: string) => any | Promise<any>;
export type CompareWithFn = (a: any, b: any) => boolean;
export type GroupValueFn = (
key: string | Record<string, any>,
children: any[]
) => string | Record<string, any>;
export type SearchFn = (term: string, item: any) => boolean;
export type TrackByFn = (item: any) => any;
export function isDefined(value: any) {
return value !== undefined && value !== null;
}
let nextUniqueId = 0;
@Component({
selector: 'mtx-select',
exportAs: 'mtxSelect',
host: {
'[attr.id]': 'id',
'[attr.aria-describedby]': '_ariaDescribedby || null',
'[class.mtx-select-floating]': 'shouldLabelFloat',
'[class.mtx-select-invalid]': 'errorState',
'class': 'mtx-select',
},
templateUrl: './select.component.html',
styleUrls: ['./select.component.scss'],
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [{ provide: MatFormFieldControl, useExisting: MtxSelectComponent }],
})
export class MtxSelectComponent
implements
OnInit,
OnDestroy,
DoCheck,
AfterViewInit,
ControlValueAccessor,
MatFormFieldControl<any>
{
@ViewChild('ngSelect', { static: true }) ngSelect!: NgSelectComponent;
// MtxSelect custom templates
@ContentChild(MtxSelectOptionTemplateDirective, { read: TemplateRef })
optionTemplate!: TemplateRef<any>;
@ContentChild(MtxSelectOptgroupTemplateDirective, { read: TemplateRef })
optgroupTemplate!: TemplateRef<any>;
@ContentChild(MtxSelectLabelTemplateDirective, { read: TemplateRef })
labelTemplate!: TemplateRef<any>;
@ContentChild(MtxSelectMultiLabelTemplateDirective, { read: TemplateRef })
multiLabelTemplate!: TemplateRef<any>;
@ContentChild(MtxSelectHeaderTemplateDirective, { read: TemplateRef })
headerTemplate!: TemplateRef<any>;
@ContentChild(MtxSelectFooterTemplateDirective, { read: TemplateRef })
footerTemplate!: TemplateRef<any>;
@ContentChild(MtxSelectNotFoundTemplateDirective, { read: TemplateRef })
notFoundTemplate!: TemplateRef<any>;
@ContentChild(MtxSelectTypeToSearchTemplateDirective, { read: TemplateRef })
typeToSearchTemplate!: TemplateRef<any>;
@ContentChild(MtxSelectLoadingTextTemplateDirective, { read: TemplateRef })
loadingTextTemplate!: TemplateRef<any>;
@ContentChild(MtxSelectTagTemplateDirective, { read: TemplateRef })
tagTemplate!: TemplateRef<any>;
@ContentChild(MtxSelectLoadingSpinnerTemplateDirective, { read: TemplateRef })
loadingSpinnerTemplate!: TemplateRef<any>;
@ContentChildren(MtxOptionComponent, { descendants: true })
mtxOptions!: QueryList<MtxOptionComponent>;
/** MtxSelect options */
@Input() addTag: boolean | AddTagFn = false;
@Input() addTagText = 'Add item';
@Input() appearance = 'underline';
@Input() appendTo!: string;
@Input() bindLabel!: string;
@Input() bindValue!: string;
@Input() closeOnSelect = true;
@Input() clearAllText = 'Clear all';
@Input() clearable = true;
@Input() clearOnBackspace = true;
@Input() compareWith!: CompareWithFn;
@Input() dropdownPosition: DropdownPosition = 'auto';
@Input() groupBy!: string | (() => void);
@Input() groupValue!: GroupValueFn;
@Input() selectableGroup = false;
@Input() selectableGroupAsModel = true;
@Input() hideSelected = false;
@Input() isOpen!: boolean;
@Input() loading = false;
@Input() loadingText = 'Loading...';
@Input() labelForId: string | null = null;
@Input() markFirst = true;
@Input() maxSelectedItems!: number;
@Input() multiple = false;
@Input() notFoundText = 'No items found';
@Input() searchable = true;
@Input() readonly = false;
@Input() searchFn: SearchFn | null = null;
@Input() searchWhileComposing = true;
@Input() selectOnTab = false;
@Input() trackByFn: TrackByFn | null = null;
@Input() inputAttrs: { [key: string]: string } = {};
@Input() tabIndex!: number;
@Input() openOnEnter!: boolean;
@Input() minTermLength = 0;
@Input() editableSearchTerm = false;
@Input() keyDownFn = (_: KeyboardEvent) => true;
@Input() virtualScroll = false;
@Input() typeToSearchText = 'Type to search';
@Input() typeahead!: Subject<string>;
@Output('blur') blurEvent = new EventEmitter();
@Output('focus') focusEvent = new EventEmitter();
@Output('change') changeEvent = new EventEmitter();
@Output('open') openEvent = new EventEmitter();
@Output('close') closeEvent = new EventEmitter();
@Output('search') searchEvent = new EventEmitter<{ term: string; items: any[] }>();
@Output('clear') clearEvent = new EventEmitter();
@Output('add') addEvent = new EventEmitter();
@Output('remove') removeEvent = new EventEmitter();
@Output('scroll') scroll = new EventEmitter<{ start: number; end: number }>();
@Output('scrollToEnd') scrollToEnd = new EventEmitter();
@Input()
get clearSearchOnAdd() {
return isDefined(this._clearSearchOnAdd) ? this._clearSearchOnAdd : this.closeOnSelect;
}
set clearSearchOnAdd(value) {
this._clearSearchOnAdd = value;
}
private _clearSearchOnAdd!: boolean;
@Input()
get items() {
return this._items;
}
set items(value: any[]) {
this._itemsAreUsed = true;
this._items = value;
}
private _items: any[] = [];
private _itemsAreUsed!: boolean;
private readonly _destroy$ = new Subject<void>();
/** Value of the select control. */
@Input()
get value(): any {
return this._value;
}
set value(newValue: any) {
this._value = newValue;
this._onChange(newValue);
this.stateChanges.next();
}
private _value = null;
/** Implemented as part of MatFormFieldControl. */
readonly stateChanges: Subject<void> = new Subject<void>();
/** Unique id of the element. */
@Input()
get id(): string {
return this._id;
}
set id(value: string) {
this._id = value || this._uid;
this.stateChanges.next();
}
private _id!: string;
/** Unique id for this input. */
private _uid = `mtx-select-${nextUniqueId++}`;
/** Placeholder to be shown if value is empty. */
@Input()
get placeholder(): string {
return this._placeholder;
}
set placeholder(value: string) {
this._placeholder = value;
this.stateChanges.next();
}
private _placeholder!: string;
/** Whether the input is focused. */
get focused(): boolean {
return this._focused;
}
private _focused = false;
get empty(): boolean {
return this.value == null || (Array.isArray(this.value) && this.value.length === 0);
}
get shouldLabelFloat(): boolean {
return this.focused || !this.empty;
}
@Input()
get required(): boolean {
return this._required;
}
set required(value: boolean) {
this._required = coerceBooleanProperty(value);
this.stateChanges.next();
}
private _required = false;
@Input()
get disabled(): boolean {
return this._disabled;
}
set disabled(value: boolean) {
this._disabled = coerceBooleanProperty(value);
this.readonly = this._disabled;
this.stateChanges.next();
}
private _disabled = false;
errorState = false;
/** A name for this control that can be used by `mat-form-field`. */
controlType = 'mtx-select';
/** The aria-describedby attribute on the select for improved a11y. */
_ariaDescribedby!: string;
/** `View -> model callback called when value changes` */
_onChange: (value: any) => void = () => {};
/** `View -> model callback called when select has been touched` */
_onTouched = () => {};
constructor(
private _focusMonitor: FocusMonitor,
private _elementRef: ElementRef<HTMLElement>,
private _changeDetectorRef: ChangeDetectorRef,
@Optional() @Self() public ngControl: NgControl
) {
_focusMonitor.monitor(_elementRef, true).subscribe(origin => {
if (this._focused && !origin) {
this._onTouched();
}
this._focused = !!origin;
this.stateChanges.next();
});
if (this.ngControl != null) {
this.ngControl.valueAccessor = this;
}
}
ngOnInit() {
// Fix compareWith warning of undefined value
// https://github.com/ng-select/ng-select/issues/1537
if (this.compareWith) {
this.ngSelect.compareWith = this.compareWith;
}
}
ngAfterViewInit() {
if (!this._itemsAreUsed) {
this._setItemsFromMtxOptions();
}
}
ngDoCheck(): void {
if (this.ngControl) {
this.errorState = (this.ngControl.invalid && this.ngControl.touched) as boolean;
this.stateChanges.next();
}
}
ngOnDestroy() {
this._destroy$.next();
this._destroy$.complete();
this.stateChanges.complete();
this._focusMonitor.stopMonitoring(this._elementRef);
}
/** Implemented as part of MatFormFieldControl. */
setDescribedByIds(ids: string[]) {
this._ariaDescribedby = ids.join(' ');
}
/**
* Disables the select. Part of the ControlValueAccessor interface required
* to integrate with Angular's core forms API.
*
* @param isDisabled Sets whether the component is disabled.
*/
setDisabledState(isDisabled: boolean) {
this.disabled = isDisabled;
}
/** Implemented as part of MatFormFieldControl. */
onContainerClick(event: MouseEvent) {
const target = event.target as HTMLElement;
if (/mat-form-field|mtx-select/g.test(target.parentElement?.classList[0] || '')) {
this.focus();
this.open();
}
}
/**
* Sets the select's value. Part of the ControlValueAccessor interface
* required to integrate with Angular's core forms API.
*
* @param value New value to be written to the model.
*/
writeValue(value: any): void {
this.value = value;
this._changeDetectorRef.markForCheck();
}
/**
* Saves a callback function to be invoked when the select's value
* changes from user input. Part of the ControlValueAccessor interface
* required to integrate with Angular's core forms API.
*
* @param fn Callback to be triggered when the value changes.
*/
registerOnChange(fn: any): void {
this._onChange = fn;
}
/**
* Saves a callback function to be invoked when the select is blurred
* by the user. Part of the ControlValueAccessor interface required
* to integrate with Angular's core forms API.
*
* @param fn Callback to be triggered when the component has been touched.
*/
registerOnTouched(fn: any): void {
this._onTouched = fn;
}
/** NgSelect: _setItemsFromNgOptions */
private _setItemsFromMtxOptions() {
const mapMtxOptions = (options: QueryList<MtxOptionComponent>) => {
this.items = options.map(option => ({
$ngOptionValue: option.value,
$ngOptionLabel: option.elementRef.nativeElement.innerHTML,
disabled: option.disabled,
}));
this.ngSelect.itemsList.setItems(this.items);
if (this.ngSelect.hasValue) {
this.ngSelect.itemsList.mapSelectedItems();
}
this.ngSelect.detectChanges();
};
const handleOptionChange = () => {
const changedOrDestroyed = merge(this.mtxOptions.changes, this._destroy$);
merge(...this.mtxOptions.map(option => option.stateChange$))
.pipe(takeUntil(changedOrDestroyed))
.subscribe(option => {
const item = this.ngSelect.itemsList.findItem(option.value);
item.disabled = option.disabled;
item.label = option.label || item.label;
this.ngSelect.detectChanges();
});
};
this.mtxOptions.changes
.pipe(startWith(this.mtxOptions), takeUntil(this._destroy$))
.subscribe(options => {
mapMtxOptions(options);
handleOptionChange();
});
}
open() {
this.ngSelect.open();
}
close() {
this.ngSelect.close();
}
focus() {
this.ngSelect.focus();
}
blur() {
this.ngSelect.blur();
}
static ngAcceptInputType_required: BooleanInput;
static ngAcceptInputType_disabled: BooleanInput;
} | the_stack |
// clang-format off
import {ContentSetting, ContentSettingsTypes, SiteDetailsPermissionElement, SiteSettingSource, SiteSettingsPrefsBrowserProxyImpl} from 'chrome://settings/lazy_load.js';
import {assertDeepEquals, assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js';
import {TestSiteSettingsPrefsBrowserProxy} from './test_site_settings_prefs_browser_proxy.js';
import {createContentSettingTypeToValuePair, createDefaultContentSetting, createRawSiteException, createSiteSettingsPrefs, SiteSettingsPref} from './test_util.js';
// clang-format on
/** @fileoverview Suite of tests for site-details. */
suite('SiteDetailsPermission', function() {
/**
* A site list element created before each test.
*/
let testElement: SiteDetailsPermissionElement;
/**
* The mock proxy object to use during test.
*/
let browserProxy: TestSiteSettingsPrefsBrowserProxy;
/**
* An example pref with only camera allowed.
*/
let prefs: SiteSettingsPref;
// Initialize a site-details-permission before each test.
setup(function() {
prefs = createSiteSettingsPrefs(
[createContentSettingTypeToValuePair(
ContentSettingsTypes.CAMERA, createDefaultContentSetting({
setting: ContentSetting.ALLOW,
}))],
[createContentSettingTypeToValuePair(
ContentSettingsTypes.CAMERA,
[createRawSiteException('https://www.example.com')])]);
browserProxy = new TestSiteSettingsPrefsBrowserProxy();
SiteSettingsPrefsBrowserProxyImpl.setInstance(browserProxy);
document.body.innerHTML = '';
testElement = document.createElement('site-details-permission');
document.body.appendChild(testElement);
});
function validatePermissionFlipWorks(
origin: string, expectedContentSetting: ContentSetting) {
browserProxy.resetResolver('setOriginPermissions');
// Simulate permission change initiated by the user.
testElement.$.permission.value = expectedContentSetting;
testElement.$.permission.dispatchEvent(new CustomEvent('change'));
return browserProxy.whenCalled('setOriginPermissions').then((args) => {
assertEquals(origin, args[0]);
assertDeepEquals(testElement.category, args[1]);
assertEquals(expectedContentSetting, args[2]);
});
}
test('camera category', function() {
const origin = 'https://www.example.com';
browserProxy.setPrefs(prefs);
testElement.category = ContentSettingsTypes.CAMERA;
testElement.label = 'Camera';
testElement.site = createRawSiteException(origin, {
origin: origin,
embeddingOrigin: '',
source: SiteSettingSource.PREFERENCE,
});
assertFalse(testElement.$.details.hidden);
const header =
testElement.$.details.querySelector<HTMLElement>('#permissionHeader')!;
assertEquals(
'Camera', header.innerText!.trim(),
'Widget should be labelled correctly');
// Flip the permission and validate that prefs stay in sync.
return validatePermissionFlipWorks(origin, ContentSetting.ALLOW)
.then(() => {
return validatePermissionFlipWorks(origin, ContentSetting.BLOCK);
})
.then(() => {
return validatePermissionFlipWorks(origin, ContentSetting.ALLOW);
})
.then(() => {
return validatePermissionFlipWorks(origin, ContentSetting.DEFAULT);
});
});
test('default string is correct', function() {
const origin = 'https://www.example.com';
browserProxy.setPrefs(prefs);
testElement.category = ContentSettingsTypes.CAMERA;
testElement.label = 'Camera';
testElement.site = createRawSiteException(origin, {
origin: origin,
embeddingOrigin: '',
setting: ContentSetting.ALLOW,
source: SiteSettingSource.PREFERENCE,
});
return browserProxy.whenCalled('getDefaultValueForContentType')
.then((args) => {
// Check getDefaultValueForContentType was called for camera category.
assertEquals(ContentSettingsTypes.CAMERA, args);
// The default option will always be the first in the menu.
assertEquals(
'Allow (default)', testElement.$.permission.options[0]!.text,
'Default setting string should match prefs');
browserProxy.resetResolver('getDefaultValueForContentType');
const defaultPrefs = createSiteSettingsPrefs(
[createContentSettingTypeToValuePair(
ContentSettingsTypes.CAMERA,
createDefaultContentSetting(
{setting: ContentSetting.BLOCK}))],
[]);
browserProxy.setPrefs(defaultPrefs);
return browserProxy.whenCalled('getDefaultValueForContentType');
})
.then((args) => {
assertEquals(ContentSettingsTypes.CAMERA, args);
assertEquals(
'Block (default)', testElement.$.permission.options[0]!.text,
'Default setting string should match prefs');
browserProxy.resetResolver('getDefaultValueForContentType');
const defaultPrefs = createSiteSettingsPrefs(
[createContentSettingTypeToValuePair(
ContentSettingsTypes.CAMERA, createDefaultContentSetting())],
[]);
browserProxy.setPrefs(defaultPrefs);
return browserProxy.whenCalled('getDefaultValueForContentType');
})
.then((args) => {
assertEquals(ContentSettingsTypes.CAMERA, args);
assertEquals(
'Ask (default)', testElement.$.permission.options[0]!.text,
'Default setting string should match prefs');
});
});
test('info string is correct', function() {
const origin = 'https://www.example.com';
testElement.category = ContentSettingsTypes.CAMERA;
// Strings that should be shown for the permission sources that don't depend
// on the ContentSetting value.
const permissionSourcesNoSetting: Map<SiteSettingSource, string> = new Map([
[SiteSettingSource.DEFAULT, ''],
[SiteSettingSource.EMBARGO, 'Automatically blocked'],
[SiteSettingSource.INSECURE_ORIGIN, 'Blocked to protect your privacy'],
[
SiteSettingSource.KILL_SWITCH,
'Temporarily blocked to protect your security'
],
[SiteSettingSource.PREFERENCE, ''],
]);
for (const [source, str] of permissionSourcesNoSetting) {
testElement.site = createRawSiteException(origin, {
origin: origin,
embeddingOrigin: origin,
setting: ContentSetting.BLOCK,
source,
});
assertEquals(
str +
(str.length === 0 ? 'Block (default)\nAllow\nBlock\nAsk' :
'\nBlock (default)\nAllow\nBlock\nAsk'),
testElement.$.permissionItem.innerText.trim());
assertEquals(
str !== '',
testElement.$.permissionItem.classList.contains('two-line'));
if (source !== SiteSettingSource.DEFAULT &&
source !== SiteSettingSource.PREFERENCE &&
source !== SiteSettingSource.EMBARGO) {
assertTrue(testElement.$.permission.disabled);
} else {
assertFalse(testElement.$.permission.disabled);
}
}
// Permissions that have been set by extensions.
const extensionSourceStrings: Map<ContentSetting, string> = new Map([
[ContentSetting.ALLOW, 'Allowed by an extension'],
[ContentSetting.BLOCK, 'Blocked by an extension'],
[ContentSetting.ASK, 'Setting controlled by an extension'],
]);
for (const [setting, str] of extensionSourceStrings) {
testElement.site = createRawSiteException(origin, {
origin: origin,
embeddingOrigin: origin,
setting,
source: SiteSettingSource.EXTENSION,
});
assertEquals(
str + '\nBlock (default)\nAllow\nBlock\nAsk',
testElement.$.permissionItem.innerText.trim());
assertTrue(testElement.$.permissionItem.classList.contains('two-line'));
assertTrue(testElement.$.permission.disabled);
assertEquals(setting, testElement.$.permission.value);
}
// Permissions that have been set by enterprise policy.
const policySourceStrings: Map<ContentSetting, string> = new Map([
[ContentSetting.ALLOW, 'Allowed by your administrator'],
[ContentSetting.ASK, 'Setting controlled by your administrator'],
[ContentSetting.BLOCK, 'Blocked by your administrator'],
]);
for (const [setting, str] of policySourceStrings) {
testElement.site = createRawSiteException(origin, {
origin: origin,
embeddingOrigin: origin,
setting,
source: SiteSettingSource.POLICY,
});
assertEquals(
str + '\nBlock (default)\nAllow\nBlock\nAsk',
testElement.$.permissionItem.innerText.trim());
assertTrue(testElement.$.permissionItem.classList.contains('two-line'));
assertTrue(testElement.$.permission.disabled);
assertEquals(setting, testElement.$.permission.value);
}
// Finally, check if changing the source from a non-user-controlled setting
// (policy) back to a user-controlled one re-enables the control.
testElement.site = createRawSiteException(origin, {
origin: origin,
embeddingOrigin: origin,
setting: ContentSetting.ASK,
source: SiteSettingSource.DEFAULT,
});
assertEquals(
'Ask (default)\nAllow\nBlock\nAsk',
testElement.$.permissionItem.innerText.trim());
assertFalse(testElement.$.permissionItem.classList.contains('two-line'));
assertFalse(testElement.$.permission.disabled);
});
test('info string correct for ads', function() {
const origin = 'https://www.example.com';
testElement.category = ContentSettingsTypes.ADS;
testElement.site = createRawSiteException(origin, {
origin: origin,
embeddingOrigin: origin,
setting: ContentSetting.BLOCK,
source: SiteSettingSource.ADS_FILTER_BLACKLIST,
});
assertEquals(
'Site shows intrusive or misleading ads' +
'\nAllow\nBlock\nAsk',
testElement.$.permissionItem.innerText.trim());
assertTrue(testElement.$.permissionItem.classList.contains('two-line'));
assertFalse(testElement.$.permission.disabled);
// Check the string that shows when ads is blocked but not blacklisted.
testElement.site = createRawSiteException(origin, {
origin: origin,
embeddingOrigin: origin,
setting: ContentSetting.BLOCK,
source: SiteSettingSource.PREFERENCE,
});
assertEquals(
'Block if site shows intrusive or misleading ads' +
'\nAllow\nBlock\nAsk',
testElement.$.permissionItem.innerText.trim());
assertTrue(testElement.$.permissionItem.classList.contains('two-line'));
assertFalse(testElement.$.permission.disabled);
// Ditto for default block settings.
testElement.site = createRawSiteException(origin, {
origin: origin,
embeddingOrigin: origin,
setting: ContentSetting.BLOCK,
source: SiteSettingSource.DEFAULT,
});
assertEquals(
'Block if site shows intrusive or misleading ads' +
'\nBlock (default)\nAllow\nBlock\nAsk',
testElement.$.permissionItem.innerText.trim());
assertTrue(testElement.$.permissionItem.classList.contains('two-line'));
assertFalse(testElement.$.permission.disabled);
// Allowing ads for unblacklisted sites shows nothing.
testElement.site = createRawSiteException(origin, {
origin: origin,
embeddingOrigin: origin,
setting: ContentSetting.ALLOW,
source: SiteSettingSource.PREFERENCE,
});
assertEquals(
'Block (default)\nAllow\nBlock\nAsk',
testElement.$.permissionItem.innerText.trim());
assertFalse(testElement.$.permissionItem.classList.contains('two-line'));
assertFalse(testElement.$.permission.disabled);
});
test('info string correct for allowlisted source', function() {
const origin = 'chrome://test';
testElement.category = ContentSettingsTypes.NOTIFICATIONS;
testElement.$.details.hidden = false;
testElement.site = createRawSiteException(origin, {
origin: origin,
embeddingOrigin: origin,
setting: ContentSetting.ALLOW,
source: SiteSettingSource.ALLOWLIST,
});
assertEquals(
'Allowlisted internally\nAllow\nBlock\nAsk',
testElement.$.permissionItem.innerText.trim());
assertTrue(testElement.$.permissionItem.classList.contains('two-line'));
assertTrue(testElement.$.permission.disabled);
});
test('sound setting default string is correct', function() {
const origin = 'https://www.example.com';
browserProxy.setPrefs(prefs);
testElement.category = ContentSettingsTypes.SOUND;
testElement.label = 'Sound';
testElement.site = createRawSiteException(origin, {
origin: origin,
embeddingOrigin: '',
setting: ContentSetting.ALLOW,
source: SiteSettingSource.PREFERENCE,
});
return browserProxy.whenCalled('getDefaultValueForContentType')
.then((args) => {
// Check getDefaultValueForContentType was called for sound category.
assertEquals(ContentSettingsTypes.SOUND, args);
// The default option will always be the first in the menu.
assertEquals(
'Allow (default)', testElement.$.permission.options[0]!.text,
'Default setting string should match prefs');
browserProxy.resetResolver('getDefaultValueForContentType');
const defaultPrefs = createSiteSettingsPrefs(
[createContentSettingTypeToValuePair(
ContentSettingsTypes.SOUND,
createDefaultContentSetting(
{setting: ContentSetting.BLOCK}))],
[]);
browserProxy.setPrefs(defaultPrefs);
return browserProxy.whenCalled('getDefaultValueForContentType');
})
.then((args) => {
assertEquals(ContentSettingsTypes.SOUND, args);
assertEquals(
'Mute (default)', testElement.$.permission.options[0]!.text,
'Default setting string should match prefs');
browserProxy.resetResolver('getDefaultValueForContentType');
testElement.useAutomaticLabel = true;
const defaultPrefs = createSiteSettingsPrefs(
[createContentSettingTypeToValuePair(
ContentSettingsTypes.SOUND,
createDefaultContentSetting(
{setting: ContentSetting.ALLOW}))],
[]);
browserProxy.setPrefs(defaultPrefs);
return browserProxy.whenCalled('getDefaultValueForContentType');
})
.then((args) => {
assertEquals(ContentSettingsTypes.SOUND, args);
assertEquals(
'Automatic (default)', testElement.$.permission.options[0]!.text,
'Default setting string should match prefs');
});
});
test('sound setting block string is correct', function() {
const origin = 'https://www.example.com';
browserProxy.setPrefs(prefs);
testElement.category = ContentSettingsTypes.SOUND;
testElement.label = 'Sound';
testElement.site = createRawSiteException(origin, {
origin: origin,
embeddingOrigin: '',
setting: ContentSetting.ALLOW,
source: SiteSettingSource.PREFERENCE,
});
return browserProxy.whenCalled('getDefaultValueForContentType')
.then((args) => {
// Check getDefaultValueForContentType was called for sound category.
assertEquals(ContentSettingsTypes.SOUND, args);
// The block option will always be the third in the menu.
assertEquals(
'Mute', testElement.$.permission.options[2]!.text,
'Block setting string should match prefs');
});
});
test('ASK can be chosen as a preference by users', function() {
const origin = 'https://www.example.com';
testElement.category = ContentSettingsTypes.USB_DEVICES;
testElement.label = 'USB';
testElement.site = createRawSiteException(origin, {
origin: origin,
embeddingOrigin: origin,
setting: ContentSetting.ASK,
source: SiteSettingSource.PREFERENCE,
});
// In addition to the assertions below, the main goal of this test is to
// ensure we do not hit any assertions when choosing ASK as a setting.
assertEquals(testElement.$.permission.value, ContentSetting.ASK);
assertFalse(testElement.$.permission.disabled);
assertFalse(
testElement.$.permission.querySelector<HTMLElement>('#ask')!.hidden);
});
test(
'Bluetooth scanning: ASK/BLOCK can be chosen as a preference by users',
function() {
const origin = 'https://www.example.com';
testElement.category = ContentSettingsTypes.BLUETOOTH_SCANNING;
testElement.label = 'Bluetooth-scanning';
testElement.site = createRawSiteException(origin, {
origin: origin,
embeddingOrigin: origin,
setting: ContentSetting.ASK,
source: SiteSettingSource.PREFERENCE,
});
// In addition to the assertions below, the main goal of this test is to
// ensure we do not hit any assertions when choosing ASK as a setting.
assertEquals(testElement.$.permission.value, ContentSetting.ASK);
assertFalse(testElement.$.permission.disabled);
assertFalse(testElement.$.permission.querySelector<HTMLElement>(
'#ask')!.hidden);
testElement.site = createRawSiteException(origin, {
origin: origin,
embeddingOrigin: origin,
setting: ContentSetting.BLOCK,
source: SiteSettingSource.PREFERENCE,
});
// In addition to the assertions below, the main goal of this test is to
// ensure we do not hit any assertions when choosing BLOCK as a setting.
assertEquals(testElement.$.permission.value, ContentSetting.BLOCK);
assertFalse(testElement.$.permission.disabled);
assertFalse(
testElement.$.permission.querySelector<HTMLElement>(
'#block')!.hidden);
});
test(
'File System Write: ASK/BLOCK can be chosen as a preference by users',
function() {
const origin = 'https://www.example.com';
testElement.category = ContentSettingsTypes.FILE_SYSTEM_WRITE;
testElement.label = 'Save to original files';
testElement.site = createRawSiteException(origin, {
origin: origin,
embeddingOrigin: origin,
setting: ContentSetting.ASK,
source: SiteSettingSource.PREFERENCE,
});
// In addition to the assertions below, the main goal of this test is to
// ensure we do not hit any assertions when choosing ASK as a setting.
assertEquals(testElement.$.permission.value, ContentSetting.ASK);
assertFalse(testElement.$.permission.disabled);
assertFalse(testElement.$.permission.querySelector<HTMLElement>(
'#ask')!.hidden);
testElement.site = createRawSiteException(origin, {
origin: origin,
embeddingOrigin: origin,
setting: ContentSetting.BLOCK,
source: SiteSettingSource.PREFERENCE,
});
// In addition to the assertions below, the main goal of this test is to
// ensure we do not hit any assertions when choosing BLOCK as a setting.
assertEquals(testElement.$.permission.value, ContentSetting.BLOCK);
assertFalse(testElement.$.permission.disabled);
assertFalse(
testElement.$.permission.querySelector<HTMLElement>(
'#block')!.hidden);
});
}); | the_stack |
import fs = require('fs');
import http = require('http');
import path = require('path');
import events = require('events');
import UnzipCommand = require("./installsdk/UnzipCommand");
import utils = require('../lib/utils');
var sdkConfigList = [{ "varName": "ANDROID_HOME", "url": "http://tool.egret-labs.org/Android-SDK/android-sdk_r24.4.1-windows.zip", "installDir": "android-sdk-windows", "fileSize": "196919088" }, { "url": "http://tool.egret-labs.org/Android-SDK/platform-tools_r24-windows.zip", "installDir": "android-sdk-windows/platform-tools", "fileSize": "3744669" }, { "url": "http://tool.egret-labs.org/Android-SDK/build-tools_r24.0.1-windows.zip", "installDir": "android-sdk-windows/build-tools/24.0.1", "fileSize": "48323734" }, { "url": "http://tool.egret-labs.org/Android-SDK/android-19_r04.zip", "installDir": "android-sdk-windows/platforms/android-19", "fileSize": "62590023" }, { "varName": "ANT_HOME", "url": "http://tool.egret-labs.org/Android-SDK/apache-ant-1.8.2-bin.zip", "installDir": "apache-ant-1.8.2", "fileSize": "41491235" }, { "varName": "GRADLE_HOME", "url": "http://tool.egret-labs.org/Android-SDK/gradle-2.9-bin.zip", "installDir": "gradle-2.9", "fileSize": "44652280" }];
function isInEgretMode() {
var isEgret = false;
try {
isEgret = !!egret;
} catch (e) {
}
return isEgret;
}
function print(info) {
var isEgret = isInEgretMode();
if (isEgret && egret.args.ide) {
var out = {
'output': info
}
console.log(JSON.stringify(out));
} else {
console.log(info);
}
}
function getFileStrByCount(count) {
var str = "file";
if (count > 1) {
str += "s";
}
return str;
}
function calcTotalFileSize(list) {
var size = 0;
if (list) {
for (var i = 0; i < list.length; i++) {
var fileSize = parseInt(list[i].fileSize);
size += fileSize;
}
} else {
size = -1;
}
return size;
}
function printAndroidSDKConfig() {
var config = getAndroidSDKConfig();
var outdata = {
'androidSDKInfo': config
}
var isEgret = isInEgretMode();
if (!isEgret || egret.args.ide) {
var str = JSON.stringify(outdata);
console.log(str);
}
}
function getAppDataEnginesRootPath() {
var rootPath;
switch (process.platform) {
case 'darwin':
var home = process.env.HOME || ("/Users/" + (process.env.NAME || process.env.LOGNAME));
if (!home)
return null;
rootPath = home + "/Library/Application Support/Egret/AndroidSDK/";
break;
case 'win32':
var appdata = process.env.AppData || process.env.USERPROFILE + "/AppData/Roaming/";
rootPath = appdata + "/Egret/AndroidSDK/";
break;
default:
;
}
if (!fs.existsSync(rootPath)) {
fs.mkdirSync(rootPath);
}
return rootPath;
}
function getRootPath() {
var root = "";
var isEgret = isInEgretMode();
if (!isEgret) {
root = __dirname;
} else {
root = getAppDataEnginesRootPath();
}
return root;
}
function readFromFile(fileName) {
var str = "";
try {
var data = fs.readFileSync(fileName);
str = data.toString();
} catch (e) {
}
return str;
}
function writeToFile(fileName, data) {
fs.writeFileSync(fileName, data);
}
function getJSONObjectFromFile(configFile) {
var config = null;
var str = readFromFile(configFile);
if (str != "") {
config = JSON.parse(str);
}
return config;
}
function writeJSONObjectToFile(configFile, jsonObj) {
var str = JSON.stringify(jsonObj);
writeToFile(configFile, str);
}
function getConfigFilePathByFileName(fileName) {
var root = getRootPath();
var filePath = path.join(root, fileName);
return filePath;
}
function getAndroidSDKConfigFilePath() {
var fileName = "AndroidSDKConfig.json";
var filePath = getConfigFilePathByFileName(fileName);
return filePath;
}
var AndroidSDKConfig = null;
function getAndroidSDKConfig() {
if (!AndroidSDKConfig) {
var filePath = getAndroidSDKConfigFilePath();
AndroidSDKConfig = getJSONObjectFromFile(filePath);
}
return AndroidSDKConfig;
}
function needAddBinToPath(name) {
var result = false;
if (name == "ANT_HOME" || name == "GRADLE_HOME") {
result = true;
}
return result;
}
function getSDKConfigList() {
return sdkConfigList;
}
var allLocalFilesAndAbsInstallDirs = null;
function getAllLocalFilesAndAbsInstallDirs() {
if (!allLocalFilesAndAbsInstallDirs) {
allLocalFilesAndAbsInstallDirs = [];
var downloadDir = getDownloadDir();
var sdkInstallDir = getSDKInstallDir();
var lists = getSDKConfigList();
for (var i = 0; i < lists.length; i++) {
var list = lists[i];
var url = list.url;
var fileName = path.basename(url);
var localFile = path.join(downloadDir, fileName);
var installDir = path.join(sdkInstallDir, list.installDir);
var result = {
"localFile": localFile,
"installDir": installDir,
"varName": list["varName"]
};
allLocalFilesAndAbsInstallDirs.push(result);
}
}
return allLocalFilesAndAbsInstallDirs;
}
function saveSDKInfoToConfigFile() {
var config = {};
var list = getAllLocalFilesAndAbsInstallDirs();
for (var i = 0; i < list.length; i++) {
var obj = list[i];
if (obj.varName) {
var installDir = obj.installDir;
if (needAddBinToPath(obj.varName)) {
installDir = path.join(installDir, "bin");
}
config[obj.varName] = installDir;
}
}
var filePath = getAndroidSDKConfigFilePath();
writeJSONObjectToFile(filePath, config);
}
class Downloader {
download(url, dest, cb) {
var file = fs.createWriteStream(dest);
var request = http.get(url, function (response) {
response.pipe(file);
file.on('finish', function () {
file.close();
}).on('close', function () {
if (cb) {
cb();
}
});
}).on('error', function (err) { // Handle errors
console.error(err.message);
});
return file;
};
}
var downloadDir = null;
function setDownloadDir(dir) {
downloadDir = dir;
if (!fs.existsSync(downloadDir)) {
fs.mkdirSync(downloadDir);
}
}
function getDownloadDir() {
if (!downloadDir) {
var root = getRootPath();
var dir = path.join(root, "download")
setDownloadDir(dir);
}
return downloadDir;
}
var sdkInstallDir = null;
function setSDKInstallDir(dir) {
sdkInstallDir = dir;
if (!fs.existsSync(sdkInstallDir)) {
fs.mkdirSync(sdkInstallDir);
}
}
function getSDKInstallDir() {
if (!sdkInstallDir) {
var root = getRootPath();
var dir = path.join(root, "SDK");
setSDKInstallDir(dir);
}
return sdkInstallDir;
}
class MultiTaskManager extends events.EventEmitter {
oneTaskFinishedEventName = "oneTaskFinished";
allTasksFinishedEventName = "allTasksFinished";
taskList = [];
progressConfigFileName = "MultiTaskProgressConfig.json";
unfinishedTask(taskIndex) {
}
// private. should NOT be overrided by subclass.
finishedTaskCount = 0;
isTaskInProgressConfigList(taskIndex) {
var result = false;
var configList = this.getProgressConfigList();
if (configList) {
for (var i = 0; i < configList.length; i++) {
if (taskIndex == configList[i]) {
result = true;
}
}
}
return result;
}
isTaskFinished(taskIndex) {
var finished = this.isTaskInProgressConfigList(taskIndex);
return finished;
}
getProgressConfigFilePath() {
var fileName = this.progressConfigFileName;
var filePath = getConfigFilePathByFileName(fileName);
return filePath;
};
getProgressConfigList() {
var progressConfigFilePath = this.getProgressConfigFilePath();
var configList = getJSONObjectFromFile(progressConfigFilePath);
return configList;
};
writeProgressConfigToFile(taskIndex) {
var configList = this.getProgressConfigList();
if (!configList) {
configList = [];
}
var isTaskInConfigList = this.isTaskInProgressConfigList(taskIndex);
if (!isTaskInConfigList) {
configList.push(taskIndex);
var configFilePath = this.getProgressConfigFilePath();
if (configFilePath) {
writeJSONObjectToFile(configFilePath, configList);
}
}
}
emitTaskFinishedEvent(taskIndex) {
this.emit(this.oneTaskFinishedEventName, taskIndex);
}
tryToEmitAllTasksFinishedEvent() {
if (this.finishedTaskCount == this.taskList.length) {
this.emit(this.allTasksFinishedEventName);
}
}
// protected. used by subclasses to notify one task finished.
taskFinishCallback(taskIndex) {
this.finishedTaskCount++;
this.writeProgressConfigToFile(taskIndex);
this.emitTaskFinishedEvent(taskIndex);
this.tryToEmitAllTasksFinishedEvent();
}
// public. used to start to process tasks.
start() {
if (this.taskList) {
for (var i = 0; i < this.taskList.length; i++) {
var taskFinished = this.isTaskFinished(i);
if (taskFinished) {
this.taskFinishCallback(i);
} else {
this.unfinishedTask(i);
}
}
}
}
}
class DownloadManager extends MultiTaskManager {
downloadDir: string;
downloader: Downloader;
static thiz;
constructor(list, dlDir) {
super();
DownloadManager.thiz = this;
// for internal use only.
this.downloadDir = dlDir || getDownloadDir();
this.downloader = new Downloader();
// override parent class members.
this.oneTaskFinishedEventName = "oneDownloadTaskFinished";
this.allTasksFinishedEventName = "allDownloadTasksFinished";
this.progressConfigFileName = "DownloadProgressConfig.json";
this.taskList = list;
}
unfinishedTask(taskIndex) {
var task = this.taskList[taskIndex];
var url = task.url;
var downloadDir = this.downloadDir;
var fileName = path.basename(url);
var fileSavePath = path.join(downloadDir, fileName);
var dl = this.downloader.download(url, fileSavePath, function () {
DownloadManager.thiz.taskFinishCallback(taskIndex);
});
}
}
class UnzipManager extends MultiTaskManager {
// for internal use only.
static thiz
constructor(list) {
super();
UnzipManager.thiz = this;
// override parent class members.
this.oneTaskFinishedEventName = "oneUnzipTaskFinished";
this.allTasksFinishedEventName = "allUnzipTasksFinished";
this.progressConfigFileName = "UnzipProgressConfig.json";
this.taskList = list;
}
unfinishedTask(taskIndex) {
var task = this.taskList[taskIndex];
var localFile = task.localFile;
var installDir = task.installDir;
UnzipCommand.unzip(localFile, installDir, function (result) {
if (result == 0) {
UnzipManager.thiz.taskFinishCallback(taskIndex);
} else {
console.error("unzip failed!");
}
});
}
}
function getUnzipManager() {
var list = getAllLocalFilesAndAbsInstallDirs();
var uzm = new UnzipManager(list);
return uzm;
}
function getBaseName(dir) {
return path.basename(dir);
}
function startToUnzipAndInstall() {
var uzm = getUnzipManager();
uzm.on(uzm.oneTaskFinishedEventName, function (taskIndex) {
var length = this.taskList.length;
var task = this.taskList[taskIndex];
var fileName = getBaseName(task.localFile);
var progressMsg = utils.tr(2209, this.finishedTaskCount + "/" + length + " " + fileName);
print(progressMsg);
});
uzm.on(uzm.allTasksFinishedEventName, function () {
var allUnzippedMsg = utils.tr(2210);
print(allUnzippedMsg);
saveSDKInfoToConfigFile();
var sdkInstalledMsg = utils.tr(2211);
print(sdkInstalledMsg);
printAndroidSDKConfig();
});
var length = uzm.taskList.length;
var unzipMsg = utils.tr(2207, length);
print(unzipMsg);
var startMsg = utils.tr(2208);
print(startMsg);
uzm.start();
}
function getDownloadManager() {
var list = getSDKConfigList();
var downloadDir = getDownloadDir();
var dlm = new DownloadManager(list, downloadDir);
return dlm;
}
function startToDownload() {
var dlm = getDownloadManager();
dlm.on(dlm.oneTaskFinishedEventName, function (taskIndex) {
var task = this.taskList[taskIndex];
var url = task.url;
var fileName = path.basename(url);
var fileSize = task.fileSize;
var length = this.taskList.length;
var progressMsg = utils.tr(2204, this.finishedTaskCount + "/" + length + " " + fileName);
print(progressMsg);
var totalMBSize = fileSize * 1.0 / (1024 * 1024);
var fileSizeMsg = utils.tr(2205, totalMBSize.toFixed(2));
print(fileSizeMsg);
});
dlm.on(dlm.allTasksFinishedEventName, function () {
var allDownloadedMsg = utils.tr(2206);
print(allDownloadedMsg);
startToUnzipAndInstall();
});
var length = dlm.taskList.length;
var downloadMsg = utils.tr(2201, length);
print(downloadMsg);
var totalByteSize = calcTotalFileSize(dlm.taskList);
var totalMBSize = totalByteSize * 1.0 / (1024 * 1024);
var totalSizeMsg = utils.tr(2202, totalMBSize.toFixed(2));
print(totalSizeMsg);
var startMsg = utils.tr(2203);
print(startMsg);
dlm.start();
}
class InstallSDK implements egret.Command {
execute() {
startToDownload();
return DontExitCode;
}
static printAndroidSDKConfig(): void {
printAndroidSDKConfig();
}
}
export = InstallSDK;
(function () {
var isEgret = isInEgretMode();
if (!isEgret) {
InstallSDK.prototype.execute();
}
})(); | the_stack |
import fc from '../../src/fast-check';
import {
IncreaseCommand,
DecreaseCommand,
EvenCommand,
OddCommand,
CheckLessThanCommand,
} from './model/CounterCommands';
const testFunc = (value: unknown) => {
const repr = fc.stringify(value).replace(/^(|Big)(Int|Uint|Float)(8|16|32|64)(|Clamped)Array\.from\((.*)\)$/, '$5');
for (let idx = 1; idx < repr.length; ++idx) {
if (repr[idx - 1] === repr[idx] && repr[idx] !== '"' && repr[idx] !== '}') {
return false;
}
}
return true;
};
// Bumping from one patch of fast-check to another is not supposed
// to change the values that will be generated by the framework.
//
// Except in case of a real bug causing the arbitrary to be totally unusable.
//
// This suite checks this invariant stays true.
// Moreover, the framework should build consistent values throughout all the versions of node.
const settings = { seed: 42, verbose: 2 };
describe(`NoRegression`, () => {
it('.filter', () => {
expect(() =>
fc.assert(
fc.property(
fc.nat().filter((n) => n % 3 !== 0),
(v) => testFunc(v)
),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('.map', () => {
expect(() =>
fc.assert(
fc.property(
fc.nat().map((n) => String(n)),
(v) => testFunc(v)
),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('.chain', () => {
expect(() =>
fc.assert(
fc.property(
fc.nat(20).chain((n) => fc.clone(fc.nat(n), n)),
(v) => testFunc(v)
),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('float', () => {
expect(() =>
fc.assert(
fc.property(fc.float(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('floatNext', () => {
expect(() =>
fc.assert(
fc.property(fc.float({ next: true }), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('double', () => {
expect(() =>
fc.assert(
fc.property(fc.double(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('doubleNext', () => {
expect(() =>
fc.assert(
fc.property(fc.double({ next: true }), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('integer', () => {
expect(() =>
fc.assert(
fc.property(fc.integer(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('nat', () => {
expect(() =>
fc.assert(
fc.property(fc.nat(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('maxSafeInteger', () => {
expect(() =>
fc.assert(
fc.property(fc.maxSafeInteger(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('maxSafeNat', () => {
expect(() =>
fc.assert(
fc.property(fc.maxSafeNat(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('string', () => {
expect(() =>
fc.assert(
fc.property(fc.string(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('asciiString', () => {
expect(() =>
fc.assert(
fc.property(fc.asciiString(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
// // Jest Snapshot seems not to support incomplete surrogate pair correctly
// it('string16bits', () => {
// expect(() => fc.assert(fc.property(fc.string16bits(), v => testFunc(v + v)), settings)).toThrowErrorMatchingSnapshot();
// });
it('stringOf', () => {
expect(() =>
fc.assert(
fc.property(fc.stringOf(fc.constantFrom('a', 'b')), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('unicodeString', () => {
expect(() =>
fc.assert(
fc.property(fc.unicodeString(), (v) => testFunc(v + v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('fullUnicodeString', () => {
expect(() =>
fc.assert(
fc.property(fc.fullUnicodeString(), (v) => testFunc(v + v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('hexaString', () => {
expect(() =>
fc.assert(
fc.property(fc.hexaString(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('base64String', () => {
expect(() =>
fc.assert(
fc.property(fc.base64String(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('lorem', () => {
expect(() =>
fc.assert(
fc.property(fc.lorem(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('mapToConstant', () => {
expect(() =>
fc.assert(
fc.property(
fc.mapToConstant({ num: 26, build: (v) => String.fromCharCode(v + 0x61) }),
fc.mapToConstant({ num: 26, build: (v) => String.fromCharCode(v + 0x61) }),
(a, b) => testFunc(a + b)
),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('option', () => {
expect(() =>
fc.assert(
fc.property(fc.option(fc.nat()), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('oneof', () => {
expect(() =>
fc.assert(
fc.property(fc.oneof<any>(fc.nat(), fc.char()), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('frequency', () => {
expect(() =>
fc.assert(
fc.property(
fc.frequency<any>({ weight: 1, arbitrary: fc.nat() }, { weight: 5, arbitrary: fc.char() }),
testFunc
),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('clone', () => {
expect(() =>
fc.assert(
fc.property(fc.clone(fc.nat(), 2), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('shuffledSubarray', () => {
expect(() =>
fc.assert(
fc.property(fc.shuffledSubarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), (v) =>
testFunc(v.join(''))
),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('subarray', () => {
expect(() =>
fc.assert(
fc.property(fc.subarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), (v) =>
testFunc(v.join(''))
),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('array', () => {
expect(() =>
fc.assert(
fc.property(fc.array(fc.nat()), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('sparseArray', () => {
expect(() =>
fc.assert(
fc.property(
fc.sparseArray(fc.nat()),
(v) =>
// Sum of first element of each group should be less or equal to 10
// If a group starts at index 0, the whole group is ignored
Object.entries(v).reduce((acc, [index, cur]) => {
if (index === '0' || v[Number(index) - 1] !== undefined) return acc;
else return acc + cur;
}, 0) <= 10
),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('sparseArray({noTrailingHole:true})', () => {
expect(() =>
fc.assert(
fc.property(
fc.sparseArray(fc.nat(), { noTrailingHole: true }),
(v) =>
// Sum of first element of each group should be less or equal to 10
// If a group starts at index 0, the whole group is ignored
Object.entries(v).reduce((acc, [index, cur]) => {
if (index === '0' || v[Number(index) - 1] !== undefined) return acc;
else return acc + cur;
}, 0) <= 10
),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('infiniteStream', () => {
expect(() =>
fc.assert(
fc.property(fc.infiniteStream(fc.nat()), (s) => testFunc([...s.take(10)])),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('set', () => {
expect(() =>
fc.assert(
fc.property(fc.set(fc.nat()), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('tuple', () => {
expect(() =>
fc.assert(
fc.property(fc.tuple(fc.nat(), fc.nat()), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('int8Array', () => {
expect(() =>
fc.assert(
fc.property(fc.int8Array(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('uint8Array', () => {
expect(() =>
fc.assert(
fc.property(fc.uint8Array(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('uint8ClampedArray', () => {
expect(() =>
fc.assert(
fc.property(fc.uint8ClampedArray(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('int16Array', () => {
expect(() =>
fc.assert(
fc.property(fc.int16Array(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('uint16Array', () => {
expect(() =>
fc.assert(
fc.property(fc.uint16Array(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('int32Array', () => {
expect(() =>
fc.assert(
fc.property(fc.int32Array(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('uint32Array', () => {
expect(() =>
fc.assert(
fc.property(fc.uint32Array(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('float32Array', () => {
expect(() =>
fc.assert(
fc.property(fc.float32Array(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('float64Array', () => {
expect(() =>
fc.assert(
fc.property(fc.float64Array(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('record', () => {
expect(() =>
fc.assert(
fc.property(fc.record({ k1: fc.nat(), k2: fc.nat() }, { withDeletedKeys: true }), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('dictionary', () => {
expect(() =>
fc.assert(
fc.property(fc.dictionary(fc.string(), fc.nat()), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('anything', () => {
expect(() =>
fc.assert(
fc.property(fc.anything(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('object', () => {
expect(() =>
fc.assert(
fc.property(fc.object(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('json', () => {
expect(() =>
fc.assert(
fc.property(fc.json(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('jsonObject', () => {
expect(() =>
fc.assert(
fc.property(fc.jsonObject(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('unicodeJson', () => {
expect(() =>
fc.assert(
fc.property(fc.unicodeJson(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('unicodeJsonObject', () => {
expect(() =>
fc.assert(
fc.property(fc.unicodeJsonObject(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('compareFunc', () => {
expect(() =>
fc.assert(
fc.property(fc.compareFunc(), (f) => testFunc(f(1, 2))),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('func', () => {
expect(() =>
fc.assert(
fc.property(fc.func(fc.nat()), (f) => testFunc(f())),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('ipV4', () => {
expect(() =>
fc.assert(
fc.property(fc.ipV4(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('ipV4Extended', () => {
expect(() =>
fc.assert(
fc.property(fc.ipV4Extended(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('ipV6', () => {
expect(() =>
fc.assert(
fc.property(fc.ipV6(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('domain', () => {
expect(() =>
fc.assert(
fc.property(fc.domain(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('webAuthority', () => {
expect(() =>
fc.assert(
fc.property(fc.webAuthority(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('webSegment', () => {
expect(() =>
fc.assert(
fc.property(fc.webSegment(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('webFragments', () => {
expect(() =>
fc.assert(
fc.property(fc.webFragments(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('webQueryParameters', () => {
expect(() =>
fc.assert(
fc.property(fc.webQueryParameters(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('webUrl', () => {
expect(() =>
fc.assert(
fc.property(fc.webUrl(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('emailAddress', () => {
expect(() =>
fc.assert(
fc.property(fc.emailAddress(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('date', () => {
expect(() =>
fc.assert(
fc.property(fc.date(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('uuid', () => {
expect(() =>
fc.assert(
fc.property(fc.uuid(), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('uuidV', () => {
expect(() =>
fc.assert(
fc.property(fc.uuidV(4), (v) => testFunc(v)),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('letrec', () => {
expect(() =>
fc.assert(
fc.property(
fc.letrec((tie) => ({
// Trick to be able to shrink from node to leaf
tree: fc.nat(1).chain((id) => (id === 0 ? tie('leaf') : tie('node'))),
node: fc.record({ left: tie('tree'), right: tie('tree') }),
leaf: fc.nat(21),
})).tree,
(v) => testFunc(v)
),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('letrec (oneof:maxDepth)', () => {
expect(() =>
fc.assert(
fc.property(
fc.letrec((tie) => ({
tree: fc.oneof({ withCrossShrink: true, maxDepth: 2 }, tie('leaf'), tie('node')),
node: fc.record({ a: tie('tree'), b: tie('tree'), c: tie('tree') }),
leaf: fc.nat(21),
})).tree,
(v) => testFunc(v)
),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('letrec (oneof:depthFactor)', () => {
expect(() =>
fc.assert(
fc.property(
fc.letrec((tie) => ({
tree: fc.oneof({ withCrossShrink: true, depthFactor: 0.5 }, tie('leaf'), tie('node')),
node: fc.record({ a: tie('tree'), b: tie('tree'), c: tie('tree') }),
leaf: fc.nat(21),
})).tree,
(v) => testFunc(v)
),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('commands', () => {
expect(() =>
fc.assert(
fc.property(
fc.commands([
fc.nat().map((n) => new IncreaseCommand(n)),
fc.nat().map((n) => new DecreaseCommand(n)),
fc.constant(new EvenCommand()),
fc.constant(new OddCommand()),
fc.nat().map((n) => new CheckLessThanCommand(n + 1)),
]),
(cmds) => {
const setup = () => ({
model: { count: 0 },
real: {},
});
try {
fc.modelRun(setup, cmds);
return true;
} catch (err) {
return false;
}
}
),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('scheduler', async () => {
await expect(
fc.assert(
fc.asyncProperty(fc.scheduler(), async (s) => {
const received = [] as string[];
for (const v of ['a', 'b', 'c']) {
s.schedule(Promise.resolve(v)).then((out) => {
received.push(out);
s.schedule(Promise.resolve(out.toUpperCase())).then((out2) => {
received.push(out2);
});
});
}
await s.waitAll();
return !received.join('').includes('aBc');
}),
settings
)
).rejects.toThrowErrorMatchingSnapshot();
});
it('context', () => {
expect(() =>
fc.assert(
fc.property(fc.context(), fc.nat(), (ctx, v) => {
ctx.log(`Value was ${v}`);
return testFunc(v);
}),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('Promise<number>', () => {
expect(() =>
fc.assert(
fc.property(
fc.integer().map((v) => [v, Promise.resolve(v)] as const),
([v, _p]) => testFunc(v)
),
settings
)
).toThrowErrorMatchingSnapshot();
});
it('user defined examples', () => {
expect(() =>
fc.assert(
fc.property(fc.string(), (v) => testFunc(v)),
{ ...settings, examples: [['hi'], ['hello'], ['hey']] }
)
).toThrowErrorMatchingSnapshot();
});
it('user defined examples (including not shrinkable values)', () => {
expect(() =>
fc.assert(
fc.property(
// Shrinkable: built-in
fc.nat(),
// Cannot shrinking: missing unmapper
fc.convertFromNext(fc.convertToNext(fc.nat()).map((v) => String(v))),
// Shrinkable: unmapper provided
fc.convertFromNext(
fc.convertToNext(fc.nat()).map(
(v) => String(v),
(v) => Number(v)
)
),
// Shrinkable: filter can shrink given the value to shrink matches the predicate
fc.nat().filter((v) => v % 2 === 0),
(a, b, c, d) => testFunc([a, b, c, d])
),
{
...settings,
examples: [
[1, '2', '3', 4],
[5, '6', '7', 8],
[9, '10', '11', 12],
[13, '14', '15', 16],
[17, '18', '19', 20],
],
}
)
).toThrowErrorMatchingSnapshot();
});
});
describe(`NoRegression (async)`, () => {
const asyncNumber = fc.integer().map((v) => Promise.resolve(v));
it('number', async () => {
await expect(
async () =>
await fc.assert(
fc.asyncProperty(fc.integer(), async (v) => testFunc(v)),
settings
)
).rejects.toThrowErrorMatchingSnapshot();
});
it('.map (to Promise)', async () => {
await expect(
async () =>
await fc.assert(
fc.asyncProperty(asyncNumber, async (v) => testFunc(await v)),
settings
)
).rejects.toThrowErrorMatchingSnapshot();
});
it('func (to Promise)', async () => {
await expect(
async () =>
await fc.assert(
fc.asyncProperty(fc.func(asyncNumber), async (f) => testFunc(await f())),
settings
)
).rejects.toThrowErrorMatchingSnapshot();
});
it('infiniteStream (to Promise)', async () => {
await expect(
async () =>
await fc.assert(
fc.asyncProperty(fc.infiniteStream(asyncNumber), async (s) => testFunc(await Promise.all([...s.take(10)]))),
settings
)
).rejects.toThrowErrorMatchingSnapshot();
});
}); | the_stack |
import { toQueryString } from "../../utils";
import { SdkClient } from "../common/sdk-client";
import { SemanticDataInterconnectModels } from "./sdi-models";
import { sdiTemplate } from "./sdi-template";
/**
* The Semantic Data Interconnect (SDI) is a collection of APIs that allows the user
* to unlock the potential of disparate big data by connecting external data.
* The SDI can infer the schemas of data based on schema-on-read, allow creating a semantic model
* and perform big data semantic queries.
* It seamlessly connects to MindSphere's Integrated Data Lake (IDL), but it can work independently as well.
*
* There are two mechanisms that can be used to upload files so that SDI can generate schemas and make data ready for query.
* The SDI operations are divided into the following groups:
*
* * Data Registration for SDI
*
* This set of APIs is used to organize the incoming data. When configuring a Data Registry,
* you have the option to update your data based on a replace or append strategy.
* If you consider a use case where schema may change and incoming data files are completely different
* every time then replace is a good strategy.
* The replace strategy will replace the existing schema and data during each data ingest operation
* whereas the append strategy will update the existing schema and data during each data ingest operation.
*
* * Custom Data Type for SDI
*
* The SDI by default identifies basic data types for each property, such as String, Integer, Float, Date, etc.
* The user can use this set of APIs to create their own custom data type.
* The SDI also provides an API under this category to suggest data type based on user-provided sample test values.
*
* * Data Lake for SDI
*
* The SDI can process files uploaded provides endpoints
* to manage customer's data lake registration based on tenant id, cloud provider and data lake type.
* The set of REST endpoint allows to create, update and retrieve base path for their data lake.
* The IDL customer needs to create an SDI folder that is under the root folder.
* Any file uploaded in this folder is automatically picked up by SDI to process via IDL notification.
*
* * Data Ingest for SDI
*
* This set of APIs allows user to upload files, start an ingest job for uploaded files, find job status for
* ingested jobs or retrieve all job statuses.
*
* * Schema Registry for SDI
*
* The SDI provides a way to find the generated schema in this category.
* * Users can find an SDI generated schema for uploaded files based on source name, data tag or schema name.
*
* * Data Query for SDI
*
* allows querying based on the extracted schemas. Important supported APIs are:
* Query interface for querying semantically correlated and transformed data
* Stores and executes data queries.
*
* Uses a semantic model to translate model-based query to physical queries.
*
* * Semantic Model for SDI
*
* allows user to create semantic model ontologies based on the extracted one or more schemas.
*
* The important functionalities achieved with APIs are:
* Contextual correlation of data from different systems.
* Infers & Recommends mappings between different schemas.
* Import and store Semantic model.
*
* @export
* @class SemanticDataInterconnectClient
* @extends {SdkClient}
*/
export class SemanticDataInterconnectClient extends SdkClient {
private _baseUrl: string = "/api/sdi/v4";
/**
* * Data Lake
*
* Retrieves DataLake for a given DataLake Id
*
* @param {string} id
* @returns {Promise<SemanticDataInterconnectModels.DataLakeResponse>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async GetDataLake(id: string): Promise<SemanticDataInterconnectModels.DataLakeResponse> {
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/dataLakes/${id}`,
});
return result as SemanticDataInterconnectModels.DataLakeResponse;
}
/**
* * Data Lake
*
* Updates base path for a given data lake type
*
* @param {string} id
* @param {SemanticDataInterconnectModels.UpdateDataLakeRequest} updateDataLakeRequest
* @returns {Promise<SemanticDataInterconnectModels.DataLakeResponse>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async PatchDataLake(
id: string,
updateDataLakeRequest: SemanticDataInterconnectModels.UpdateDataLakeRequest
): Promise<SemanticDataInterconnectModels.DataLakeResponse> {
const result = await this.HttpAction({
verb: "PATCH",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
body: updateDataLakeRequest,
baseUrl: `${this._baseUrl}/dataLakes/${id}`,
});
return result as SemanticDataInterconnectModels.DataLakeResponse;
}
/**
* * Data Lake
*
* Retrieves base path for a given data lake type, this will return an empty array when no datalake is found.
*
* @returns {Promise<SemanticDataInterconnectModels.DataLakeList>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async GetDataLakes(): Promise<SemanticDataInterconnectModels.DataLakeList> {
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/dataLakes`,
});
return result as SemanticDataInterconnectModels.DataLakeList;
}
/**
* * Data Lake
*
* Creates a data lake record with given data lake type, name and base path.
* To use IDL as preferred data lake, use type as MindSphere and name as IDL.
* The possible values for type is MindSphere or Custom.
*
* @param {SemanticDataInterconnectModels.CreateDataLakeRequest} createDataLakeRequest
* @returns {Promise<SemanticDataInterconnectModels.CreateDataLakeResponse>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async PostDataLake(
createDataLakeRequest: SemanticDataInterconnectModels.CreateDataLakeRequest
): Promise<SemanticDataInterconnectModels.CreateDataLakeResponse> {
const result = await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
body: createDataLakeRequest,
baseUrl: `${this._baseUrl}/dataLakes`,
});
return result as SemanticDataInterconnectModels.CreateDataLakeRequest;
}
/**
* * Data Lakes
*
* !important: this doesn't work because of missing support in mindsphere in April 2021
* !fix: implemented the method for the case that there is a support in the future
*
* @param {string} id
*
* @memberOf SemanticDataInterconnectClient
*/
public async DeleteDataLake(id: string) {
try {
await this.HttpAction({
verb: "DELETE",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/dataLakes/${id}`,
});
} catch (error) {
console.error(
"At the time of creation of this client (April 2021), MindSphere didn't have any support for DELETE operation on data lakes."
);
console.error("This was reported to mindsphere development team and should eventually start working.");
throw error;
}
}
/**
* * Data Registries
*
* Retrieves Data Registry for a given registry id
*
* @param {string} id
* @returns {Promise<SemanticDataInterconnectModels.DataRegistry>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async GetDataRegistry(id: string): Promise<SemanticDataInterconnectModels.DataRegistry> {
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/dataRegistries/${id}`,
});
return result as SemanticDataInterconnectModels.DataRegistry;
}
/**
*
* * Data Registries
*
* Update Data Registry entries for a given Data Registry Id.
*
* @param {string} id
* @param {SemanticDataInterconnectModels.UpdateDataRegistryRequest} updateDataRegistryRequest
* @returns {Promise<SemanticDataInterconnectModels.DataRegistry>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async PatchDataRegistry(
id: string,
updateDataRegistryRequest: SemanticDataInterconnectModels.UpdateDataRegistryRequest
): Promise<SemanticDataInterconnectModels.DataRegistry> {
const result = await this.HttpAction({
verb: "PATCH",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/dataRegistries/${id}`,
body: updateDataRegistryRequest,
});
return result as SemanticDataInterconnectModels.DataRegistry;
}
/**
*
* * Data Registries
*
* Retrieves all Data Registry entries, Data Registry based on sourceName, dataTag or combination of sourceName and dataTag.
*
* @param {{
* dataTag?: string;
* sourceName?: string;
* pageToken?: string;
* }} [params]
* @param params.datatag dataTag
* @param params.sourceName sourceName
* @param params.pageToken Selects next page. Value must be taken rom response body property 'page.nextToken’. If omitted, first page is returned.
*
* @returns {Promise<SemanticDataInterconnectModels.ListOfRegistryResponse>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async GetDataRegistries(params?: {
dataTag?: string;
sourceName?: string;
pageToken?: string;
}): Promise<SemanticDataInterconnectModels.ListOfRegistryResponse> {
const parameters = params || {};
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/dataRegistries?${toQueryString(parameters)}`,
});
return result as SemanticDataInterconnectModels.ListOfRegistryResponse;
}
/**
*
* * Data Registries
*
* Initiate creation of Data Registry for the current tenant.
* The Data Registry information is used during data ingest for the tenant.
* Only one Data Registry can be created for a request.
* The dataTag, sourceName and fileUploadStrategy is required to create Date Registry
* otherwise creation is rejected.
* DataUpload will allow only files to be uploaded matching this Data Registry.
* This returns unique registryId for each request that can be used to retrieve the created registry.
* The tenant cannot have more than 500 data registries in the system.
* The schemaFrozen flag must be set to false during creation of a registry.
* It can be set to true after creation of the initial schema for the registry.
*
* @param {SemanticDataInterconnectModels.CreateDataRegistryRequest} createDataRegistryRequest
* @returns {Promise<SemanticDataInterconnectModels.DataRegistry>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async PostDataRegistry(
createDataRegistryRequest: SemanticDataInterconnectModels.CreateDataRegistryRequest
): Promise<SemanticDataInterconnectModels.DataRegistry> {
const result = await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/dataRegistries`,
body: createDataRegistryRequest,
});
return result as SemanticDataInterconnectModels.DataRegistry;
}
/**
* * Data Registries
*
* !important: this doesn't work because of missing support in mindsphere in April 2021
* !fix: implemented the method for the case that there is a support in the future
*
* @param {string} id
*
* @memberOf SemanticDataInterconnectClient
*/
public async DeleteDataRegistry(id: string) {
try {
await this.HttpAction({
verb: "DELETE",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/dataRegistries/${id}`,
});
} catch (error) {
console.error(
"At the time of creation of this client (April 2021), MindSphere didn't have any support for DELETE operation on data registries."
);
console.error("This was reported to mindsphere development team and should eventually start working.");
throw error;
}
}
/**
* * IoT Data Registries
*
* Retrieves an IoT Data Registry with MindSphere AssetId and AspectName
*
* @param {{
* filter?: string;
* pageToken?: string;
* }} [params]
* @param params.filter filter
* @param params.pageToken Selects next page. Value must be taken rom response body property 'page.nextToken’. If omitted, first page is returned.
*
* @returns {Promise<SemanticDataInterconnectModels.ListOfIoTRegistryResponse>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async GetIotDataRegistries(params?: {
filter?: string;
pageToken?: string;
}): Promise<SemanticDataInterconnectModels.ListOfIoTRegistryResponse> {
const parameters = params || {};
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/iotDataRegistries?${toQueryString(parameters)}`,
});
return result as SemanticDataInterconnectModels.ListOfIoTRegistryResponse;
}
/**
* * IoT Data Registry
*
* Create new IoT Data Registry with MindSphereAssetId and AspectName
*
* @param {SemanticDataInterconnectModels.IotDataRegistry} iotDataRegistry
* @returns {Promise<SemanticDataInterconnectModels.IotDataRegistryResponse>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async PostIotDataRegistry(
iotDataRegistry: SemanticDataInterconnectModels.IotDataRegistry
): Promise<SemanticDataInterconnectModels.IotDataRegistryResponse> {
const result = await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/iotDataRegistries`,
body: iotDataRegistry,
});
return result as SemanticDataInterconnectModels.IotDataRegistryResponse;
}
/**
* * Iot Data Registry
*
* Gets the details about the iot data registry
*
* !important!: this is convenience method in the client as the SDI API didn't have a specific operation in April 2021
* *
* @param {string} registryId
* @returns {Promise<SemanticDataInterconnectModels.IotDataRegistry>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async GetIotDataRegistry(registryId: string): Promise<SemanticDataInterconnectModels.IotDataRegistry> {
let nextToken = undefined;
let registry = undefined;
do {
const result = await this.GetIotDataRegistries();
result.iotDataRegistries?.forEach((x) => {
if (x.registryId === registryId) {
registry = x;
}
});
nextToken = result.page?.nextToken;
} while (nextToken);
if (!registry) {
throw new Error(`couldn't find iot data registry with id ${registryId}`);
}
return registry;
}
/**
* * Iot Registries
*
* !important: this doesn't work because of missing support in mindsphere in April 2021
* !fix: implemented the method for the case that there is a support in the future
*
* @param {string} id
*
* @memberOf SemanticDataInterconnectClient
*/
public async DeleteIotRegistry(id: string) {
try {
await this.HttpAction({
verb: "DELETE",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/iotDataRegistries/${id}`,
});
} catch (error) {
console.error(
"At the time of creation of this client (April 2021), MindSphere didn't have any support for DELETE operation on data registries."
);
console.error("This was reported to mindsphere development team and should eventually start working.");
throw error;
}
}
/**
* * Data Types
*
* Update custom datatypes. The patterns can be added only to existing datatype.
*
* @param {string} name data type name
* @param {SemanticDataInterconnectModels.DataTypePattern} dataTypePattern
* @returns {Promise<SemanticDataInterconnectModels.DataTypeDefinition>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async AddPatternToDataType(
name: string,
dataTypePattern: SemanticDataInterconnectModels.DataTypePattern
): Promise<SemanticDataInterconnectModels.DataTypeDefinition> {
const result = await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/dataTypes/${name}/addPatterns`,
body: dataTypePattern,
});
return result as SemanticDataInterconnectModels.DataTypeDefinition;
}
/**
*
* * Data Types
*
* Retrieves Data Type for Given Name
*
* @param {string} name
* @returns {Promise<SemanticDataInterconnectModels.DataTypeDefinition>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async GetDataType(name: string): Promise<SemanticDataInterconnectModels.DataTypeDefinition> {
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/dataTypes/${name}`,
});
return result as SemanticDataInterconnectModels.DataTypeDefinition;
}
/**
* * Data Types
*
* Deletes custom datatype for a given datatype name if it is not being used by any schema
*
* @param {string} name
*
* @memberOf SemanticDataInterconnectClient
*/
public async DeleteDataType(name: string) {
await this.HttpAction({
verb: "DELETE",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/dataTypes/${name}`,
noResponse: true,
});
}
/**
* * Data Types
*
* Retrieves custom datatypes for the current tenant containing data type name and one or more registered patterns.
*
* @param {{
* pageToken?: string;
* }} [params]
* @returns {Promise<SemanticDataInterconnectModels.ListOfDataTypeDefinition>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async GetDataTypes(params?: {
pageToken?: string;
}): Promise<SemanticDataInterconnectModels.ListOfDataTypeDefinition> {
const parameters = params || {};
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/dataTypes?${toQueryString(parameters)}`,
});
return result as SemanticDataInterconnectModels.ListOfDataTypeDefinition;
}
/**
* * Data Types
*
* Custom Data Type Registration
*
* Initiates a registration for list of custom datatypes for given datatype name and regular expression patterns.
* There can be one or more pattern for a given custom data type.
* The custom datatype is being used by DataUpload process during schema generation.
* The custom datatype registration is rejected for the current tenant if invalid regular expression pattern
* is provided.
*
* The custom datatype applies to all the files ingested for the current tenant.
* The tenant can have maximum 200 datatypes per tenant and each datatype cannot exceed 10
* regular expression pattern per datatypename. This returns unique *name that can be used to
* retrieve the custom data type.
*
* @param {SemanticDataInterconnectModels.DataTypeDefinition} dataTypeDefinition
* @returns {Promise<SemanticDataInterconnectModels.DataTypeDefinition>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async PostDataType(
dataTypeDefinition: SemanticDataInterconnectModels.DataTypeDefinition
): Promise<SemanticDataInterconnectModels.DataTypeDefinition> {
const result = await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/dataTypes`,
body: dataTypeDefinition,
});
return result as SemanticDataInterconnectModels.DataTypeDefinition;
}
/**
*
* * Data Types
*
* !fix: important! in may 2021 the SDI was return wrong results here (array instead of object). this was fixed in the client.
*
* Generates the regular expression patterns for a given set of sample values.
* In this case sampleValues generates a number of regex patterns and tries to match with
* patterns provided in testValues.
*
* The response contains any of testValues that matches sampleValues as probable pattern match.
*
*
* @param {SemanticDataInterconnectModels.SuggestPatternsRequest} request
* @returns {Promise<SemanticDataInterconnectModels.ListOfPatterns>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async SuggestPatterns(
request: SemanticDataInterconnectModels.SuggestPatternsRequest
): Promise<SemanticDataInterconnectModels.ListOfPatterns> {
let result = await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/suggestPatterns`,
body: request,
});
const transformed: any = { suggestPatterns: [] };
// !fix: manual fix for wrong result, in April 2021 sdi was returning wrong results here
if (Array.isArray(result)) {
(result as Array<any>).forEach((element) => {
const result: Array<string> = [];
(element.matches || []).forEach((t: any) => {
result.push(t.toString());
});
transformed.suggestPatterns.push({
schema: element.schema,
matches: result,
schemaValid: element.schemaValid,
});
});
result = transformed;
}
return result as SemanticDataInterconnectModels.ListOfPatterns;
}
/**
* * Data Ingest
*
* Initiate the file upload process for provided file under the current tenant.
*
* @param {string} fileName Select the file to Upload for SDI process
* @param {Buffer} buffer
* @param {string} [mimetype]
* @returns
*
* @memberOf SemanticDataInterconnectClient
*/
public async DataUpload(fileName: string, buffer: Buffer, mimetype?: string) {
const body = sdiTemplate(fileName, buffer, mimetype);
const result = await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/dataUpload`,
body: body,
multiPartFormData: true,
});
return result as SemanticDataInterconnectModels.SdiFileUploadResponse;
}
/**
* * Data Ingest
*
* Initiate the data ingestion and start the SDI’s schema generation process for the current tenant.
* This operation currently supports CSV and XML format files. The XML format file requires root element
* information that is entry point for this operation. This is provided as either rootTag parameter to this
* operation or registered as part of Data Registry API operation. There are two modes for data ingest.
*
* Default: Allows performing the data ingest without need of any Data Registry.
* In this case service processes files with default policy for schema generation.
* The schema generated this way cannot be versioned or changed with different files.
* This mode is used for quick validating the generated schema.
*
* Dataregistry: The operation uses Data Registry for ingested file to generate schema.
* This is preferred mode as it allows more validation against the Data Registry and create
* multiple schema based on different domains created under Data Registry.
* Using this mode customer can create combination of schemas from different domain and query
* them or use for analytical modelling. This works in combination with Data Registry API.
*
* @param {SemanticDataInterconnectModels.SDIIngestData} ingestData
* Specifies the file path and Data Registry information to initiate data ingest process.
* The ‘{filePath}’ is required parameter and valid file path used during file upload operations.
* The ‘{dataTag}’ and ‘{sourceName}’ are the valid Data Registry source name and data tag.
* The ‘{rootTag}’ is optional and applies to XML formatted files.
* @returns {Promise<SemanticDataInterconnectModels.SdiJobStatusResponse>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async PostIngestJob(
ingestData: SemanticDataInterconnectModels.SDIIngestData
): Promise<SemanticDataInterconnectModels.SdiJobStatusResponse> {
const result = await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/ingestJobs`,
body: ingestData,
});
return result as SemanticDataInterconnectModels.SdiJobStatusResponse;
}
/**
* * Data Ingest
*
* Get a list of jobIds that is ingested, this jobId can be used to find detailed status using ingestJobStatus.
*
* @param {{
* pageToken?: string;
* }} [params]
*
* @param params.pageToken
*
* Selects next page. Value must be taken rom response body property 'page.nextToken’.
* If omitted, first page is returned.
*
* @returns {Promise<SemanticDataInterconnectModels.ListOfJobIds>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async GetIngestJobs(params?: { pageToken?: string }): Promise<SemanticDataInterconnectModels.ListOfJobIds> {
const parameters = params || {};
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/ingestJobStatus?${toQueryString(parameters)}`,
});
return result as SemanticDataInterconnectModels.ListOfJobIds;
}
/**
*
* * Data Ingest
*
* Retrieve the job status based on jobid for the current tenant. The jobid belongs to data ingestion process started for the current tenant.
*
* @param {string} id
* @returns {Promise<SemanticDataInterconnectModels.SdiJobStatusResponse>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async GetIngestJobStatus(id: string): Promise<SemanticDataInterconnectModels.SdiJobStatusResponse> {
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/ingestJobStatus/${id}`,
});
return result as SemanticDataInterconnectModels.SdiJobStatusResponse;
}
/**
* * Schema registry
*
* Operations to review generated schemas and infer semantic model based on extracted schemas.
* Search schema for ingested data.
*
* The data ingestion API creates and stores the schemas for each ingested file.
* This schema can be retrieved based on schema name, or source name and data tag combination.
* SchemaSearchRequest is limited to 20 schemas atmost.
*
* @param {SemanticDataInterconnectModels.SchemaSearchRequest} schemaSearchRequest
* @param {{ pageToken?: string }} [params]
* @param params.pageToken
* Selects next page. Value must be taken from response body property 'page.nextToken’.
* If omitted, first page is returned
*
* @returns {Promise<SemanticDataInterconnectModels.ListOfSchemaRegistry>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async SearchSchemas(
schemaSearchRequest: SemanticDataInterconnectModels.SchemaSearchRequest,
params?: { pageToken?: string }
): Promise<SemanticDataInterconnectModels.ListOfSchemaRegistry> {
const parameters = params || {};
const response = (await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/searchSchemas?${toQueryString(parameters)}`,
body: schemaSearchRequest,
rawResponse: true,
})) as Response;
let result;
// handle no content
if (response.status === 204) {
result = { schemas: [] };
} else {
result = response.json();
}
return result as SemanticDataInterconnectModels.ListOfSchemaRegistry;
}
/**
* * Data Query
*
* Returns a list of Data Query SQL Model
*
* @param {{
* pageToken?: string;
* executable?: boolean;
* isDynamic?: boolean;
* ontologyId?: string;
* }} [params]
*
* @param params.pageToken
* Selects next page. Value must be taken from response body property 'page.nextToken’.
* If omitted, first page is returned
*
* @param params.executable
* Filter based on executable flag.
*
* @param params.isDynamic
* Filter based on isDynamic flag.
*
* @param params.ontologyId
* Filter based on ontology id
* @returns {Promise<SemanticDataInterconnectModels.ResponseAllDataSQLQuery>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async GetQueries(params?: {
pageToken?: string;
executable?: boolean;
isDynamic?: boolean;
ontologyId?: string;
}): Promise<SemanticDataInterconnectModels.ResponseAllDataSQLQuery> {
const parameters = params || {};
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/queries?${toQueryString(parameters)}`,
});
return result as SemanticDataInterconnectModels.ResponseAllDataSQLQuery;
}
/**
* * Data Query
*
* Create new queries and returns id of created query.
*
* @param {SemanticDataInterconnectModels.DataQuerySQLRequest} dataQuerySQLRequest
* @returns {Promise<SemanticDataInterconnectModels.DataQuerySQLResponse>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async PostQuery(
dataQuerySQLRequest: SemanticDataInterconnectModels.DataQuerySQLRequest
): Promise<SemanticDataInterconnectModels.DataQuerySQLResponse> {
const result = await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/queries`,
body: dataQuerySQLRequest,
});
return result as SemanticDataInterconnectModels.DataQuerySQLResponse;
}
/**
* * Data Query
*
* Retrieve query by query id.
* Returns a Data Query SQL Model.
*
* @param {string} id
* @returns {Promise<SemanticDataInterconnectModels.NativeQueryGetResponse>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async GetQuery(id: string): Promise<SemanticDataInterconnectModels.NativeQueryGetResponse> {
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/queries/${id}`,
});
return result as SemanticDataInterconnectModels.NativeQueryGetResponse;
}
/**
* * Data Query
*
* Update query by query id
* Returns Updated Data Query SQL Model
*
*
* @param {string} id
* @param {SemanticDataInterconnectModels.DataQuerySQLUpdateRequest} dataQuerySQLUpdateRequest
* @returns {Promise<SemanticDataInterconnectModels.DataQuerySQLResponse>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async PatchQuery(
id: string,
dataQuerySQLUpdateRequest: SemanticDataInterconnectModels.DataQuerySQLUpdateRequest
): Promise<SemanticDataInterconnectModels.DataQuerySQLResponse> {
const result = await this.HttpAction({
verb: "PATCH",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/queries/${id}`,
body: dataQuerySQLUpdateRequest,
});
return result as SemanticDataInterconnectModels.DataQuerySQLResponse;
}
/**
* * Data Query
*
* delete query by query id
*
* @param {string} id
*
* @memberOf SemanticDataInterconnectClient
*/
public async DeleteQuery(id: string) {
await this.HttpAction({
verb: "DELETE",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/queries/${id}`,
noResponse: true,
});
}
/**
* * Query Execution Jobs
*
* Create execution job for dynamic query. There is soft limit of upto 10 number of parameters and aliases.
* Returns id of created job
*
* @param {string} id
* @param {SemanticDataInterconnectModels.DataQueryExecuteQueryRequest} dataQueryExecuteRequest
* @returns {Promise<SemanticDataInterconnectModels.DataQuerySQLResponse>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async PostExecutionJob(
id: string,
dataQueryExecuteRequest: SemanticDataInterconnectModels.DataQueryExecuteQueryRequest
): Promise<SemanticDataInterconnectModels.DataQuerySQLResponse> {
const result = await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/queries/${id}/executionJobs`,
body: dataQueryExecuteRequest,
});
return result as SemanticDataInterconnectModels.DataQueryExecuteQueryResponse;
}
/**
* * Query Execution Jobs
*
* Retrieve latest query results by query id
*
* @param {string} id
* @param {{ Range?: string }} [params]
* @param params.Range
* Part of a file to return in Bytes, eg bytes=200-600
*
* @returns {Promise<SemanticDataInterconnectModels.QueryResult>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async GetQueryExecutionJobLatestResults(
id: string,
params?: { Range?: string }
): Promise<SemanticDataInterconnectModels.QueryResult> {
const parameters = params || {};
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/queries/${id}/executionJobs/latestResults`,
additionalHeaders: parameters,
});
return result as SemanticDataInterconnectModels.QueryResult;
}
/**
*
* * Execution Jobs
*
* Returns query results
*
* @param {string} id
* @param {{ Range?: string }} [params]
*
* @param params.Range
* Part of a file to return in Bytes, eg bytes=200-600
*
* @returns {Promise<SemanticDataInterconnectModels.QueryResult>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async GetExecutionJobResults(
id: string,
params?: { Range?: string }
): Promise<SemanticDataInterconnectModels.QueryResult> {
const parameters = params || {};
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/executionJobs/${id}/results`,
additionalHeaders: parameters,
});
return result as SemanticDataInterconnectModels.QueryResult;
}
/**
* * Execution Jobs
*
* Retrieve job details by job id
* Returns Data Query Execution Model
* @param {string} id
* @returns {Promise<SemanticDataInterconnectModels.DataQueryExecutionResponse>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async GetExecutionJob(id: string): Promise<SemanticDataInterconnectModels.DataQueryExecutionResponse> {
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/executionJobs/${id}`,
});
return result as SemanticDataInterconnectModels.DataQueryExecutionResponse;
}
/**
* * Execution Jobs
*
* Delete job by job id
*
* @param {string} id
*
* @memberOf SemanticDataInterconnectClient
*/
public async DeleteExecutionJob(id: string) {
await this.HttpAction({
verb: "DELETE",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/executionJobs/${id}`,
noResponse: true,
});
}
/**
* * Execution Job
*
* Retrieve all jobs
* *
* @param {{
* pageToken?: string;
* queryId?: string;
* status?: string;
* }} [params]
* @param params.pageToken
* Selects next page.
* Value must be taken rom response body property 'page.nextToken’. If omitted, first page is returned.
*
* @param params.queryId
* Filter based on query id
*
* @param params.status
* Filter based on job status
*
* @returns {Promise<SemanticDataInterconnectModels.ResponseAllDataQueryExecutionResponse>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async GetExecutionJobs(params?: {
pageToken?: string;
queryId?: string;
status?: string;
}): Promise<SemanticDataInterconnectModels.ResponseAllDataQueryExecutionResponse> {
const parameters = params || {};
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/executionJobs?${toQueryString(parameters)}`,
});
return result as SemanticDataInterconnectModels.ResponseAllDataQueryExecutionResponse;
}
/**
* * Ontologies
*
* Retrieve all ontologies.
* Returns a list of ontologies
*
* @param {{
* pageToken?: string;
* }} [params]
*
* @param params.pageToken
* Selects next page.
* Value must be taken rom response body property 'page.nextToken’. If omitted, first page is returned.
* @returns {Promise<SemanticDataInterconnectModels.ResponseAllOntologies>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async GetOntologies(params?: {
pageToken?: string;
}): Promise<SemanticDataInterconnectModels.ResponseAllOntologies> {
const parameters = params || {};
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/ontologies?${toQueryString(parameters)}`,
});
return result as SemanticDataInterconnectModels.ResponseAllOntologies;
}
/**
* * Ontologies
*
* Retrieve ontology.
* @param {string} id
*
* @param {{ Range?: string }} [params]
*
* @param params.Range
* Part of a file to return in Bytes, eg bytes=200-600
*
* @returns {Promise<SemanticDataInterconnectModels.OntologyResponseData>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async GetOntology(
id: string,
params?: { Range?: string }
): Promise<SemanticDataInterconnectModels.OntologyResponseData> {
const parameters = params || {};
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/ontologies/${id}`,
additionalHeaders: parameters,
});
return result as SemanticDataInterconnectModels.OntologyResponseData;
}
/**
* * Ontologies
*
* Delete ontology.
*
* @param {string} id
*
* @memberOf SemanticDataInterconnectClient
*/
public async DeleteOntology(id: string) {
await this.HttpAction({
verb: "DELETE",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/ontologies/${id}`,
noResponse: true,
});
}
/**
* * Ontologies
*
* Infer semantic model based on two or more generated schemas. Currently it supports infer of up to 20 schemas.
* Provide two or more schemas to infer an ontology.
*
* @param {SemanticDataInterconnectModels.InferSchemaSearchRequest} inferSchemaSearchRequest
* @returns this returns the predefined JSON format as required by ontologyJobs operation.
*
* @memberOf SemanticDataInterconnectClient
*/
public async InferOntology(
inferSchemaSearchRequest: SemanticDataInterconnectModels.InferSchemaSearchRequest
): Promise<any> {
const result = await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/inferOntology`,
body: inferSchemaSearchRequest,
});
return result;
}
/**
*
* * Ontologies
*
* Upload file and submit job for create/update ontology
*
* @param {string} ontologyName
* Ontology name should be unique.
* @param {Buffer} file
* We support JSON and OWL file pre-defined format.
* @param {string} [ontologyId]
* Provide OntologyId for updating existing ontology. If empty then will create new ontology.
* @param {string} [ontologyDescription]
* Ontology description.
* @param {string} [keyMappingType]
* Define keyMappingType for ontology.
* Available values : INNER JOIN, FULL OUTER JOIN
* Default value : INNER JOIN
* @returns {Promise<SemanticDataInterconnectModels.OntologyJob>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async PostOntologyJob(
fileName: string,
file: Buffer,
mimetype: string,
ontologyName: string,
ontologyId?: string,
ontologyDescription?: string,
keyMappingType?: string
): Promise<SemanticDataInterconnectModels.OntologyJob> {
const body = sdiTemplate(fileName, file, mimetype, {
ontologyName,
ontologyId,
ontologyDescription,
keyMappingType,
});
const result = await this.HttpAction({
verb: "POST",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/ontologyJobs`,
body: body,
multiPartFormData: true,
});
return result as SemanticDataInterconnectModels.OntologyJob;
}
/**
* * Ontologies
*
* Retrieve status of ontology creation/updation job
*
* @param {string} id
* @returns {Promise<SemanticDataInterconnectModels.JobStatus>}
*
* @memberOf SemanticDataInterconnectClient
*/
public async GetOntologyJobStatus(id: string): Promise<SemanticDataInterconnectModels.JobStatus> {
const result = await this.HttpAction({
verb: "GET",
gateway: this.GetGateway(),
authorization: await this.GetToken(),
baseUrl: `${this._baseUrl}/ontologyJobs/${id}`,
});
return result as SemanticDataInterconnectModels.JobStatus;
}
} | the_stack |
import * as zrUtil from 'zrender/src/core/util';
import Model from './Model';
import * as componentUtil from '../util/component';
import {
enableClassManagement,
parseClassType,
isExtendedClass,
ExtendableConstructor,
ClassManager,
mountExtend
} from '../util/clazz';
import {
makeInner, ModelFinderIndexQuery, queryReferringComponents, ModelFinderIdQuery, QueryReferringOpt
} from '../util/model';
import * as layout from '../util/layout';
import GlobalModel from './Global';
import {
ComponentOption,
ComponentMainType,
ComponentSubType,
ComponentFullType,
ComponentLayoutMode,
BoxLayoutOptionMixin
} from '../util/types';
const inner = makeInner<{
defaultOption: ComponentOption
}, ComponentModel>();
class ComponentModel<Opt extends ComponentOption = ComponentOption> extends Model<Opt> {
// [Caution]: Becuase this class or desecendants can be used as `XXX.extend(subProto)`,
// the class members must not be initialized in constructor or declaration place.
// Otherwise there is bad case:
// class A {xxx = 1;}
// enableClassExtend(A);
// class B extends A {}
// var C = B.extend({xxx: 5});
// var c = new C();
// console.log(c.xxx); // expect 5 but always 1.
/**
* @readonly
*/
type: ComponentFullType;
/**
* @readonly
*/
id: string;
/**
* Because simplified concept is probably better, series.name (or component.name)
* has been having too many resposibilities:
* (1) Generating id (which requires name in option should not be modified).
* (2) As an index to mapping series when merging option or calling API (a name
* can refer to more then one components, which is convinient is some case).
* (3) Display.
* @readOnly But injected
*/
name: string;
/**
* @readOnly
*/
mainType: ComponentMainType;
/**
* @readOnly
*/
subType: ComponentSubType;
/**
* @readOnly
*/
componentIndex: number;
/**
* @readOnly
*/
protected defaultOption: ComponentOption;
/**
* @readOnly
*/
ecModel: GlobalModel;
/**
* @readOnly
*/
static dependencies: string[];
readonly uid: string;
// // No common coordinateSystem needed. Each sub class implement
// // `CoordinateSystemHostModel` itself.
// coordinateSystem: CoordinateSystemMaster | CoordinateSystemExecutive;
/**
* Support merge layout params.
* Only support 'box' now (left/right/top/bottom/width/height).
*/
static layoutMode: ComponentLayoutMode | ComponentLayoutMode['type'];
/**
* Prevent from auto set z, zlevel, z2 by the framework.
*/
preventAutoZ: boolean;
// Injectable properties:
__viewId: string;
__requireNewView: boolean;
static protoInitialize = (function () {
const proto = ComponentModel.prototype;
proto.type = 'component';
proto.id = '';
proto.name = '';
proto.mainType = '';
proto.subType = '';
proto.componentIndex = 0;
})();
constructor(option: Opt, parentModel: Model, ecModel: GlobalModel) {
super(option, parentModel, ecModel);
this.uid = componentUtil.getUID('ec_cpt_model');
}
init(option: Opt, parentModel: Model, ecModel: GlobalModel): void {
this.mergeDefaultAndTheme(option, ecModel);
}
mergeDefaultAndTheme(option: Opt, ecModel: GlobalModel): void {
const layoutMode = layout.fetchLayoutMode(this);
const inputPositionParams = layoutMode
? layout.getLayoutParams(option as BoxLayoutOptionMixin) : {};
const themeModel = ecModel.getTheme();
zrUtil.merge(option, themeModel.get(this.mainType));
zrUtil.merge(option, this.getDefaultOption());
if (layoutMode) {
layout.mergeLayoutParam(option as BoxLayoutOptionMixin, inputPositionParams, layoutMode);
}
}
mergeOption(option: Opt, ecModel: GlobalModel): void {
zrUtil.merge(this.option, option, true);
const layoutMode = layout.fetchLayoutMode(this);
if (layoutMode) {
layout.mergeLayoutParam(
this.option as BoxLayoutOptionMixin,
option as BoxLayoutOptionMixin,
layoutMode
);
}
}
/**
* Called immediately after `init` or `mergeOption` of this instance called.
*/
optionUpdated(newCptOption: Opt, isInit: boolean): void {}
/**
* [How to declare defaultOption]:
*
* (A) If using class declaration in typescript (since echarts 5):
* ```ts
* import {ComponentOption} from '../model/option';
* export interface XxxOption extends ComponentOption {
* aaa: number
* }
* export class XxxModel extends Component {
* static type = 'xxx';
* static defaultOption: XxxOption = {
* aaa: 123
* }
* }
* Component.registerClass(XxxModel);
* ```
* ```ts
* import {inheritDefaultOption} from '../util/component';
* import {XxxModel, XxxOption} from './XxxModel';
* export interface XxxSubOption extends XxxOption {
* bbb: number
* }
* class XxxSubModel extends XxxModel {
* static defaultOption: XxxSubOption = inheritDefaultOption(XxxModel.defaultOption, {
* bbb: 456
* })
* fn() {
* let opt = this.getDefaultOption();
* // opt is {aaa: 123, bbb: 456}
* }
* }
* ```
*
* (B) If using class extend (previous approach in echarts 3 & 4):
* ```js
* let XxxComponent = Component.extend({
* defaultOption: {
* xx: 123
* }
* })
* ```
* ```js
* let XxxSubComponent = XxxComponent.extend({
* defaultOption: {
* yy: 456
* },
* fn: function () {
* let opt = this.getDefaultOption();
* // opt is {xx: 123, yy: 456}
* }
* })
* ```
*/
getDefaultOption(): Opt {
const ctor = this.constructor;
// If using class declaration, it is different to travel super class
// in legacy env and auto merge defaultOption. So if using class
// declaration, defaultOption should be merged manually.
if (!isExtendedClass(ctor)) {
// When using ts class, defaultOption must be declared as static.
return (ctor as any).defaultOption;
}
// FIXME: remove this approach?
const fields = inner(this);
if (!fields.defaultOption) {
const optList = [];
let clz = ctor as ExtendableConstructor;
while (clz) {
const opt = clz.prototype.defaultOption;
opt && optList.push(opt);
clz = clz.superClass;
}
let defaultOption = {};
for (let i = optList.length - 1; i >= 0; i--) {
defaultOption = zrUtil.merge(defaultOption, optList[i], true);
}
fields.defaultOption = defaultOption;
}
return fields.defaultOption as Opt;
}
/**
* Notice: always force to input param `useDefault` in case that forget to consider it.
* The same behavior as `modelUtil.parseFinder`.
*
* @param useDefault In many cases like series refer axis and axis refer grid,
* If axis index / axis id not specified, use the first target as default.
* In other cases like dataZoom refer axis, if not specified, measn no refer.
*/
getReferringComponents(mainType: ComponentMainType, opt: QueryReferringOpt): {
// Always be array rather than null/undefined, which is convenient to use.
models: ComponentModel[];
// Whether target compoent specified
specified: boolean;
} {
const indexKey = (mainType + 'Index') as keyof Opt;
const idKey = (mainType + 'Id') as keyof Opt;
return queryReferringComponents(
this.ecModel,
mainType,
{
index: this.get(indexKey, true) as unknown as ModelFinderIndexQuery,
id: this.get(idKey, true) as unknown as ModelFinderIdQuery
},
opt
);
}
getBoxLayoutParams() {
// Consider itself having box layout configs.
const boxLayoutModel = this as Model<ComponentOption & BoxLayoutOptionMixin>;
return {
left: boxLayoutModel.get('left'),
top: boxLayoutModel.get('top'),
right: boxLayoutModel.get('right'),
bottom: boxLayoutModel.get('bottom'),
width: boxLayoutModel.get('width'),
height: boxLayoutModel.get('height')
};
}
// // Interfaces for component / series with select ability.
// select(dataIndex?: number[], dataType?: string): void {}
// unSelect(dataIndex?: number[], dataType?: string): void {}
// getSelectedDataIndices(): number[] {
// return [];
// }
static registerClass: ClassManager['registerClass'];
static hasClass: ClassManager['hasClass'];
static registerSubTypeDefaulter: componentUtil.SubTypeDefaulterManager['registerSubTypeDefaulter'];
}
export type ComponentModelConstructor = typeof ComponentModel
& ClassManager
& componentUtil.SubTypeDefaulterManager
& ExtendableConstructor
& componentUtil.TopologicalTravelable<object>;
mountExtend(ComponentModel, Model);
enableClassManagement(ComponentModel as ComponentModelConstructor);
componentUtil.enableSubTypeDefaulter(ComponentModel as ComponentModelConstructor);
componentUtil.enableTopologicalTravel(ComponentModel as ComponentModelConstructor, getDependencies);
function getDependencies(componentType: string): string[] {
let deps: string[] = [];
zrUtil.each((ComponentModel as ComponentModelConstructor).getClassesByMainType(componentType), function (clz) {
deps = deps.concat((clz as any).dependencies || (clz as any).prototype.dependencies || []);
});
// Ensure main type.
deps = zrUtil.map(deps, function (type) {
return parseClassType(type).main;
});
// Hack dataset for convenience.
if (componentType !== 'dataset' && zrUtil.indexOf(deps, 'dataset') <= 0) {
deps.unshift('dataset');
}
return deps;
}
export default ComponentModel; | the_stack |
import * as cdk from '@aws-cdk/core';
import * as cfn_parse from '@aws-cdk/core/lib/cfn-parse';
/**
* Properties for defining a `AWS::ElasticLoadBalancing::LoadBalancer`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html
* @external
*/
export interface CfnLoadBalancerProps {
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.Listeners`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-listeners
* @external
*/
readonly listeners: Array<CfnLoadBalancer.ListenersProperty | cdk.IResolvable> | cdk.IResolvable;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.AccessLoggingPolicy`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-accessloggingpolicy
* @external
*/
readonly accessLoggingPolicy?: CfnLoadBalancer.AccessLoggingPolicyProperty | cdk.IResolvable;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.AppCookieStickinessPolicy`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-appcookiestickinesspolicy
* @external
*/
readonly appCookieStickinessPolicy?: Array<CfnLoadBalancer.AppCookieStickinessPolicyProperty | cdk.IResolvable> | cdk.IResolvable;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.AvailabilityZones`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-availabilityzones
* @external
*/
readonly availabilityZones?: string[];
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.ConnectionDrainingPolicy`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-connectiondrainingpolicy
* @external
*/
readonly connectionDrainingPolicy?: CfnLoadBalancer.ConnectionDrainingPolicyProperty | cdk.IResolvable;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.ConnectionSettings`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-connectionsettings
* @external
*/
readonly connectionSettings?: CfnLoadBalancer.ConnectionSettingsProperty | cdk.IResolvable;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.CrossZone`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-crosszone
* @external
*/
readonly crossZone?: boolean | cdk.IResolvable;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.HealthCheck`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-healthcheck
* @external
*/
readonly healthCheck?: CfnLoadBalancer.HealthCheckProperty | cdk.IResolvable;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.Instances`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-instances
* @external
*/
readonly instances?: string[];
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.LBCookieStickinessPolicy`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-lbcookiestickinesspolicy
* @external
*/
readonly lbCookieStickinessPolicy?: Array<CfnLoadBalancer.LBCookieStickinessPolicyProperty | cdk.IResolvable> | cdk.IResolvable;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.LoadBalancerName`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-elbname
* @external
*/
readonly loadBalancerName?: string;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.Policies`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-policies
* @external
*/
readonly policies?: Array<CfnLoadBalancer.PoliciesProperty | cdk.IResolvable> | cdk.IResolvable;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.Scheme`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-scheme
* @external
*/
readonly scheme?: string;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.SecurityGroups`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-securitygroups
* @external
*/
readonly securityGroups?: string[];
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.Subnets`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-subnets
* @external
*/
readonly subnets?: string[];
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.Tags`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-elasticloadbalancing-loadbalancer-tags
* @external
*/
readonly tags?: cdk.CfnTag[];
}
/**
* A CloudFormation `AWS::ElasticLoadBalancing::LoadBalancer`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html
* @external
* @cloudformationResource AWS::ElasticLoadBalancing::LoadBalancer
*/
export declare class CfnLoadBalancer extends cdk.CfnResource implements cdk.IInspectable {
/**
* The CloudFormation resource type name for this resource class.
*
* @external
*/
static readonly CFN_RESOURCE_TYPE_NAME = "AWS::ElasticLoadBalancing::LoadBalancer";
/**
* A factory method that creates a new instance of this class from an object
* containing the CloudFormation properties of this resource.
* Used in the @aws-cdk/cloudformation-include module.
*
* @internal
*/
static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnLoadBalancer;
/**
* @external
* @cloudformationAttribute CanonicalHostedZoneName
*/
readonly attrCanonicalHostedZoneName: string;
/**
* @external
* @cloudformationAttribute CanonicalHostedZoneNameID
*/
readonly attrCanonicalHostedZoneNameId: string;
/**
* @external
* @cloudformationAttribute DNSName
*/
readonly attrDnsName: string;
/**
* @external
* @cloudformationAttribute SourceSecurityGroup.GroupName
*/
readonly attrSourceSecurityGroupGroupName: string;
/**
* @external
* @cloudformationAttribute SourceSecurityGroup.OwnerAlias
*/
readonly attrSourceSecurityGroupOwnerAlias: string;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.Listeners`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-listeners
* @external
*/
listeners: Array<CfnLoadBalancer.ListenersProperty | cdk.IResolvable> | cdk.IResolvable;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.AccessLoggingPolicy`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-accessloggingpolicy
* @external
*/
accessLoggingPolicy: CfnLoadBalancer.AccessLoggingPolicyProperty | cdk.IResolvable | undefined;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.AppCookieStickinessPolicy`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-appcookiestickinesspolicy
* @external
*/
appCookieStickinessPolicy: Array<CfnLoadBalancer.AppCookieStickinessPolicyProperty | cdk.IResolvable> | cdk.IResolvable | undefined;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.AvailabilityZones`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-availabilityzones
* @external
*/
availabilityZones: string[] | undefined;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.ConnectionDrainingPolicy`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-connectiondrainingpolicy
* @external
*/
connectionDrainingPolicy: CfnLoadBalancer.ConnectionDrainingPolicyProperty | cdk.IResolvable | undefined;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.ConnectionSettings`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-connectionsettings
* @external
*/
connectionSettings: CfnLoadBalancer.ConnectionSettingsProperty | cdk.IResolvable | undefined;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.CrossZone`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-crosszone
* @external
*/
crossZone: boolean | cdk.IResolvable | undefined;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.HealthCheck`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-healthcheck
* @external
*/
healthCheck: CfnLoadBalancer.HealthCheckProperty | cdk.IResolvable | undefined;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.Instances`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-instances
* @external
*/
instances: string[] | undefined;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.LBCookieStickinessPolicy`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-lbcookiestickinesspolicy
* @external
*/
lbCookieStickinessPolicy: Array<CfnLoadBalancer.LBCookieStickinessPolicyProperty | cdk.IResolvable> | cdk.IResolvable | undefined;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.LoadBalancerName`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-elbname
* @external
*/
loadBalancerName: string | undefined;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.Policies`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-policies
* @external
*/
policies: Array<CfnLoadBalancer.PoliciesProperty | cdk.IResolvable> | cdk.IResolvable | undefined;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.Scheme`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-scheme
* @external
*/
scheme: string | undefined;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.SecurityGroups`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-securitygroups
* @external
*/
securityGroups: string[] | undefined;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.Subnets`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-subnets
* @external
*/
subnets: string[] | undefined;
/**
* `AWS::ElasticLoadBalancing::LoadBalancer.Tags`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-elasticloadbalancing-loadbalancer-tags
* @external
*/
readonly tags: cdk.TagManager;
/**
* Create a new `AWS::ElasticLoadBalancing::LoadBalancer`.
*
* @param scope - scope in which this resource is defined.
* @param id - scoped id of the resource.
* @param props - resource properties.
* @external
*/
constructor(scope: cdk.Construct, id: string, props: CfnLoadBalancerProps);
/**
* (experimental) Examines the CloudFormation resource and discloses attributes.
*
* @param inspector - tree inspector to collect and process attributes.
* @experimental
*/
inspect(inspector: cdk.TreeInspector): void;
/**
* @external
*/
protected get cfnProperties(): {
[key: string]: any;
};
/**
* @external
*/
protected renderProperties(props: {
[key: string]: any;
}): {
[key: string]: any;
};
}
/**
* A CloudFormation `AWS::ElasticLoadBalancing::LoadBalancer`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html
* @external
* @cloudformationResource AWS::ElasticLoadBalancing::LoadBalancer
*/
export declare namespace CfnLoadBalancer {
/**
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-accessloggingpolicy.html
* @external
*/
interface AccessLoggingPolicyProperty {
/**
* `CfnLoadBalancer.AccessLoggingPolicyProperty.EmitInterval`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-accessloggingpolicy.html#cfn-elb-accessloggingpolicy-emitinterval
* @external
*/
readonly emitInterval?: number;
/**
* `CfnLoadBalancer.AccessLoggingPolicyProperty.Enabled`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-accessloggingpolicy.html#cfn-elb-accessloggingpolicy-enabled
* @external
*/
readonly enabled: boolean | cdk.IResolvable;
/**
* `CfnLoadBalancer.AccessLoggingPolicyProperty.S3BucketName`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-accessloggingpolicy.html#cfn-elb-accessloggingpolicy-s3bucketname
* @external
*/
readonly s3BucketName: string;
/**
* `CfnLoadBalancer.AccessLoggingPolicyProperty.S3BucketPrefix`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-accessloggingpolicy.html#cfn-elb-accessloggingpolicy-s3bucketprefix
* @external
*/
readonly s3BucketPrefix?: string;
}
}
/**
* A CloudFormation `AWS::ElasticLoadBalancing::LoadBalancer`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html
* @external
* @cloudformationResource AWS::ElasticLoadBalancing::LoadBalancer
*/
export declare namespace CfnLoadBalancer {
/**
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-AppCookieStickinessPolicy.html
* @external
*/
interface AppCookieStickinessPolicyProperty {
/**
* `CfnLoadBalancer.AppCookieStickinessPolicyProperty.CookieName`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-AppCookieStickinessPolicy.html#cfn-elb-appcookiestickinesspolicy-cookiename
* @external
*/
readonly cookieName: string;
/**
* `CfnLoadBalancer.AppCookieStickinessPolicyProperty.PolicyName`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-AppCookieStickinessPolicy.html#cfn-elb-appcookiestickinesspolicy-policyname
* @external
*/
readonly policyName: string;
}
}
/**
* A CloudFormation `AWS::ElasticLoadBalancing::LoadBalancer`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html
* @external
* @cloudformationResource AWS::ElasticLoadBalancing::LoadBalancer
*/
export declare namespace CfnLoadBalancer {
/**
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-connectiondrainingpolicy.html
* @external
*/
interface ConnectionDrainingPolicyProperty {
/**
* `CfnLoadBalancer.ConnectionDrainingPolicyProperty.Enabled`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-connectiondrainingpolicy.html#cfn-elb-connectiondrainingpolicy-enabled
* @external
*/
readonly enabled: boolean | cdk.IResolvable;
/**
* `CfnLoadBalancer.ConnectionDrainingPolicyProperty.Timeout`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-connectiondrainingpolicy.html#cfn-elb-connectiondrainingpolicy-timeout
* @external
*/
readonly timeout?: number;
}
}
/**
* A CloudFormation `AWS::ElasticLoadBalancing::LoadBalancer`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html
* @external
* @cloudformationResource AWS::ElasticLoadBalancing::LoadBalancer
*/
export declare namespace CfnLoadBalancer {
/**
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-connectionsettings.html
* @external
*/
interface ConnectionSettingsProperty {
/**
* `CfnLoadBalancer.ConnectionSettingsProperty.IdleTimeout`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-connectionsettings.html#cfn-elb-connectionsettings-idletimeout
* @external
*/
readonly idleTimeout: number;
}
}
/**
* A CloudFormation `AWS::ElasticLoadBalancing::LoadBalancer`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html
* @external
* @cloudformationResource AWS::ElasticLoadBalancing::LoadBalancer
*/
export declare namespace CfnLoadBalancer {
/**
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-health-check.html
* @external
*/
interface HealthCheckProperty {
/**
* `CfnLoadBalancer.HealthCheckProperty.HealthyThreshold`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-health-check.html#cfn-elb-healthcheck-healthythreshold
* @external
*/
readonly healthyThreshold: string;
/**
* `CfnLoadBalancer.HealthCheckProperty.Interval`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-health-check.html#cfn-elb-healthcheck-interval
* @external
*/
readonly interval: string;
/**
* `CfnLoadBalancer.HealthCheckProperty.Target`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-health-check.html#cfn-elb-healthcheck-target
* @external
*/
readonly target: string;
/**
* `CfnLoadBalancer.HealthCheckProperty.Timeout`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-health-check.html#cfn-elb-healthcheck-timeout
* @external
*/
readonly timeout: string;
/**
* `CfnLoadBalancer.HealthCheckProperty.UnhealthyThreshold`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-health-check.html#cfn-elb-healthcheck-unhealthythreshold
* @external
*/
readonly unhealthyThreshold: string;
}
}
/**
* A CloudFormation `AWS::ElasticLoadBalancing::LoadBalancer`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html
* @external
* @cloudformationResource AWS::ElasticLoadBalancing::LoadBalancer
*/
export declare namespace CfnLoadBalancer {
/**
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-LBCookieStickinessPolicy.html
* @external
*/
interface LBCookieStickinessPolicyProperty {
/**
* `CfnLoadBalancer.LBCookieStickinessPolicyProperty.CookieExpirationPeriod`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-LBCookieStickinessPolicy.html#cfn-elb-lbcookiestickinesspolicy-cookieexpirationperiod
* @external
*/
readonly cookieExpirationPeriod?: string;
/**
* `CfnLoadBalancer.LBCookieStickinessPolicyProperty.PolicyName`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-LBCookieStickinessPolicy.html#cfn-elb-lbcookiestickinesspolicy-policyname
* @external
*/
readonly policyName?: string;
}
}
/**
* A CloudFormation `AWS::ElasticLoadBalancing::LoadBalancer`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html
* @external
* @cloudformationResource AWS::ElasticLoadBalancing::LoadBalancer
*/
export declare namespace CfnLoadBalancer {
/**
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-listener.html
* @external
*/
interface ListenersProperty {
/**
* `CfnLoadBalancer.ListenersProperty.InstancePort`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-listener.html#cfn-ec2-elb-listener-instanceport
* @external
*/
readonly instancePort: string;
/**
* `CfnLoadBalancer.ListenersProperty.InstanceProtocol`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-listener.html#cfn-ec2-elb-listener-instanceprotocol
* @external
*/
readonly instanceProtocol?: string;
/**
* `CfnLoadBalancer.ListenersProperty.LoadBalancerPort`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-listener.html#cfn-ec2-elb-listener-loadbalancerport
* @external
*/
readonly loadBalancerPort: string;
/**
* `CfnLoadBalancer.ListenersProperty.PolicyNames`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-listener.html#cfn-ec2-elb-listener-policynames
* @external
*/
readonly policyNames?: string[];
/**
* `CfnLoadBalancer.ListenersProperty.Protocol`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-listener.html#cfn-ec2-elb-listener-protocol
* @external
*/
readonly protocol: string;
/**
* `CfnLoadBalancer.ListenersProperty.SSLCertificateId`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-listener.html#cfn-ec2-elb-listener-sslcertificateid
* @external
*/
readonly sslCertificateId?: string;
}
}
/**
* A CloudFormation `AWS::ElasticLoadBalancing::LoadBalancer`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html
* @external
* @cloudformationResource AWS::ElasticLoadBalancing::LoadBalancer
*/
export declare namespace CfnLoadBalancer {
/**
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html
* @external
*/
interface PoliciesProperty {
/**
* `CfnLoadBalancer.PoliciesProperty.Attributes`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-attributes
* @external
*/
readonly attributes: Array<any | cdk.IResolvable> | cdk.IResolvable;
/**
* `CfnLoadBalancer.PoliciesProperty.InstancePorts`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-instanceports
* @external
*/
readonly instancePorts?: string[];
/**
* `CfnLoadBalancer.PoliciesProperty.LoadBalancerPorts`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-loadbalancerports
* @external
*/
readonly loadBalancerPorts?: string[];
/**
* `CfnLoadBalancer.PoliciesProperty.PolicyName`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-policyname
* @external
*/
readonly policyName: string;
/**
* `CfnLoadBalancer.PoliciesProperty.PolicyType`.
*
* @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-policytype
* @external
*/
readonly policyType: string;
}
} | the_stack |
declare module "magix-combine" {
interface ICombineResult {
/**
* 通过config指定的tmplFolder文件夹中的文件路径
*/
from: string
/**
* 通过config指定的srcFolder文件夹中的文件路径
*/
to: string | undefined
/**
* 当前编译的from文件依赖的其它文件
*/
fileDeps: {
[key: string]: 1
}
/**
* 文件内容
*/
content: string
/**
* 指示是否排除define的包装
*/
exclude: boolean
/**
* 指示是否把该文件内容根据to的位置写入到硬盘上
*/
writeFile: boolean
/**
* 模块id
*/
moduleId: string
/**
* 依赖的其它模块,同requires
*/
deps: string[]
/**
* 依赖的其它模块,同deps
*/
requires: string[]
/**
* 依赖的模块声明的变量
*/
vars: string[]
/**
* 当前js文件收集到的样式名称映射对象
*/
cssNamesMap: {
[originalSelector: string]: string
}
/**
* 当前js文件收集到的样式名称所在的文件
*/
cssNamesInFiles: {
[selector: string]: string
}
/**
* 当前js文件收集到的样式标签名称所在的文件
*/
cssTagsInFiles: {
[tag: string]: string
},
/**
* 模块包名
*/
pkgName: string
}
interface IRequireInfo {
/**
* require语句变量前面的前缀信息,如var或,等
*/
prefix: string
/**
* require语句后面的信息,如;等
*/
tail: string
/**
* 未经任何处理的原始模块id
*/
originalDependedId: string
/**
* 依赖的id
*/
dependedId: string
/**
* 声明的变量字符串
*/
variable: string
/**
* 如果存在该字段,则把require语句换成该字段指定的内容
*/
replacement?: string
}
interface ICheckerConfig {
/**
* 样式
*/
css: boolean
// /**
// * 样式中的url
// */
// cssUrl: boolean
// /**
// * js循环
// */
// jsLoop: boolean
// /**
// * js接口服务
// */
// jsService: boolean
/**
* js this别名
*/
//jsThis: boolean
/**
* 模板命令语法检查
*/
tmplCmdSyntax: boolean
/**
* 模板img属性
*/
//tmplAttrImg: boolean
/**
* 不允许的标签
*/
tmplDisallowedTag: boolean
/**
* 危险的属性
*/
tmplAttrDangerous: boolean
/**
* 需要添加noopener
*/
tmplAttrNoopener: boolean
/**
* 检测anchor类标签
*/
tmplAttrAnchor: boolean
/**
* mx事件
*/
tmplAttrMxEvent: boolean
/**
* mx view
*/
tmplAttrMxView: boolean
/**
* 重复的属性
*/
tmplDuplicateAttr: boolean
/**
* 模板中函数或for of检测
*/
tmplCmdFnOrForOf: boolean
/**
* 标签配对
*/
//tmplTagsMatch: boolean
}
/**
* 组件信息对象
*/
interface IGMap {
/**
* 组件的路径
*/
path: string
/**
* 生成组件时,使用的原生的html标签
*/
tag: string
}
interface ICompileCssStart {
/**
* 扩展名
*/
ext: string
/**
* 文件完整路径
*/
file: string
/**
* css内容
*/
content: string
/**
* 短文件名
*/
shortFile: string
}
/**
* 读取css结果对象
*/
interface ICompileCssResult {
/**
* 读取的样式文件是否存在
*/
exists: boolean
/**
* 文件完整路径
*/
file: string
/**
* css内容
*/
content: string
/**
* source map
*/
map: object
}
interface IConfig {
/**
* 编译的模板目录。默认tmpl
*/
commonFolder?: string
/**
* 编译结果存储目录。默认src
*/
compiledFolder?: string
/**
* 匹配模板中模板引擎语句的正则,对模板处理时,先去掉无关的内容处理起来会更准确
*/
tmplCommand?: RegExp
/**
* cssnano压缩选项
*/
cssnano: object
/**
* less编译选项
*/
less: object
/**
* sass编译选项
*/
sass: object
/**
* 生成样式选择器时的前缀,通常是项目名。
*/
projectName?: string
/**
* 是否输出css sourcemap,默认false
*/
//sourceMapCss?: boolean
/**
* 是否支持类似 import 'style.css' 导入样式的语法,默认false
*/
importCssSyntax?: boolean
/**
* magix模块名称,默认magix
*/
magixModuleIds?: [string]
/**
* 任务同时执行的并发数量,默认为1
*/
concurrentTask: number
/**
* autprefixer配置
*/
autoprefixer?: object
/**
* 加载器类型,该选项决定如何添加包装,如添加define函数。默认为cmd加载器
*/
loaderType?: "amd" | "amd_es" | "cmd" | "cmd_es" | "iife" | "iife_es" | "none" | "webpack" | "kissy" | "kissy_es" | "umd" | "umd_es" | "acmd" | "acmd_es"
/**
* html压缩选项
*/
htmlminifier?: object
/**
* 是否输出日志信息。默认为true
*/
log?: boolean
/**
* 编译成调试版本,默认false
*/
debug?: boolean
/**
* 检测对象
*/
checker?: ICheckerConfig
/**
* 是否把模板中的view打包到js中的文件依赖中,默认false。如果为true,渲染的view会在加载相应的js时提前加载,有效解决页面渲染时子view加载的闪烁问题
*/
tmplAddViewsToDependencies?: boolean
/**
* 是否增加事件前缀,开启该选项有利于提高magix查找vframe的效率。默认为true
*/
tmplAddEventPrefix?: boolean
/**
* 模板中静态节点分析,只有在magixUpdaterIncrease启用的情况下该配置项才生效,默认true
*/
tmplStaticAnalyze?: boolean
/**
* 项目中使用的全局样式,不建议使用该选项
*/
globalCss?: string[]
/**
* 项目中全局但做为scoped使用的样式
*/
scopedCss?: string[]
/**
* 对样式做检测时,忽略某些全局样式的检测,该选项配合globalCss使用。
*/
uncheckGlobalCss?: string[]
/**
* 是否使用@转换路径的功能,如@./index转换成app/views/orders/index。默认为true
*/
useAtPathConverter?: boolean
/**
* 待编译的文件后缀,默认为['js', 'mx', 'ts', 'jsx', 'es', 'tsx']
*/
jsFileExtNames?: string[]
/**
* mx-view 处理器
*/
mxViewProcessor?: ({ path: string, pkgName: string }) => string
/**
* 待编译的模板文件后缀,默认为['html', 'haml', 'pug', 'jade', 'tpl']
*/
tmplFileExtNames?: string[]
/**
* 模板中不会变的变量,减少不必要的子模板的分析输出
*/
tmplConstVars?: object
/**
* 是否使用类mustach模板,默认true
*/
tmplArtEngine?: boolean
/**
* 模板中的全局变量,这些变量不会做scope处理
*/
tmplGlobalVars?: object
/**
* 模板输出时是否输出识别到的事件列表,默认为false
*/
tmplOutputWithEvents?: boolean
/**
* 是否启用增量更新,即dom diff
*/
magixUpdaterIncrement?: boolean
/**
* 是否启用双向绑定时生成唯一一个mxe属性,默认true
*/
magixUpdaterBindExpression?: boolean
/**
* 是否启用quick模板
*/
magixUpdaterQuick?: boolean
/**
* 是否禁用magix view中的updater,该选项影响模板对象的输出,默认为false
*/
disableMagixUpdater?: boolean
/**
* 补充模板中方法调用时的参数
*/
tmplPadCallArguments?: (name: string) => string
/**
* 编译文件被写入硬盘时调用
*/
writeFileStart?: (e: ICombineResult) => void
/**
* 开始编译某个js文件之前的处理器,可以加入一些处理,比如typescript的预处理
*/
compileJSStart?: (content: string, e: ICombineResult) => string | Promise<ICombineResult> | Promise<string>
/**
* 结束编译时的处理器
*/
compileJSEnd?: (content: string, e: ICombineResult) => string | Promise<ICombineResult> | Promise<string>
/**
* 开始编译css前处理器
*/
compileCSSStart?: (css: string, e: ICompileCssStart) => Promise<string> | string
/**
* 结束编译css时的处理器
*/
compileCSSEnd?: (css: string, e: ICompileCssResult) => Promise<string> | string
/**
* 对自定义标签做加工处理
*/
customTagProcessor?: (tmpl: string, e?: ICombineResult) => string
/**
* 检测js代码中循环嵌套的层数,当超过该值时,输出提示,默认4层。合理的数据结构可以减少循环的嵌套,有效的提升性能
*/
jsLoopDepth?: number
/**
* 组件配置对象
*/
galleries?: object
/**
* 对模板中的标签做处理
*/
tmplTagProcessor?: (tag: string) => string
/**
* 对模板中的样式类做处理
*/
cssNamesProcessor?: (tmpl: string, cssNamesMap?: object) => string
/**
* 转换模板中的命令字符串
*/
compileTmplCommand?: (tmpl: string, config: IConfig) => string
/**
* 开始转换模板
*/
compileTmplStart?: (tmpl: string) => string
/**
* 结束转换模板
*/
compileTmplEnd?: (tmpl: string) => string
/**
* 处理样式内容
*/
cssConentProcessor?: (content: string, shortName: string, e: ICombineResult) => Promise<string>
applyStyleProcessor?: () => string
/**
* 加工处理模块id
*/
resolveModuleId?: (moduleId: string) => string
/**
* 加工处理require语句
*/
resolveRequire?: (requireInfo: IRequireInfo, e?: ICombineResult) => void
}
/**
* 配置打包编译参数
* @param cfg 配置对象
*/
function config(cfg: IConfig): IConfig
/**
* 遍历文件夹及子、孙文件夹下的文件
* @param folder 文件夹
* @param callback 回调
*/
function walk(folder: string, callback: (file: string) => void): void
/**
* 读取文件内容
* @param file 文件路径
* @param original 是否二进制数据
*/
function readFile<T>(file: string, original: boolean): T
/**
* 复制文件,当复制到的路径中文件夹不存在时,会自动创建文件夹
* @param from 源文件位置
* @param to 复制到目标位置
*/
function copyFile(from: string, to: string): void
/**
* 写入文件内容,当目标位置中的文件夹不存在时,会自动创建文件夹
* @param to 目标位置
* @param content 文件内容
*/
function writeFile(to: string, content: string): void
/**
* 移除magix-combine中对该文件相关的依赖及其它信息
* @param from 模板文件夹tmpl中的文件
*/
function removeFile(from: string): void
/**
* 根据配置信息编译整个项目中的文件
*/
function combine(): Promise<void>
/**
* 编译单个模板文件并写入src目录
* @param from 模板文件夹tmpl中的文件
*/
function processFile(from: string): Promise<void>
/**
* 编译文件内容,返回编译后的对象,不写入到硬盘
* @param from 模板文件夹tmplFolder中的文件
* @param to 源文件夹srcFolder中的文件位置,可选
* @param content 文件内容,可选
*/
function processContent(from: string, to?: string, content?: string): Promise<ICombineResult>
/**
* 处理tmpl文件夹中的模板文件,通常向节点添加spm等属性
*/
function processTmpl(): Promise<void>
/**
* 移除某个文件的缓存,在下次编译的时候重新编译该文件
* @param file 文件路径
*/
function removeCache(file: string): void
/**
* 获取依赖当前文件的其它文件
* @param file 文件路径
*/
function getFileDependents(file: string): object
} | the_stack |
import { format, parseISO } from 'date-fns';
import * as types from '../actions/actionTypes';
// jNote - build interface for state TODO: this should be in types?
interface StateInterface {
currentTab: string,
reqResArray: [],
scheduledReqResArray: [],
history: [],
collections: [],
warningMessage: Record<string, unknown>,
newRequestsOpenAPI: {
openapiMetadata: {
info: Record<string, unknown>,
tags: [],
serverUrls: [],
},
openapiReqArray: [],
},
newRequestFields: {
protocol: string,
restUrl: string,
wsUrl: string,
gqlUrl: string,
grpcUrl: string,
webrtcUrl: string,
url: string,
method: string,
graphQL: boolean,
gRPC: boolean,
ws: boolean,
openapi: boolean,
webrtc: boolean,
webhook: boolean,
network: string,
testContent: string,
testResults: [],
openapiReqObj: Record<string, unknown>,
},
newRequestHeaders: {
headersArr: [],
count: number,
},
newRequestStreams: {
streamsArr: [],
count: number,
streamContent: [],
selectedPackage: null,
selectedRequest: null,
selectedService: null,
selectedServiceObj: null,
selectedStreamingType: null,
initialQuery: null,
queryArr: null,
protoPath: null,
services: null,
protoContent: string,
},
newRequestCookies: {
cookiesArr: [],
count: number,
},
newRequestBody: {
bodyContent: string,
bodyVariables: string,
bodyType: string,
rawType: string,
JSONFormatted: boolean,
bodyIsNew: boolean,
},
newRequestSSE: {
isSSE: boolean,
},
newRequestOpenAPIObject: {
request: {
id: number,
enabled: boolean,
reqTags: [],
reqServers: [],
summary: string,
description: string,
operationId: string,
method: string,
endpoint: string,
headers: Record<string, unknown>,
parameters: [],
body: Record<string, unknown>,
urls: [],
},
},
introspectionData: { schemaSDL: null, clientSchema: null },
dataPoints: Record<string, unknown>,
currentResponse: {
request: {
network: string,
},
},
};
// jNote - need to tie it to state interface
const initialState: StateInterface = {
currentTab: 'First Tab',
reqResArray: [],
scheduledReqResArray: [],
history: [],
collections: [],
warningMessage: {},
newRequestsOpenAPI: {
openapiMetadata: {
info: {},
tags: [],
serverUrls: [],
},
openapiReqArray: [],
},
newRequestFields: {
protocol: '',
restUrl: 'http://',
wsUrl: 'ws://',
gqlUrl: 'https://',
grpcUrl: '',
webrtcUrl: '',
url: 'http://',
method: 'GET',
graphQL: false,
gRPC: false,
ws: false,
openapi: false,
webrtc: false,
webhook: false,
network: 'rest',
testContent: '',
testResults: [],
openapiReqObj: {},
},
newRequestHeaders: {
headersArr: [],
count: 0,
},
newRequestStreams: {
streamsArr: [],
count: 0,
streamContent: [],
selectedPackage: null,
selectedRequest: null,
selectedService: null,
selectedServiceObj: null,
selectedStreamingType: null,
initialQuery: null,
queryArr: null,
protoPath: null,
services: null,
protoContent: '',
},
newRequestCookies: {
cookiesArr: [],
count: 0,
},
newRequestBody: {
bodyContent: '',
bodyVariables: '',
bodyType: 'raw',
rawType: 'text/plain',
JSONFormatted: true,
bodyIsNew: false,
},
newRequestSSE: {
isSSE: false,
},
newRequestOpenAPIObject: {
request: {
id: 0,
enabled: true,
reqTags: [],
reqServers: [],
summary: '',
description: '',
operationId: '',
method: '',
endpoint: '',
headers: {},
parameters: [],
body: {},
urls: [],
},
},
introspectionData: { schemaSDL: null, clientSchema: null },
dataPoints: {},
currentResponse: {
request: {
network: '',
},
},
};
const businessReducer = (state = initialState, action: {type: string, payload: unknown}): StateInterface => {
switch (action.type) {
case types.GET_HISTORY: {
return {
...state,
history: action.payload,
};
}
case types.DELETE_HISTORY: {
const deleteId: number = action.payload.id;
let createdAt
if(typeof action.payload.createdAt === 'string') {
createdAt = parseISO(action.payload.createdAt)
} else {
createdAt = action.payload.createdAt
}
const deleteDate: string = format(createdAt, 'MM/dd/yyyy');
const newHistory = JSON.parse(JSON.stringify(state.history));
// @ts-expect-error ts-migrate(2304) FIXME: Cannot find name '$TSFixMe'.
newHistory.forEach((obj: $TSFixMe, i: $TSFixMe) => {
if (obj.date === deleteDate)
// @ts-expect-error ts-migrate(2304) FIXME: Cannot find name '$TSFixMe'.
obj.history = obj.history.filter((hist: $TSFixMe) => hist.id !== deleteId);
if (obj.history.length === 0) {
newHistory.splice(i, 1);
}
});
console.log('newHistory', newHistory)
return {
...state,
history: newHistory,
};
}
case types.CLEAR_HISTORY: {
return {
...state,
history: [],
};
}
case types.GET_COLLECTIONS: {
return {
...state,
collections: action.payload,
};
}
case types.DELETE_COLLECTION: {
const deleteId: Record<string, unknown> = action.payload.id;
const newCollections: string[] = JSON.parse(JSON.stringify(state.collections));
// @ts-expect-error ts-migrate(2304) FIXME: Cannot find name '$TSFixMe'.
newCollections.forEach((obj: Record<string, unknown>, i: $TSFixMe) => {
if (obj.id === deleteId) {
newCollections.splice(i, 1);
}
});
return {
...state,
collections: newCollections,
};
}
case types.RESET_COMPOSER_FIELDS: {
return {
...state,
newRequestHeaders: {
headersArr: [],
count: 0,
},
newRequestCookies: {
cookiesArr: [],
count: 0,
},
newRequestBody: {
...state.newRequestBody,
bodyContent: '',
bodyVariables: '',
bodyType: 'raw',
rawType: 'text/plain',
JSONFormatted: true,
},
newRequestFields: { // should this clear every field or just protocol?
...state.newRequestFields,
protocol: '',
},
newRequestSSE: {
isSSE: false,
},
warningMessage: {},
};
}
case types.COLLECTION_TO_REQRES: {
const reqResArray = JSON.parse(JSON.stringify(action.payload));
return {
...state,
reqResArray,
};
}
case types.COLLECTION_ADD: {
// add to collection to array in state
return {
...state,
collections: [action.payload, ...state.collections],
};
}
case types.COLLECTION_UPDATE: {
// update collection from state
const collectionName = action.payload.name;
const newCollections: string[] = JSON.parse(JSON.stringify(state.collections));
// @ts-expect-error ts-migrate(2304) FIXME: Cannot find name '$TSFixMe'.
newCollections.forEach((obj: $TSFixMe, i: $TSFixMe) => {
if (obj.name === collectionName) {
newCollections[i] = action.payload;
}
});
return {
...state,
collections: newCollections,
};
}
case types.REQRES_CLEAR: {
return {
...state,
reqResArray: [],
currentResponse: {
request: {
network: '',
},
},
};
}
case types.REQRES_ADD: {
const reqResArray = JSON.parse(JSON.stringify(state.reqResArray));
reqResArray.push(action.payload);
const addDate = format(action.payload.createdAt, 'MM/dd/yyyy');
const newHistory: string[] = JSON.parse(JSON.stringify(state.history));
let updated = false;
// if there is history for added date, add query to beginning of history
// @ts-expect-error ts-migrate(2304) FIXME: Cannot find name '$TSFixMe'.
newHistory.forEach((obj: $TSFixMe) => {
if (obj.date === addDate) {
obj.history.unshift(action.payload);
updated = true;
}
});
// if there is not history at added date, create new history with new query
if (!updated) {
newHistory.unshift({
date: addDate,
history: [action.payload],
});
}
return {
...state,
reqResArray,
history: newHistory,
};
}
case types.REQRES_DELETE: {
const deleteId = action.payload.id;
const newReqResArray = state.reqResArray.filter(
// @ts-expect-error ts-migrate(2339) FIXME: Property 'id' does not exist on type 'never'.
(reqRes) => reqRes.id !== deleteId
);
return {
...state,
reqResArray: newReqResArray,
};
}
case types.SET_CHECKS_AND_MINIS: {
return {
...state,
reqResArray: JSON.parse(JSON.stringify(action.payload)),
};
}
case types.REQRES_UPDATE: {
const reqResDeepCopy = JSON.parse(JSON.stringify(state.reqResArray));
let indexToBeUpdated;
// @ts-expect-error ts-migrate(2304) FIXME: Cannot find name '$TSFixMe'.
reqResDeepCopy.forEach((reqRes: $TSFixMe, index: $TSFixMe) => {
if (reqRes.id === action.payload.id) indexToBeUpdated = index;
});
if (indexToBeUpdated !== undefined) {
// @ts-expect-error ts-migrate(2339) FIXME: Property 'checked' does not exist on type 'never'.
action.payload.checked = state.reqResArray[indexToBeUpdated].checked;
action.payload.minimized =
// @ts-expect-error ts-migrate(2339) FIXME: Property 'minimized' does not exist on type 'never... Remove this comment to see the full error message
state.reqResArray[indexToBeUpdated].minimized;
reqResDeepCopy.splice(
indexToBeUpdated,
1,
JSON.parse(JSON.stringify(action.payload))
); // FOR SOME REASON THIS IS NECESSARY, MESSES UP CHECKS OTHERWISE
}
return {
...state,
reqResArray: reqResDeepCopy,
};
}
case types.SCHEDULED_REQRES_UPDATE: {
const scheduledReqResArray = JSON.parse(
JSON.stringify(state.scheduledReqResArray)
);
scheduledReqResArray.push(action.payload);
return {
...state,
scheduledReqResArray,
};
}
case types.SCHEDULED_REQRES_DELETE: {
// @ts-expect-error ts-migrate(2304) FIXME: Cannot find name '$TSFixMe'.
const scheduledReqResArray: $TSFixMe = [];
return {
...state,
scheduledReqResArray,
};
}
case types.UPDATE_GRAPH: {
const { id } = action.payload;
// action.payload is the latest reqRes object
// dataPoints to be used by graph
const dataPointsCopy = JSON.parse(JSON.stringify(state.dataPoints));
dataPointsCopy.current = id;
// if more than 8 points, data will shift down an index
if (!dataPointsCopy[id]) {
dataPointsCopy[id] = [];
} else if (dataPointsCopy[id].length > 49) {
dataPointsCopy[id] = dataPointsCopy[id].slice(1);
}
// check if new object is a closed request with timeSent and timeReceived
if (
!dataPointsCopy[id].some(
// @ts-expect-error ts-migrate(2304) FIXME: Cannot find name '$TSFixMe'.
(elem: $TSFixMe) => elem.timeSent === action.payload.timeSent
)
) {
// if a color hasn't been added to this specific request id, add a new one
const color = !dataPointsCopy[id][0]?.color
? `${Math.random() * 256}, ${Math.random() * 256}, ${
Math.random() * 256
}`
: dataPointsCopy[id][0].color;
// add dataPoint to array connected to its id -and return to state
dataPointsCopy[id].push({
reqRes: action.payload,
url: action.payload.url,
timeSent: action.payload.timeSent,
timeReceived: action.payload.timeReceived,
createdAt: action.payload.createdAt,
color,
});
return {
...state,
dataPoints: dataPointsCopy,
};
}
return {
...state,
dataPoints: dataPointsCopy,
};
}
case types.CLEAR_GRAPH: {
const dataPointsCopy = JSON.parse(JSON.stringify(state.dataPoints));
dataPointsCopy[action.payload] = [];
return {
...state,
dataPoints: dataPointsCopy,
};
}
case types.CLEAR_ALL_GRAPH: {
return {
...state,
dataPoints: {},
};
}
case types.SET_COMPOSER_WARNING_MESSAGE: {
return {
...state,
warningMessage: action.payload,
};
}
case types.SET_NEW_REQUEST_FIELDS: {
return {
...state,
newRequestFields: action.payload,
};
}
case types.SET_NEW_REQUEST_HEADERS: {
return {
...state,
newRequestHeaders: action.payload,
};
}
case types.SET_NEW_REQUEST_STREAMS: {
return {
...state,
newRequestStreams: action.payload,
};
}
case types.SET_NEW_REQUEST_BODY: {
return {
...state,
newRequestBody: action.payload,
};
}
case types.SET_NEW_TEST_CONTENT: {
return {
...state,
newRequestFields: {
...state.newRequestFields,
testContent: action.payload,
},
};
}
case types.SET_NEW_REQUEST_COOKIES: {
return {
...state,
newRequestCookies: action.payload,
};
}
case types.SET_NEW_REQUEST_SSE: {
return {
...state,
newRequestSSE: { isSSE: action.payload },
};
}
case types.SET_CURRENT_TAB: {
return {
...state,
currentTab: action.payload,
};
}
case types.SET_INTROSPECTION_DATA: {
return {
...state,
introspectionData: action.payload,
};
}
case types.SAVE_CURRENT_RESPONSE_DATA: {
return {
...state,
currentResponse: action.payload,
};
}
// OPENAPI
case types.SET_NEW_REQUESTS_OPENAPI: {
return {
...state,
newRequestsOpenAPI: { ...action.payload },
};
}
case types.SET_OPENAPI_SERVERS_GLOBAL: {
// @ts-expect-error ts-migrate(2339) FIXME: Property 'openapiMetadata' does not exist on type ... Remove this comment to see the full error message
const openapiMetadata = { ...state.openapiMetadata };
// @ts-expect-error ts-migrate(2339) FIXME: Property 'openapiMetadata' does not exist on type ... Remove this comment to see the full error message
openapiMetadata.serverUrls = [...state.openapiMetadata.serverUrls].filter(
(_, i) => action.payload.includes(i)
);
return {
...state,
newRequestsOpenAPI: openapiMetadata,
};
}
case types.SET_NEW_OPENAPI_SERVERS: {
const { id, serverIds } = action.payload;
// @ts-expect-error ts-migrate(2339) FIXME: Property 'openapiReqArray' does not exist on type ... Remove this comment to see the full error message
const request = [...state.openapiReqArray]
.filter(({ request }) => request.id === id)
.pop();
// @ts-expect-error ts-migrate(2339) FIXME: Property 'openapiMetadata' does not exist on type ... Remove this comment to see the full error message
request.reqServers = [...state.openapiMetadata.serverUrls].filter(
(_, i) => serverIds.includes(i)
);
// @ts-expect-error ts-migrate(2339) FIXME: Property 'openapiReqArray' does not exist on type ... Remove this comment to see the full error message
const openapiReqArray = [...state.openapiReqArray].push({ request });
return {
...state,
newRequestsOpenAPI: openapiReqArray,
};
}
case types.SET_NEW_OPENAPI_PARAMETER: {
const { id, location, name, value } = action.payload;
// @ts-expect-error ts-migrate(2339) FIXME: Property 'openapiReqArray' does not exist on type ... Remove this comment to see the full error message
const request = [...state.openapiReqArray]
.filter(({ request }) => request.id === id)
.pop();
const urls = [...request.reqServers].map(
(url) => (url += request.endpoint)
);
switch (location) {
case 'path': {
urls.map((url) => url.replace(`{${name}}`, value));
request.urls = urls;
// @ts-expect-error ts-migrate(2339) FIXME: Property 'openapiReqArray' does not exist on type ... Remove this comment to see the full error message
const openapiReqArray = [...state.openapiReqArray].push({ request });
return {
...state,
newRequestsOpenAPI: openapiReqArray,
};
}
case 'query': {
urls.map((url) => {
if (url.slice(-1) !== '?') url += '?';
url += `${name}=${value}&`;
});
request.urls = urls;
// @ts-expect-error ts-migrate(2339) FIXME: Property 'openapiReqArray' does not exist on type ... Remove this comment to see the full error message
const openapiReqArray = [...state.openapiReqArray].push({ request });
return {
...state,
newRequestsOpenAPI: openapiReqArray,
};
}
case 'header': {
// @ts-expect-error ts-migrate(2304) FIXME: Cannot find name 'key'.
if (['Content-Type', 'Authorization', 'Accepts'].includes(key)) break;
request.headers.push({ name: value });
// @ts-expect-error ts-migrate(2339) FIXME: Property 'openapiReqArray' does not exist on type ... Remove this comment to see the full error message
const openapiReqArray = [...state.openapiReqArray].push({ request });
return {
...state,
newRequestsOpenAPI: openapiReqArray,
};
}
case 'cookie': {
request.cookies = value;
// @ts-expect-error ts-migrate(2339) FIXME: Property 'openapiReqArray' does not exist on type ... Remove this comment to see the full error message
const openapiReqArray: [Record<string, unknown>] = [...state.openapiReqArray].push({ request });
return {
...state,
newRequestsOpenAPI: openapiReqArray,
};
}
default: {
return state;
}
}
break;
}
case types.SET_NEW_OPENAPI_REQUEST_BODY: {
const { id, mediaType, requestBody } = action.payload;
// @ts-expect-error ts-migrate(2339) FIXME: Property 'openapiReqArray' does not exist on type ... Remove this comment to see the full error message
const request: Record<string, unknown> = [...state.openapiReqArray]
.filter(({ request }) => request.id === id)
.pop();
const { method } = request;
if (
!['get', 'delete', 'head'].includes(method) &&
requestBody !== undefined
) {
request.body = requestBody;
request.rawType = mediaType;
}
// @ts-expect-error ts-migrate(2339) FIXME: Property 'openapiReqArray' does not exist on type ... Remove this comment to see the full error message
const openapiReqArray = [...state.openapiReqArray].push({ request });
return {
...state,
newRequestsOpenAPI: openapiReqArray,
};
}
default:
return state;
}
return state;
};
export default businessReducer; | the_stack |
* AccumulationChart Selection src file
*/
import { extend, isNullOrUndefined } from '@syncfusion/ej2-base';
import { Rect, SvgRenderer, CanvasRenderer } from '@syncfusion/ej2-svg-base';
import { indexFinder } from '../../common/utils/helper';
import { AccumulationChart } from '../accumulation';
import { AccumulationSeries, pointByIndex, AccPoints } from '../model/acc-base';
import { AccumulationSeriesModel } from '../model/acc-base-model';
import { Indexes, Index } from '../../common/model/base';
import { BaseSelection } from '../../common/user-interaction/selection';
import { AccumulationTooltip } from './tooltip';
/**
* `AccumulationSelection` module handles the selection for accumulation chart.
*/
export class AccumulationSelection extends BaseSelection {
private renderer: SvgRenderer | CanvasRenderer;
/** @private */
public rectPoints: Rect;
public selectedDataIndexes: Indexes[];
private series: AccumulationSeries[];
constructor(accumulation: AccumulationChart) {
super(accumulation);
this.renderer = accumulation.renderer;
}
/**
* To initialize the private variables
*/
private initPrivateVariables(accumulation: AccumulationChart): void {
this.styleId = accumulation.element.id + '_ej2_chart_selection';
this.unselected = accumulation.element.id + '_ej2_deselected';
this.selectedDataIndexes = [];
this.rectPoints = null;
}
/**
* Invoke selection for rendered chart.
*
* @param {AccumulationChart} accumulation Define the chart to invoke the selection.
* @returns {void}
*/
public invokeSelection(accumulation: AccumulationChart): void {
this.initPrivateVariables(accumulation);
this.series = <AccumulationSeries[]>extend({}, accumulation.visibleSeries, null, true);
this.seriesStyles();
this.selectDataIndex(this.concatIndexes(accumulation.selectedDataIndexes, this.selectedDataIndexes), accumulation);
}
/**
* To get series selection style by series.
*/
private generateStyle(series: AccumulationSeriesModel): string {
return (series.selectionStyle || this.styleId + '_series_' + (<AccumulationSeries>series).index);
}
/**
* To get elements by index, series
*/
private findElements(accumulation: AccumulationChart, series: AccumulationSeriesModel, index: Index): Element[] {
return [this.getElementByIndex(index)];
}
/**
* To get series point element by index
*/
private getElementByIndex(index: Index): Element {
const elementId: string = this.control.element.id + '_Series_' + index.series + '_Point_' + index.point;
return document.getElementById(elementId);
}
/**
* To calculate selected elements on mouse click or touch
*
* @private
*/
public calculateSelectedElements(accumulation: AccumulationChart, event: Event): void {
if ((<HTMLElement>event.target).id.indexOf(accumulation.element.id + '_') === -1) {
return;
}
if ((<HTMLElement>event.target).id.indexOf('_Series_') > -1 || (<HTMLElement>event.target).id.indexOf('_datalabel_') > -1) {
this.performSelection(indexFinder((<HTMLElement>event.target).id), accumulation, <Element>event.target);
}
}
/**
* To perform the selection process based on index and element.
*/
private performSelection(index: Index, accumulation: AccumulationChart, element?: Element): void {
element = element.id.indexOf('datalabel') > -1 ?
<Element>accumulation.getSeriesElement().childNodes[index.series].childNodes[index.point]
: element;
switch (accumulation.selectionMode) {
case 'Point':
if (!isNaN(index.point)) {
this.selection(accumulation, index, [element]);
this.blurEffect(accumulation.element.id, accumulation.visibleSeries);
}
break;
}
}
/**
* To select the element by index. Adding or removing selection style class name.
*/
private selection(accumulation: AccumulationChart, index: Index, selectedElements: Element[]): void {
if (!accumulation.isMultiSelect) {
this.removeMultiSelectEelments(accumulation, this.selectedDataIndexes, index, accumulation.series);
}
const className: string = selectedElements[0] && (selectedElements[0].getAttribute('class') || '');
if (selectedElements[0] && className.indexOf(this.getSelectionClass(selectedElements[0].id)) > -1) {
this.removeStyles(selectedElements, index);
this.addOrRemoveIndex(this.selectedDataIndexes, index);
if (accumulation.enableBorderOnMouseMove) {
const borderElement: Element = document.getElementById(selectedElements[0].id.split('_')[0] + 'PointHover_Border');
if (!isNullOrUndefined(borderElement)) {
this.removeSvgClass(borderElement, borderElement.getAttribute('class'));
}
}
} else {
this.applyStyles(selectedElements, index);
if (accumulation.enableBorderOnMouseMove) {
const borderElement: Element = document.getElementById(selectedElements[0].id.split('_')[0] + 'PointHover_Border');
if (!isNullOrUndefined(borderElement)) {
this.addSvgClass(borderElement, selectedElements[0].getAttribute('class'));
}
}
this.addOrRemoveIndex(this.selectedDataIndexes, index, true);
}
}
/**
* To redraw the selection process on accumulation chart refresh.
*
* @private
*/
public redrawSelection(accumulation: AccumulationChart): void {
const selectedDataIndexes: Indexes[] = <Indexes[]>extend([], this.selectedDataIndexes, null, true);
this.removeSelectedElements(accumulation, this.selectedDataIndexes);
this.blurEffect(accumulation.element.id, accumulation.visibleSeries);
this.selectDataIndex(selectedDataIndexes, accumulation);
}
/**
* To remove the selected elements style classes by indexes.
*/
private removeSelectedElements(accumulation: AccumulationChart, indexes: Index[]): void {
for (const index of indexes) {
this.removeStyles([this.getElementByIndex(index)], index);
}
}
/**
* To perform the selection for legend elements.
*
* @private
*/
public legendSelection(accumulation: AccumulationChart, series: number, pointIndex: number): void {
const seriesElements: Element = <Element>accumulation.getSeriesElement().childNodes[series].childNodes[pointIndex];
this.selection(accumulation, new Index(series, pointIndex), [seriesElements]);
this.blurEffect(accumulation.element.id, accumulation.visibleSeries);
}
/**
* To select the element by selected data indexes.
*/
private selectDataIndex(indexes: Index[], accumulation: AccumulationChart): void {
let element: Element;
for (const index of indexes) {
element = this.getElementByIndex(index);
if (element) {
this.performSelection(index, accumulation, element);
}
}
}
/**
* To remove the selection styles for multi selection process.
*/
private removeMultiSelectEelments(accumulation: AccumulationChart, index: Index[], currentIndex: Index,
seriesCollection: AccumulationSeriesModel[]): void {
let series: AccumulationSeriesModel;
for (let i: number = 0; i < index.length; i++) {
series = seriesCollection[index[i].series];
if (!this.checkEquals(index[i], currentIndex)) {
this.removeStyles(this.findElements(accumulation, series, index[i]), index[i]);
index.splice(i, 1);
i--;
}
}
}
/**
* To apply the opacity effect for accumulation chart series elements.
*/
private blurEffect(pieId: string, visibleSeries: AccumulationSeries[]): void {
const visibility: boolean = this.checkPointVisibility(this.selectedDataIndexes); // legend click scenario
for (const series of visibleSeries) {
if (series.visible) {
this.checkSelectionElements(document.getElementById(pieId + '_SeriesCollection'),
this.generateStyle(series), visibility);
}
}
}
/**
* To check selection elements by style class name.
*/
private checkSelectionElements(element: Element, className: string, visibility: boolean): void {
const children: NodeList = element.childNodes[0].childNodes;
let legendShape: Element;
let elementClass: string;
let parentClass: string;
for (let i: number = 0; i < children.length; i++) {
elementClass = (children[i] as HTMLElement).getAttribute('class') || '';
parentClass = (<Element>children[i].parentNode).getAttribute('class') || '';
if (elementClass.indexOf(className) === -1 && parentClass.indexOf(className) === -1 && visibility) {
this.addSvgClass(children[i] as HTMLElement, this.unselected);
} else {
this.removeSvgClass(children[i] as HTMLElement, this.unselected);
}
if ((this.control as AccumulationChart).accumulationLegendModule && this.control.legendSettings.visible) {
legendShape = document.getElementById(this.control.element.id + '_chart_legend_shape_' + i);
if (legendShape) {
if (elementClass.indexOf(className) === -1 && parentClass.indexOf(className) === -1 && visibility) {
this.addSvgClass(legendShape, this.unselected);
} else {
this.removeSvgClass(legendShape, this.unselected);
}
}
}
}
}
/**
* To apply selection style for elements.
*/
private applyStyles(elements: Element[], index: Index): void {
const accumulationTooltip: AccumulationTooltip = (this.control as AccumulationChart).accumulationTooltipModule;
for (const element of elements) {
let legendShape: Element;
if (element) {
if ((this.control as AccumulationChart).accumulationLegendModule && this.control.legendSettings.visible) {
legendShape = document.getElementById(this.control.element.id + '_chart_legend_shape_' + index.point);
this.removeSvgClass(legendShape, this.unselected);
this.addSvgClass(legendShape, this.getSelectionClass(legendShape.id));
}
this.removeSvgClass(<Element>element.parentNode, this.unselected);
this.removeSvgClass(element, this.unselected);
const opacity: number = accumulationTooltip && (accumulationTooltip.previousPoints.length > 0 &&
accumulationTooltip.previousPoints[0].point.index !== index.point) ?
accumulationTooltip.svgTooltip.opacity : this.series[index.series].opacity;
element.setAttribute('opacity', opacity.toString());
this.addSvgClass(element, this.getSelectionClass(element.id));
}
}
}
/**
* To get selection style class name by id
*/
private getSelectionClass(id: string): string {
return this.generateStyle((this.control as AccumulationChart).series[indexFinder(id).series]);
}
/**
* To remove selection style for elements.
*/
private removeStyles(elements: Element[], index: Index): void {
const accumulationTooltip: AccumulationTooltip = (this.control as AccumulationChart).accumulationTooltipModule;
let legendShape: Element;
for (const element of elements) {
if (element) {
if ((this.control as AccumulationChart).accumulationLegendModule && this.control.legendSettings.visible) {
legendShape = document.getElementById(this.control.element.id + '_chart_legend_shape_' + index.point);
this.removeSvgClass(legendShape, this.getSelectionClass(legendShape.id));
}
const opacity: number = accumulationTooltip && accumulationTooltip.previousPoints.length > 0
&& (accumulationTooltip.previousPoints[0].point.index === index.point) ?
accumulationTooltip.svgTooltip.opacity : this.series[index.series].opacity;
element.setAttribute('opacity', opacity.toString());
this.removeSvgClass(element, this.getSelectionClass(element.id));
}
}
}
/**
* To apply or remove selected elements index.
*/
private addOrRemoveIndex(indexes: Index[], index: Index, add?: boolean): void {
for (let i: number = 0; i < indexes.length; i++) {
if (this.checkEquals(indexes[i], index)) {
indexes.splice(i, 1);
i--;
}
}
if (add) { indexes.push(index); }
}
/**
* To check two index, point and series are equal
*/
private checkEquals(first: Index, second: Index): boolean {
return ((first.point === second.point) && (first.series === second.series));
}
/**
* To check selected points are visibility
*/
private checkPointVisibility(selectedDataIndexes: Indexes[]): boolean {
let visible: boolean = false;
for (const data of selectedDataIndexes) {
if (pointByIndex(data.point, <AccPoints[]>this.control.visibleSeries[0].points).visible) {
visible = true;
break;
}
}
return visible;
}
/**
* Get module name.
*/
public getModuleName(): string {
return 'AccumulationSelection';
}
/**
* To destroy the selection.
*
* @returns {void}
* @private
*/
public destroy(): void {
// Destroy method performed here
}
} | the_stack |
import { AfterViewInit, Component, OnChanges, OnDestroy, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { Course } from 'app/entities/course.model';
import { CourseManagementService } from 'app/course/manage/course-management.service';
import { ActivatedRoute } from '@angular/router';
import { Subject, Subscription } from 'rxjs';
import { TranslateService } from '@ngx-translate/core';
import dayjs from 'dayjs/esm';
import { AccountService } from 'app/core/auth/account.service';
import { flatten, maxBy, sum } from 'lodash-es';
import { GuidedTourService } from 'app/guided-tour/guided-tour.service';
import { courseExerciseOverviewTour } from 'app/guided-tour/tours/course-exercise-overview-tour';
import { isOrion } from 'app/shared/orion/orion';
import { ProgrammingSubmissionService } from 'app/exercises/programming/participate/programming-submission.service';
import { LocalStorageService } from 'ngx-webstorage';
import { CourseScoreCalculationService } from 'app/overview/course-score-calculation.service';
import { Exercise, ExerciseType, IncludedInOverallScore } from 'app/entities/exercise.model';
import { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';
import { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';
import { getExerciseDueDate, hasExerciseDueDatePassed } from 'app/exercises/shared/exercise/exercise.utils';
import { faAngleDown, faAngleUp, faFilter, faPlayCircle, faSortNumericDown, faSortNumericUp } from '@fortawesome/free-solid-svg-icons';
import { User } from 'app/core/user/user.model';
import { StudentParticipation } from 'app/entities/participation/student-participation.model';
import { BarControlConfiguration, BarControlConfigurationProvider } from 'app/overview/course-overview.component';
export enum ExerciseFilter {
OVERDUE = 'OVERDUE',
NEEDS_WORK = 'NEEDS_WORK',
UNRELEASED = 'UNRELEASED',
OPTIONAL = 'OPTIONAL',
}
export enum ExerciseSortingOrder {
ASC = 1,
DESC = -1,
}
enum SortFilterStorageKey {
FILTER = 'artemis.course.exercises.filter',
ORDER = 'artemis.course.exercises.order',
ATTRIBUTE = 'artemis.course.exercises.attribute',
}
export enum SortingAttribute {
DUE_DATE = 0,
RELEASE_DATE = 1,
}
interface ExerciseWithDueDate {
exercise: Exercise;
dueDate?: dayjs.Dayjs;
}
@Component({
selector: 'jhi-course-exercises',
templateUrl: './course-exercises.component.html',
styleUrls: ['../course-overview.scss'],
})
export class CourseExercisesComponent implements OnInit, OnChanges, OnDestroy, AfterViewInit, BarControlConfigurationProvider {
private courseId: number;
private paramSubscription: Subscription;
private courseUpdatesSubscription: Subscription;
private translateSubscription: Subscription;
private currentUser?: User;
public course?: Course;
public weeklyIndexKeys: string[];
public weeklyExercisesGrouped: object;
public upcomingExercises: ExerciseWithDueDate[] = [];
public exerciseCountMap: Map<string, number>;
readonly ASC = ExerciseSortingOrder.ASC;
readonly DESC = ExerciseSortingOrder.DESC;
readonly DUE_DATE = SortingAttribute.DUE_DATE;
readonly RELEASE_DATE = SortingAttribute.RELEASE_DATE;
readonly filterType = ExerciseFilter;
sortingOrder: ExerciseSortingOrder;
activeFilters: Set<ExerciseFilter>;
numberOfExercises: number;
exerciseForGuidedTour?: Exercise;
nextRelevantExercise?: ExerciseWithDueDate;
sortingAttribute: SortingAttribute;
// Icons
faPlayCircle = faPlayCircle;
faFilter = faFilter;
faAngleUp = faAngleUp;
faAngleDown = faAngleDown;
faSortNumericUp = faSortNumericUp;
faSortNumericDown = faSortNumericDown;
// The extracted controls template from our template to be rendered in the top bar of "CourseOverviewComponent"
@ViewChild('controls', { static: false }) private controls: TemplateRef<any>;
// Provides the control configuration to be read and used by "CourseOverviewComponent"
public readonly controlConfiguration: BarControlConfiguration = {
subject: new Subject<TemplateRef<any>>(),
useIndentation: true,
};
constructor(
private courseService: CourseManagementService,
private courseCalculationService: CourseScoreCalculationService,
private courseServer: CourseManagementService,
private translateService: TranslateService,
private exerciseService: ExerciseService,
private accountService: AccountService,
private route: ActivatedRoute,
private guidedTourService: GuidedTourService,
private programmingSubmissionService: ProgrammingSubmissionService,
private localStorage: LocalStorageService,
) {}
ngOnInit() {
this.exerciseCountMap = new Map<string, number>();
this.numberOfExercises = 0;
const filters = this.localStorage.retrieve(SortFilterStorageKey.FILTER);
const filtersInStorage = filters
? filters
.split(',')
.map((filter: string) => ExerciseFilter[filter])
.filter(Boolean)
: [];
this.activeFilters = new Set(filtersInStorage);
this.loadOrderAndAttributeForSorting();
this.paramSubscription = this.route.parent!.params.subscribe((params) => {
this.courseId = parseInt(params['courseId'], 10);
});
this.course = this.courseCalculationService.getCourse(this.courseId);
this.onCourseLoad();
this.courseUpdatesSubscription = this.courseService.getCourseUpdates(this.courseId).subscribe((course: Course) => {
this.courseCalculationService.updateCourse(course);
this.course = this.courseCalculationService.getCourse(this.courseId);
this.onCourseLoad();
});
this.translateSubscription = this.translateService.onLangChange.subscribe(() => {
this.applyFiltersAndOrder();
});
this.exerciseForGuidedTour = this.guidedTourService.enableTourForCourseExerciseComponent(this.course, courseExerciseOverviewTour, true);
this.accountService.identity().then((user) => {
this.currentUser = user;
this.updateNextRelevantExercise();
});
}
ngAfterViewInit(): void {
// Send our controls template to parent so it will be rendered in the top bar
if (this.controls) {
this.controlConfiguration.subject!.next(this.controls);
}
}
setSortingAttribute(attribute: SortingAttribute) {
this.sortingAttribute = attribute;
this.localStorage.store(SortFilterStorageKey.ATTRIBUTE, this.sortingAttribute.toString());
this.applyFiltersAndOrder();
}
ngOnChanges() {
this.updateNextRelevantExercise();
}
ngOnDestroy(): void {
this.translateSubscription?.unsubscribe();
this.courseUpdatesSubscription?.unsubscribe();
this.paramSubscription?.unsubscribe();
}
private onCourseLoad() {
this.programmingSubmissionService.initializeCacheForStudent(this.course!.exercises, true);
this.applyFiltersAndOrder();
}
private calcNumberOfExercises() {
this.numberOfExercises = sum(Array.from(this.exerciseCountMap.values()));
}
private updateNextRelevantExercise() {
const nextExercise = this.exerciseService.getNextExerciseForHours(this.course?.exercises?.filter(this.fulfillsCurrentFilter.bind(this)), 12, this.currentUser);
if (nextExercise) {
const dueDate = CourseExercisesComponent.exerciseDueDate(nextExercise);
this.nextRelevantExercise = {
exercise: nextExercise,
dueDate,
};
} else {
this.nextRelevantExercise = undefined;
}
}
/**
* Reorders all displayed exercises
*/
flipOrder() {
this.sortingOrder = this.sortingOrder === this.ASC ? this.DESC : this.ASC;
this.localStorage.store(SortFilterStorageKey.ORDER, this.sortingOrder.toString());
this.applyFiltersAndOrder();
}
/**
* Filters all displayed exercises by applying the selected activeFilters
* @param filters The filters which should be applied
*/
toggleFilters(filters: ExerciseFilter[]) {
filters.forEach((filter) => (this.activeFilters.has(filter) ? this.activeFilters.delete(filter) : this.activeFilters.add(filter)));
this.localStorage.store(SortFilterStorageKey.FILTER, Array.from(this.activeFilters).join(','));
this.applyFiltersAndOrder();
this.updateNextRelevantExercise();
}
/**
* Checks whether an exercise is visible to students or not
* @param exercise The exercise which should be checked
*/
isVisibleToStudents(exercise: Exercise): boolean | undefined {
return !this.activeFilters.has(ExerciseFilter.UNRELEASED) || (exercise as QuizExercise)?.visibleToStudents;
}
/**
* Checks if the given exercise still needs work, i.e. wasn't even started yet or is not graded with 100%
* @param exercise The exercise which should get checked
*/
private needsWork(exercise: Exercise): boolean {
const latestResult = maxBy(flatten(exercise.studentParticipations?.map((participation) => participation.results)), 'completionDate');
return !latestResult || !latestResult.score || latestResult.score < 100;
}
/**
* Applies all selected activeFilters and orders and groups the user's exercises
*/
private applyFiltersAndOrder() {
const filtered = this.course?.exercises?.filter(this.fulfillsCurrentFilter.bind(this));
this.groupExercises(filtered);
}
/**
* Check if the given exercise fulfills the currently selected filters
* @param exercise the exercise to check
* @return true if the given exercise fulfills the currently selected filters; false otherwise
* @private
*/
private fulfillsCurrentFilter(exercise: Exercise): boolean {
const needsWorkFilterActive = this.activeFilters.has(ExerciseFilter.NEEDS_WORK);
const overdueFilterActive = this.activeFilters.has(ExerciseFilter.OVERDUE);
const unreleasedFilterActive = this.activeFilters.has(ExerciseFilter.UNRELEASED);
const optionalFilterActive = this.activeFilters.has(ExerciseFilter.OPTIONAL);
const participation = CourseExercisesComponent.studentParticipation(exercise);
return !!(
(!needsWorkFilterActive || this.needsWork(exercise)) &&
(!exercise.dueDate || !overdueFilterActive || !hasExerciseDueDatePassed(exercise, participation)) &&
(!exercise.releaseDate || !unreleasedFilterActive || (exercise as QuizExercise)?.visibleToStudents) &&
(!optionalFilterActive || exercise.includedInOverallScore !== IncludedInOverallScore.NOT_INCLUDED) &&
(!isOrion || exercise.type === ExerciseType.PROGRAMMING)
);
}
private getSortingAttributeFromExercise(): (exercise: Exercise) => dayjs.Dayjs | undefined {
if (this.sortingAttribute === this.DUE_DATE) {
return CourseExercisesComponent.exerciseDueDate;
} else {
return (exercise) => exercise.releaseDate;
}
}
private loadOrderAndAttributeForSorting() {
const orderInStorage = this.localStorage.retrieve(SortFilterStorageKey.ORDER);
const parsedOrderInStorage = Object.keys(ExerciseSortingOrder).find((exerciseOrder) => exerciseOrder === orderInStorage);
this.sortingOrder = parsedOrderInStorage ? (+parsedOrderInStorage as ExerciseSortingOrder) : ExerciseSortingOrder.ASC;
const attributeInStorage = this.localStorage.retrieve(SortFilterStorageKey.ATTRIBUTE);
const parsedAttributeInStorage = Object.keys(SortingAttribute).find((exerciseOrder) => exerciseOrder === attributeInStorage);
this.sortingAttribute = parsedAttributeInStorage ? (+parsedAttributeInStorage as SortingAttribute) : SortingAttribute.DUE_DATE;
}
private increaseExerciseCounter(exercise: Exercise) {
if (!this.exerciseCountMap.has(exercise.type!)) {
this.exerciseCountMap.set(exercise.type!, 1);
} else {
let exerciseCount = this.exerciseCountMap.get(exercise.type!)!;
this.exerciseCountMap.set(exercise.type!, ++exerciseCount);
}
}
private updateUpcomingExercises(upcomingExercises: Exercise[]) {
const sortedExercises = (this.sortExercises(CourseExercisesComponent.exerciseDueDate, upcomingExercises, ExerciseSortingOrder.ASC) || []).map((exercise) => {
return { exercise, dueDate: CourseExercisesComponent.exerciseDueDate(exercise) };
});
if (upcomingExercises.length <= 5) {
this.upcomingExercises = sortedExercises;
} else {
// sort after selected date and take the first 5 elements
this.upcomingExercises = sortedExercises.slice(0, 5);
}
}
private static exerciseDueDate(exercise: Exercise): dayjs.Dayjs | undefined {
return getExerciseDueDate(exercise, CourseExercisesComponent.studentParticipation(exercise));
}
private static studentParticipation(exercise: Exercise): StudentParticipation | undefined {
return exercise.studentParticipations && exercise.studentParticipations.length > 0 ? exercise.studentParticipations[0] : undefined;
}
private groupExercises(exercises?: Exercise[]) {
// set all values to 0
this.exerciseCountMap = new Map<string, number>();
this.weeklyExercisesGrouped = {};
this.weeklyIndexKeys = [];
const groupedExercises = {};
const indexKeys: string[] = [];
const sortedExercises = this.sortExercises(this.getSortingAttributeFromExercise(), exercises) || [];
const notAssociatedExercises: Exercise[] = [];
const upcomingExercises: Exercise[] = [];
sortedExercises.forEach((exercise) => {
const dateValue = this.getSortingAttributeFromExercise()(exercise);
this.increaseExerciseCounter(exercise);
if (!dateValue) {
notAssociatedExercises.push(exercise);
return;
}
const dateIndex = dateValue ? dayjs(dateValue).startOf('week').format('YYYY-MM-DD') : 'NoDate';
if (!groupedExercises[dateIndex]) {
indexKeys.push(dateIndex);
groupedExercises[dateIndex] = {
start: dayjs(dateValue).startOf('week'),
end: dayjs(dateValue).endOf('week'),
isCollapsed: dateValue.isBefore(dayjs(), 'week'),
isCurrentWeek: dateValue.isSame(dayjs(), 'week'),
exercises: [],
};
}
groupedExercises[dateIndex].exercises.push(exercise);
if (exercise.dueDate && !dayjs().isAfter(dateValue, 'day')) {
upcomingExercises.push(exercise);
}
});
this.updateUpcomingExercises(upcomingExercises);
if (notAssociatedExercises.length > 0) {
this.weeklyExercisesGrouped = {
...groupedExercises,
noDate: {
label: this.translateService.instant('artemisApp.courseOverview.exerciseList.noExerciseDate'),
isCollapsed: false,
isCurrentWeek: false,
exercises: notAssociatedExercises,
},
};
this.weeklyIndexKeys = [...indexKeys, 'noDate'];
} else {
this.weeklyExercisesGrouped = groupedExercises;
this.weeklyIndexKeys = indexKeys;
}
this.calcNumberOfExercises();
}
private sortExercises(byAttribute: (exercise: Exercise) => dayjs.Dayjs | undefined, exercises?: Exercise[], sortOrder?: ExerciseSortingOrder) {
const sortingOrder = sortOrder ?? this.sortingOrder;
return exercises?.sort((a, b) => {
const sortingAttributeA = byAttribute(a);
const sortingAttributeB = byAttribute(b);
const aValue = sortingAttributeA ? sortingAttributeA.second(0).millisecond(0).valueOf() : dayjs().valueOf();
const bValue = sortingAttributeB ? sortingAttributeB.second(0).millisecond(0).valueOf() : dayjs().valueOf();
const titleSortValue = a.title && b.title ? a.title.localeCompare(b.title) : 0;
return sortingOrder.valueOf() * (aValue - bValue === 0 ? titleSortValue : aValue - bValue);
});
}
} | the_stack |
import execa from 'execa';
import { tmpdir } from 'os';
import assert from 'assert';
import { basename, join } from 'path';
import { mkdirp, remove, readFile, stat } from 'fs-extra';
import {
funCacheDir,
initializeRuntime,
cleanCacheDir,
createFunction,
ValidationError
} from '../src';
import { generateNodeTarballUrl, installNode } from '../src/install-node';
import { generatePythonTarballUrl, installPython } from '../src/install-python';
import { LambdaError } from '../src/errors';
const isWin = process.platform === 'win32';
function assertProcessExitedError(err: Error): void {
assert(err instanceof LambdaError);
assert.equal(err.name, 'LambdaError');
assert(
/RequestId: [a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12} Process exited before completing request/.test(
err.message
)
);
}
jest.setTimeout(60_000);
function testInvoke(
fnPromise: () => Promise<any>,
test: (...args: any[]) => Promise<unknown>
) {
return async function() {
const fn = await fnPromise();
try {
await test(fn);
} finally {
await fn.destroy();
}
};
}
it('funCacheDir', () => {
expect(typeof funCacheDir).toBe('string');
});
it('LambdaError', () => {
const err = new LambdaError({
errorType: 'InitError',
errorMessage: 'I crashed!',
stackTrace: [
' at Object.<anonymous> (/Code/zeit/fun/test/functions/nodejs-init-error/handler.js:2:7)',
' at Module._compile (module.js:652:30)',
' at Object.Module._extensions..js (module.js:663:10)',
' at Module.load (module.js:565:32)',
' at tryModuleLoad (module.js:505:12)',
' at Function.Module._load (module.js:497:3)',
' at Module.require (module.js:596:17)',
' at require (internal/module.js:11:18)',
' at getHandler (/Library/Caches/co.zeit.fun/runtimes/nodejs/bootstrap.js:151:15)',
' at /Library/Caches/co.zeit.fun/runtimes/nodejs/bootstrap.js:37:23'
]
});
expect(err.name).toBe('InitError');
expect(err.message).toBe('I crashed!');
expect(err.stack).toContain('nodejs-init-error/handler.js');
});
// `install-node.ts` tests
it('install_node_tarball_url_darwin', () => {
expect(generateNodeTarballUrl('8.10.0', 'darwin', 'x64')).toBe(
'https://nodejs.org/dist/v8.10.0/node-v8.10.0-darwin-x64.tar.gz'
);
});
it('install_node_tarball_url_windows', () => {
expect(generateNodeTarballUrl('8.10.0', 'win32', 'x64')).toBe(
'https://nodejs.org/dist/v8.10.0/node-v8.10.0-win-x64.zip'
);
});
it('install_node', async () => {
const version = 'v10.0.0';
const dest = join(
tmpdir(),
`install-node-${Math.random()
.toString(16)
.substring(2)}`
);
await mkdirp(dest);
try {
await installNode(dest, version);
const res = await execa(join(dest, 'bin/node'), [
'-p',
'process.version'
]);
expect(res.stdout.trim()).toBe(version);
} finally {
// Clean up
try {
await remove(dest);
} catch (err) {
// On Windows EPERM can happen due to anti-virus software like Windows Defender.
// There's nothing that we can do about it so don't fail the test case when it happens.
if (err.code !== 'EPERM') {
throw err;
}
}
}
});
// `install-python.ts` tests
it('install_python_tarball_url', () => {
expect(generatePythonTarballUrl('2.7.12', 'darwin', 'x64')).toBe(
'https://python-binaries.zeit.sh/python-2.7.12-darwin-x64.tar.gz'
);
});
it('install_python', async () => {
const version = '3.6.8';
const dest = join(
tmpdir(),
`install-python-${Math.random()
.toString(16)
.substring(2)}`
);
await mkdirp(dest);
try {
await installPython(dest, version);
const res = await execa(join(dest, 'bin/python'), [
'-c',
'import platform; print(platform.python_version())'
]);
expect(res.stdout.trim()).toBe(version);
} finally {
// Clean up
//await remove(dest);
}
});
// Validation
it('lambda_properties', async () => {
const fn = await createFunction({
Code: {
Directory: __dirname + '/functions/nodejs-echo'
},
Handler: 'handler.handler',
Runtime: 'nodejs',
Environment: {
Variables: {
HELLO: 'world'
}
}
});
expect(fn.version).toBe('$LATEST');
//assert.equal(fn.functionName, 'nodejs-echo');
});
it('reserved_env', async () => {
let err;
try {
await createFunction({
Code: {
Directory: __dirname + '/functions/nodejs-echo'
},
Handler: 'handler.handler',
Runtime: 'nodejs',
Environment: {
Variables: {
AWS_REGION: 'foo',
TZ: 'US/Pacific'
}
}
});
} catch (_err) {
err = _err;
}
assert(err);
assert(err instanceof ValidationError);
assert.equal(err.name, 'ValidationError');
assert.deepEqual(err.reserved, ['AWS_REGION', 'TZ']);
assert.equal(
err.toString(),
'ValidationError: The following environment variables can not be configured: AWS_REGION, TZ'
);
});
// Initialization
it('initialize_runtime_with_string', async () => {
const runtime = await initializeRuntime('nodejs8.10');
assert.equal(typeof runtime.cacheDir, 'string');
const nodeName = isWin ? 'node.exe' : 'node';
const nodeStat = await stat(join(runtime.cacheDir, 'bin', nodeName));
assert(nodeStat.isFile());
});
it('initialize_runtime_with_invalid_name', async () => {
let err: Error;
try {
await initializeRuntime('node8.10');
} catch (_err) {
err = _err;
}
assert(err);
assert.equal('Could not find runtime with name "node8.10"', err.message);
});
// Invocation
it(
'nodejs_event',
testInvoke(
() =>
createFunction({
Code: {
Directory: __dirname + '/functions/nodejs-echo'
},
Handler: 'handler.handler',
Runtime: 'nodejs'
}),
async fn => {
const res = await fn.invoke({
Payload: JSON.stringify({ hello: 'world' })
});
assert.equal(res.StatusCode, 200);
assert.equal(res.ExecutedVersion, '$LATEST');
assert.equal(typeof res.Payload, 'string');
const payload = JSON.parse(String(res.Payload));
assert.deepEqual(payload.event, { hello: 'world' });
}
)
);
it(
'nodejs_no_payload',
testInvoke(
() =>
createFunction({
Code: {
Directory: __dirname + '/functions/nodejs-echo'
},
Handler: 'handler.handler',
Runtime: 'nodejs'
}),
async fn => {
const res = await fn.invoke();
assert.equal(typeof res.Payload, 'string');
const payload = JSON.parse(String(res.Payload));
assert.deepEqual(payload.event, {});
}
)
);
it(
'nodejs_context',
testInvoke(
() =>
createFunction({
Code: {
Directory: __dirname + '/functions/nodejs-echo'
},
Handler: 'handler.handler',
Runtime: 'nodejs'
}),
async fn => {
const res = await fn.invoke();
const { context } = JSON.parse(String(res.Payload));
assert.equal(context.logGroupName, 'aws/lambda/nodejs-echo');
assert.equal(context.functionName, 'nodejs-echo');
assert.equal(context.memoryLimitInMB, '128');
assert.equal(context.functionVersion, '$LATEST');
}
)
);
it(
'env_vars',
testInvoke(
() =>
createFunction({
Code: {
Directory: __dirname + '/functions/nodejs-env'
},
Handler: 'index.env',
Runtime: 'nodejs',
AccessKeyId: 'TestAccessKeyId',
SecretAccessKey: 'TestSecretAccessKey'
}),
async fn => {
const res = await fn.invoke();
assert.equal(typeof res.Payload, 'string');
const env = JSON.parse(String(res.Payload));
assert(env.LAMBDA_TASK_ROOT.length > 0);
assert(env.LAMBDA_RUNTIME_DIR.length > 0);
assert.equal(env.TZ, ':UTC');
assert.equal(env.LANG, 'en_US.UTF-8');
assert.equal(env._HANDLER, 'index.env');
assert.equal(env.AWS_LAMBDA_FUNCTION_VERSION, '$LATEST');
assert.equal(env.AWS_EXECUTION_ENV, 'AWS_Lambda_nodejs');
assert.equal(env.AWS_LAMBDA_FUNCTION_NAME, 'nodejs-env');
assert.equal(env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE, '128');
assert.equal(env.AWS_ACCESS_KEY_ID, 'TestAccessKeyId');
assert.equal(env.AWS_SECRET_ACCESS_KEY, 'TestSecretAccessKey');
}
)
);
it(
'double_invoke_serial',
testInvoke(
() =>
createFunction({
Code: {
Directory: __dirname + '/functions/nodejs-pid'
},
Handler: 'index.pid',
Runtime: 'nodejs'
}),
async fn => {
let res;
// Invoke once, will fire up a new lambda process
res = await fn.invoke();
assert.equal(typeof res.Payload, 'string');
const pid = JSON.parse(String(res.Payload));
assert.equal(typeof pid, 'number');
assert.notEqual(pid, process.pid);
// Invoke a second time, the same lambda process will be used
res = await fn.invoke();
assert.equal(typeof res.Payload, 'string');
const pid2 = JSON.parse(String(res.Payload));
assert.equal(pid, pid2);
}
)
);
it(
'double_invoke_parallel',
testInvoke(
() =>
createFunction({
Code: {
Directory: __dirname + '/functions/nodejs-pid'
},
Handler: 'index.pid',
Runtime: 'nodejs'
}),
async fn => {
const [res1, res2] = await Promise.all([fn.invoke(), fn.invoke()]);
const pid1 = JSON.parse(String(res1.Payload));
const pid2 = JSON.parse(String(res2.Payload));
assert.notEqual(pid1, process.pid);
assert.notEqual(pid2, process.pid);
// This assert always passed on my MacBook 12", but is flaky on
// CircleCI's containers due to the second worker process not yet
// being in an initialized state.
// assert.notEqual(pid1, pid2);
}
)
);
test(
'lambda_invoke',
testInvoke(
() =>
createFunction({
Code: {
Directory: __dirname + '/functions/nodejs-echo'
},
Handler: 'handler.handler',
Runtime: 'nodejs'
}),
async fn => {
const payload = await fn({ hello: 'world' });
assert.deepEqual(payload.event, { hello: 'world' });
}
)
);
it(
'lambda_callback_with_return',
testInvoke(
() =>
createFunction({
Code: {
Directory:
__dirname + '/functions/nodejs-callback-with-return'
},
Handler: 'handler.handler',
Runtime: 'nodejs'
}),
async fn => {
const payload = await fn();
assert.deepEqual(payload, { foo: 'bar' });
}
)
);
it(
'nodejs_exit_before_init',
testInvoke(
() =>
createFunction({
Code: {
Directory: __dirname + '/functions/nodejs-exit'
},
Handler: 'handler.handler',
Runtime: 'nodejs'
}),
async fn => {
let err;
try {
await fn();
} catch (_err) {
err = _err;
}
assert(err);
assertProcessExitedError(err);
}
)
);
// `fun` should be resilient to its runtime cache being wiped away during
// runtime. At least, in between function creations. Consider a user running
// `now dev cache clean` while a `now dev` server is running, and then the
// user does a hard refresh to re-create the Lambda functions.
interface Hello {
event: {
hello: string;
};
}
it('clean_cache_dir_recovery', async () => {
await cleanCacheDir();
const fn = await createFunction({
Code: {
Directory: __dirname + '/functions/nodejs-echo'
},
Handler: 'handler.handler',
Runtime: 'nodejs'
});
try {
const payload = await fn<Hello>({ hello: 'world' });
assert.deepEqual(payload.event, { hello: 'world' });
} finally {
await fn.destroy();
}
});
// `provided` runtime
it(
'provided_bash_echo',
testInvoke(
() =>
createFunction({
Code: {
Directory: __dirname + '/functions/provided-bash-echo'
},
Handler: 'handler.handler',
Runtime: 'provided'
}),
async fn => {
const payload = await fn({ hello: 'world' });
assert.deepEqual(payload, { hello: 'world' });
}
)
);
// `nodejs6.10` runtime
it(
'nodejs610_version',
testInvoke(
() =>
createFunction({
Code: {
Directory: __dirname + '/functions/nodejs-version'
},
Handler: 'handler.handler',
Runtime: 'nodejs6.10'
}),
async fn => {
const versions = await fn({ hello: 'world' });
assert.equal(versions.node, '6.10.0');
}
)
);
// `nodejs8.10` runtime
it(
'nodejs810_version',
testInvoke(
() =>
createFunction({
Code: {
Directory: __dirname + '/functions/nodejs-version'
},
Handler: 'handler.handler',
Runtime: 'nodejs8.10'
}),
async fn => {
const versions = await fn({ hello: 'world' });
assert.equal(versions.node, '8.10.0');
}
)
);
it(
'nodejs810_handled_error',
testInvoke(
() =>
createFunction({
Code: {
Directory: __dirname + '/functions/nodejs-eval'
},
Handler: 'handler.handler',
Runtime: 'nodejs8.10'
}),
async fn => {
let err;
const error = 'this is a handled error';
try {
await fn({ error });
} catch (_err) {
err = _err;
}
assert(err);
expect(err.message).toBe(error);
const { result } = await fn({ code: '1 + 1' });
expect(result).toBe(2);
}
)
);
it(
'nodejs_reference_error',
testInvoke(
() =>
createFunction({
Code: {
Directory: __dirname + '/functions/nodejs-reference-error'
},
Handler: 'handler.handler',
Runtime: 'nodejs'
}),
async fn => {
let err;
try {
await fn();
} catch (_err) {
err = _err;
}
assert(err);
assert.equal(err.name, 'ReferenceError');
assert.equal(err.message, 'x is not defined');
}
)
);
it(
'nodejs810_exit_in_handler',
testInvoke(
() =>
createFunction({
Code: {
Directory: __dirname + '/functions/nodejs-eval'
},
Handler: 'handler.handler',
Runtime: 'nodejs8.10'
}),
async fn => {
let err;
try {
await fn({ code: 'process.exit(5)' });
} catch (_err) {
err = _err;
}
assert(err);
assertProcessExitedError(err);
}
)
);
// `nodejs10.x` runtime
it(
'nodejs10_version',
testInvoke(
() =>
createFunction({
Code: {
Directory: __dirname + '/functions/nodejs-version'
},
Handler: 'handler.handler',
Runtime: 'nodejs10.x'
}),
async fn => {
const versions = await fn({ hello: 'world' });
assert.equal(versions.node, '10.15.3');
}
)
);
// `nodejs12.x` runtime
it(
'nodejs12_version',
testInvoke(
() =>
createFunction({
Code: {
Directory: __dirname + '/functions/nodejs-version'
},
Handler: 'handler.handler',
Runtime: 'nodejs12.x'
}),
async fn => {
const versions = await fn({ hello: 'world' });
assert.equal(versions.node, '12.22.7');
}
)
);
// `nodejs14.x` runtime
it(
'nodejs14_version',
testInvoke(
() =>
createFunction({
Code: {
Directory: __dirname + '/functions/nodejs-version'
},
Handler: 'handler.handler',
Runtime: 'nodejs14.x'
}),
async fn => {
const versions = await fn({ hello: 'world' });
assert.equal(versions.node, '14.18.1');
}
)
);
// Support for paths as Handler
it(
'lambda_nested_handler',
testInvoke(
() =>
createFunction({
Code: {
Directory: __dirname + '/functions/nodejs-nested-handler'
},
Handler: 'hid.den/launcher.handler',
Runtime: 'nodejs',
Environment: {
Variables: {
HELLO: 'world'
}
}
}),
async fn => {
const env = await fn();
expect(env.HELLO).toBe('world');
}
)
);
// `python` runtime
it(
'python_hello',
testInvoke(
() =>
createFunction({
Code: {
Directory: __dirname + '/functions/python-hello'
},
Handler: 'hello.hello_handler',
Runtime: 'python'
}),
async fn => {
const payload = await fn({
first_name: 'John',
last_name: 'Smith'
});
assert.deepEqual(payload, { message: 'Hello John Smith!' });
}
)
);
// `python2.7` runtime
it(
'python27_version',
testInvoke(
() =>
createFunction({
Code: {
Directory: __dirname + '/functions/python-version'
},
Handler: 'handler.handler',
Runtime: 'python2.7'
}),
async fn => {
const payload = await fn();
assert.equal(payload['platform.python_version'], '2.7.12');
}
)
);
// `python3` runtime
it(
'python3_version',
testInvoke(
() =>
createFunction({
Code: {
Directory: __dirname + '/functions/python-version'
},
Handler: 'handler.handler',
Runtime: 'python3'
}),
async fn => {
const payload = await fn();
assert.equal(payload['platform.python_version'][0], '3');
}
)
);
// `python3.6` runtime
it(
'python36_version',
testInvoke(
() =>
createFunction({
Code: {
Directory: __dirname + '/functions/python-version'
},
Handler: 'handler.handler',
Runtime: 'python3.6'
}),
async fn => {
const payload = await fn();
assert.equal(payload['platform.python_version'], '3.6.8');
}
)
);
// `python3.7` runtime
it(
'python37_version',
testInvoke(
() =>
createFunction({
Code: {
Directory: __dirname + '/functions/python-version'
},
Handler: 'handler.handler',
Runtime: 'python3.7'
}),
async fn => {
const payload = await fn();
assert.equal(payload['platform.python_version'], '3.7.2');
}
)
);
// `ZipFile` Buffer support
it(
'lambda_zip_file_buffer',
testInvoke(
async () => {
return await createFunction({
Code: {
ZipFile: await readFile(
__dirname + '/functions/nodejs-env.zip'
)
},
Handler: 'index.env',
Runtime: 'nodejs',
Environment: {
Variables: {
HELLO: 'world'
}
}
});
},
async fn => {
const env = await fn();
assert.equal(env.HELLO, 'world');
// Assert that the `TASK_ROOT` dir includes the "zeit-fun-" prefix
assert(/^zeit-fun-/.test(basename(env.LAMBDA_TASK_ROOT)));
}
)
);
// `ZipFile` string support
it(
'lambda_zip_file_string',
testInvoke(
() =>
createFunction({
Code: {
ZipFile: __dirname + '/functions/nodejs-env.zip'
},
Handler: 'index.env',
Runtime: 'nodejs',
Environment: {
Variables: {
HELLO: 'world'
}
}
}),
async fn => {
const env = await fn();
assert.equal(env.HELLO, 'world');
// Assert that the `TASK_ROOT` dir includes the "zeit-fun-" prefix
assert(/^zeit-fun-/.test(basename(env.LAMBDA_TASK_ROOT)));
}
)
);
// `pkg` compilation support, requires go@1.15, must not be a higher version
it('pkg_support', async () => {
const root = require.resolve('pkg').replace(/\/node_modules(.*)$/, '');
const pkg = join(root, 'node_modules/.bin/pkg');
await execa(pkg, ['-t', 'node8', 'test/pkg-invoke.js'], {
cwd: root
});
const { stdout } = await execa(join(root, 'pkg-invoke'), {
cwd: __dirname,
stdio: ['ignore', 'pipe', 'inherit']
});
expect(JSON.parse(stdout).hello).toBe('world');
});
// `go1.x` runtime, requires go@1.15, must not be a higher version
it(
'go1x_echo',
testInvoke(
() =>
createFunction({
Code: {
Directory: __dirname + '/functions/go-echo'
},
Handler: 'handler',
Runtime: 'go1.x'
}),
async fn => {
const payload = await fn({ hello: 'world' });
expect(payload).toEqual({ hello: 'world' });
}
)
); | the_stack |
import { vertex } from '@tools/fragments';
import fragment from './glitch.frag';
import { Filter, Texture } from '@pixi/core';
import { SCALE_MODES } from '@pixi/constants';
import { DEG_TO_RAD, Rectangle } from '@pixi/math';
import type { IPoint } from '@pixi/math';
import type { FilterSystem, RenderTexture } from '@pixi/core';
import type { CLEAR_MODES } from '@pixi/constants';
type PointLike = IPoint | number[];
interface GlitchFilterOptions {
slices: number;
offset: number;
direction: number;
fillMode: number;
seed: number;
average: boolean;
minSize: number;
sampleSize: number;
red: PointLike;
green: PointLike;
blue: PointLike;
}
/**
* The GlitchFilter applies a glitch effect to an object.<br>
* 
*
* @class
* @extends PIXI.Filter
* @memberof PIXI.filters
* @see {@link https://www.npmjs.com/package/@pixi/filter-glitch|@pixi/filter-glitch}
* @see {@link https://www.npmjs.com/package/pixi-filters|pixi-filters}
*/
class GlitchFilter extends Filter
{
/** Default constructor options. */
public static readonly defaults: GlitchFilterOptions = {
slices: 5,
offset: 100,
direction: 0,
fillMode: 0,
average: false,
seed: 0,
red: [0, 0],
green: [0, 0],
blue: [0, 0],
minSize: 8,
sampleSize: 512,
};
/** Fill mode as transparent */
static readonly TRANSPARENT = 0;
/** Fill mode as original */
static readonly ORIGINAL = 1;
/** Fill mode as loop */
static readonly LOOP = 2;
/** Fill mode as clamp */
static readonly CLAMP = 3;
/** Fill mode as mirror */
static readonly MIRROR = 4;
/** The maximum offset value for each of the slices. */
public offset = 100;
/** The fill mode of the space after the offset. */
public fillMode: number = GlitchFilter.TRANSPARENT;
/**
* `true` will divide the bands roughly based on equal amounts
* where as setting to `false` will vary the band sizes dramatically (more random looking).
*/
public average = false;
/**
* A seed value for randomizing color offset. Animating
* this value to `Math.random()` produces a twitching effect.
*/
public seed = 0;
/** Minimum size of slices as a portion of the `sampleSize` */
public minSize = 8;
/** Height of the displacement map canvas. */
public sampleSize = 512;
/** Internally generated canvas. */
private _canvas: HTMLCanvasElement;
/**
* The displacement map is used to generate the bands.
* If using your own texture, `slices` will be ignored.
*
* @member {PIXI.Texture}
* @readonly
*/
public texture: Texture;
/** Internal number of slices */
private _slices = 0;
private _offsets: Float32Array = new Float32Array(1);
private _sizes: Float32Array = new Float32Array(1);
/** direction is actually a setter for uniform.cosDir and uniform.sinDir.
* Must be initialized to something different than the default value.
*/
private _direction = -1;
/**
* @param {object} [options] - The more optional parameters of the filter.
* @param {number} [options.slices=5] - The maximum number of slices.
* @param {number} [options.offset=100] - The maximum offset amount of slices.
* @param {number} [options.direction=0] - The angle in degree of the offset of slices.
* @param {number} [options.fillMode=0] - The fill mode of the space after the offset. Acceptable values:
* - `0` {@link PIXI.filters.GlitchFilter.TRANSPARENT TRANSPARENT}
* - `1` {@link PIXI.filters.GlitchFilter.ORIGINAL ORIGINAL}
* - `2` {@link PIXI.filters.GlitchFilter.LOOP LOOP}
* - `3` {@link PIXI.filters.GlitchFilter.CLAMP CLAMP}
* - `4` {@link PIXI.filters.GlitchFilter.MIRROR MIRROR}
* @param {number} [options.seed=0] - A seed value for randomizing glitch effect.
* @param {boolean} [options.average=false] - `true` will divide the bands roughly based on equal amounts
* where as setting to `false` will vary the band sizes dramatically (more random looking).
* @param {number} [options.minSize=8] - Minimum size of individual slice. Segment of total `sampleSize`
* @param {number} [options.sampleSize=512] - The resolution of the displacement map texture.
* @param {number[]} [options.red=[0,0]] - Red channel offset
* @param {number[]} [options.green=[0,0]] - Green channel offset.
* @param {number[]} [options.blue=[0,0]] - Blue channel offset.
*/
constructor(options?: Partial<GlitchFilterOptions>)
{
super(vertex, fragment);
this.uniforms.dimensions = new Float32Array(2);
this._canvas = document.createElement('canvas');
this._canvas.width = 4;
this._canvas.height = this.sampleSize;
this.texture = Texture.from(this._canvas, { scaleMode: SCALE_MODES.NEAREST });
Object.assign(this, GlitchFilter.defaults, options);
}
/**
* Override existing apply method in PIXI.Filter
* @private
*/
apply(filterManager: FilterSystem, input: RenderTexture, output: RenderTexture, clear: CLEAR_MODES): void
{
const { width, height } = input.filterFrame as Rectangle;
this.uniforms.dimensions[0] = width;
this.uniforms.dimensions[1] = height;
this.uniforms.aspect = height / width;
this.uniforms.seed = this.seed;
this.uniforms.offset = this.offset;
this.uniforms.fillMode = this.fillMode;
filterManager.applyFilter(this, input, output, clear);
}
/**
* Randomize the slices size (heights).
*
* @private
*/
private _randomizeSizes()
{
const arr = this._sizes;
const last = this._slices - 1;
const size = this.sampleSize;
const min = Math.min(this.minSize / size, 0.9 / this._slices);
if (this.average)
{
const count = this._slices;
let rest = 1;
for (let i = 0; i < last; i++)
{
const averageWidth = rest / (count - i);
const w = Math.max(averageWidth * (1 - (Math.random() * 0.6)), min);
arr[i] = w;
rest -= w;
}
arr[last] = rest;
}
else
{
let rest = 1;
const ratio = Math.sqrt(1 / this._slices);
for (let i = 0; i < last; i++)
{
const w = Math.max(ratio * rest * Math.random(), min);
arr[i] = w;
rest -= w;
}
arr[last] = rest;
}
this.shuffle();
}
/**
* Shuffle the sizes of the slices, advanced usage.
*/
shuffle(): void
{
const arr = this._sizes;
const last = this._slices - 1;
// shuffle
for (let i = last; i > 0; i--)
{
const rand = (Math.random() * i) >> 0;
const temp = arr[i];
arr[i] = arr[rand];
arr[rand] = temp;
}
}
/**
* Randomize the values for offset from -1 to 1
*
* @private
*/
private _randomizeOffsets(): void
{
for (let i = 0; i < this._slices; i++)
{
this._offsets[i] = Math.random() * (Math.random() < 0.5 ? -1 : 1);
}
}
/**
* Regenerating random size, offsets for slices.
*/
refresh(): void
{
this._randomizeSizes();
this._randomizeOffsets();
this.redraw();
}
/**
* Redraw displacement bitmap texture, advanced usage.
*/
redraw(): void
{
const size = this.sampleSize;
const texture = this.texture;
const ctx = this._canvas.getContext('2d') as CanvasRenderingContext2D;
ctx.clearRect(0, 0, 8, size);
let offset;
let y = 0;
for (let i = 0; i < this._slices; i++)
{
offset = Math.floor(this._offsets[i] * 256);
const height = this._sizes[i] * size;
const red = offset > 0 ? offset : 0;
const green = offset < 0 ? -offset : 0;
ctx.fillStyle = `rgba(${red}, ${green}, 0, 1)`;
ctx.fillRect(0, y >> 0, size, height + 1 >> 0);
y += height;
}
texture.baseTexture.update();
this.uniforms.displacementMap = texture;
}
/**
* Manually custom slices size (height) of displacement bitmap
*
* @member {number[]|Float32Array}
*/
set sizes(sizes: Float32Array)
{
const len = Math.min(this._slices, sizes.length);
for (let i = 0; i < len; i++)
{
this._sizes[i] = sizes[i];
}
}
get sizes(): Float32Array
{
return this._sizes;
}
/**
* Manually set custom slices offset of displacement bitmap, this is
* a collection of values from -1 to 1. To change the max offset value
* set `offset`.
*
* @member {number[]|Float32Array}
*/
set offsets(offsets: Float32Array)
{
const len = Math.min(this._slices, offsets.length);
for (let i = 0; i < len; i++)
{
this._offsets[i] = offsets[i];
}
}
get offsets(): Float32Array
{
return this._offsets;
}
/**
* The count of slices.
* @default 5
*/
get slices(): number
{
return this._slices;
}
set slices(value: number)
{
if (this._slices === value)
{
return;
}
this._slices = value;
this.uniforms.slices = value;
this._sizes = this.uniforms.slicesWidth = new Float32Array(value);
this._offsets = this.uniforms.slicesOffset = new Float32Array(value);
this.refresh();
}
/**
* The angle in degree of the offset of slices.
* @default 0
*/
get direction(): number
{
return this._direction;
}
set direction(value: number)
{
if (this._direction === value)
{
return;
}
this._direction = value;
const radians = value * DEG_TO_RAD;
this.uniforms.sinDir = Math.sin(radians);
this.uniforms.cosDir = Math.cos(radians);
}
/**
* Red channel offset.
*
* @member {PIXI.Point|number[]}
*/
get red(): PointLike
{
return this.uniforms.red;
}
set red(value: PointLike)
{
this.uniforms.red = value;
}
/**
* Green channel offset.
*
* @member {PIXI.Point|number[]}
*/
get green(): PointLike
{
return this.uniforms.green;
}
set green(value: PointLike)
{
this.uniforms.green = value;
}
/**
* Blue offset.
*
* @member {PIXI.Point|number[]}
*/
get blue(): PointLike
{
return this.uniforms.blue;
}
set blue(value: PointLike)
{
this.uniforms.blue = value;
}
/**
* Removes all references
*/
destroy(): void
{
this.texture?.destroy(true);
this.texture
= this._canvas
= this.red
= this.green
= this.blue
= this._sizes
= this._offsets = null as any;
}
}
export { GlitchFilter };
export type { GlitchFilterOptions }; | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { DatabaseAccounts } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { CosmosDBManagementClient } from "../cosmosDBManagementClient";
import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro";
import { LroImpl } from "../lroImpl";
import {
DatabaseAccountGetResults,
DatabaseAccountsListOptionalParams,
DatabaseAccountsListByResourceGroupOptionalParams,
Metric,
DatabaseAccountsListMetricsOptionalParams,
Usage,
DatabaseAccountsListUsagesOptionalParams,
MetricDefinition,
DatabaseAccountsListMetricDefinitionsOptionalParams,
DatabaseAccountsGetOptionalParams,
DatabaseAccountsGetResponse,
DatabaseAccountUpdateParameters,
DatabaseAccountsUpdateOptionalParams,
DatabaseAccountsUpdateResponse,
DatabaseAccountCreateUpdateParameters,
DatabaseAccountsCreateOrUpdateOptionalParams,
DatabaseAccountsCreateOrUpdateResponse,
DatabaseAccountsDeleteOptionalParams,
FailoverPolicies,
DatabaseAccountsFailoverPriorityChangeOptionalParams,
DatabaseAccountsListResponse,
DatabaseAccountsListByResourceGroupResponse,
DatabaseAccountsListKeysOptionalParams,
DatabaseAccountsListKeysResponse,
DatabaseAccountsListConnectionStringsOptionalParams,
DatabaseAccountsListConnectionStringsResponse,
RegionForOnlineOffline,
DatabaseAccountsOfflineRegionOptionalParams,
DatabaseAccountsOnlineRegionOptionalParams,
DatabaseAccountsGetReadOnlyKeysOptionalParams,
DatabaseAccountsGetReadOnlyKeysResponse,
DatabaseAccountsListReadOnlyKeysOptionalParams,
DatabaseAccountsListReadOnlyKeysResponse,
DatabaseAccountRegenerateKeyParameters,
DatabaseAccountsRegenerateKeyOptionalParams,
DatabaseAccountsCheckNameExistsOptionalParams,
DatabaseAccountsListMetricsResponse,
DatabaseAccountsListUsagesResponse,
DatabaseAccountsListMetricDefinitionsResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing DatabaseAccounts operations. */
export class DatabaseAccountsImpl implements DatabaseAccounts {
private readonly client: CosmosDBManagementClient;
/**
* Initialize a new instance of the class DatabaseAccounts class.
* @param client Reference to the service client
*/
constructor(client: CosmosDBManagementClient) {
this.client = client;
}
/**
* Lists all the Azure Cosmos DB database accounts available under the subscription.
* @param options The options parameters.
*/
public list(
options?: DatabaseAccountsListOptionalParams
): PagedAsyncIterableIterator<DatabaseAccountGetResults> {
const iter = this.listPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listPagingPage(options);
}
};
}
private async *listPagingPage(
options?: DatabaseAccountsListOptionalParams
): AsyncIterableIterator<DatabaseAccountGetResults[]> {
let result = await this._list(options);
yield result.value || [];
}
private async *listPagingAll(
options?: DatabaseAccountsListOptionalParams
): AsyncIterableIterator<DatabaseAccountGetResults> {
for await (const page of this.listPagingPage(options)) {
yield* page;
}
}
/**
* Lists all the Azure Cosmos DB database accounts available under the given resource group.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param options The options parameters.
*/
public listByResourceGroup(
resourceGroupName: string,
options?: DatabaseAccountsListByResourceGroupOptionalParams
): PagedAsyncIterableIterator<DatabaseAccountGetResults> {
const iter = this.listByResourceGroupPagingAll(resourceGroupName, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByResourceGroupPagingPage(resourceGroupName, options);
}
};
}
private async *listByResourceGroupPagingPage(
resourceGroupName: string,
options?: DatabaseAccountsListByResourceGroupOptionalParams
): AsyncIterableIterator<DatabaseAccountGetResults[]> {
let result = await this._listByResourceGroup(resourceGroupName, options);
yield result.value || [];
}
private async *listByResourceGroupPagingAll(
resourceGroupName: string,
options?: DatabaseAccountsListByResourceGroupOptionalParams
): AsyncIterableIterator<DatabaseAccountGetResults> {
for await (const page of this.listByResourceGroupPagingPage(
resourceGroupName,
options
)) {
yield* page;
}
}
/**
* Retrieves the metrics determined by the given filter for the given database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param filter An OData filter expression that describes a subset of metrics to return. The
* parameters that can be filtered are name.value (name of the metric, can have an or of multiple
* names), startTime, endTime, and timeGrain. The supported operator is eq.
* @param options The options parameters.
*/
public listMetrics(
resourceGroupName: string,
accountName: string,
filter: string,
options?: DatabaseAccountsListMetricsOptionalParams
): PagedAsyncIterableIterator<Metric> {
const iter = this.listMetricsPagingAll(
resourceGroupName,
accountName,
filter,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listMetricsPagingPage(
resourceGroupName,
accountName,
filter,
options
);
}
};
}
private async *listMetricsPagingPage(
resourceGroupName: string,
accountName: string,
filter: string,
options?: DatabaseAccountsListMetricsOptionalParams
): AsyncIterableIterator<Metric[]> {
let result = await this._listMetrics(
resourceGroupName,
accountName,
filter,
options
);
yield result.value || [];
}
private async *listMetricsPagingAll(
resourceGroupName: string,
accountName: string,
filter: string,
options?: DatabaseAccountsListMetricsOptionalParams
): AsyncIterableIterator<Metric> {
for await (const page of this.listMetricsPagingPage(
resourceGroupName,
accountName,
filter,
options
)) {
yield* page;
}
}
/**
* Retrieves the usages (most recent data) for the given database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
public listUsages(
resourceGroupName: string,
accountName: string,
options?: DatabaseAccountsListUsagesOptionalParams
): PagedAsyncIterableIterator<Usage> {
const iter = this.listUsagesPagingAll(
resourceGroupName,
accountName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listUsagesPagingPage(
resourceGroupName,
accountName,
options
);
}
};
}
private async *listUsagesPagingPage(
resourceGroupName: string,
accountName: string,
options?: DatabaseAccountsListUsagesOptionalParams
): AsyncIterableIterator<Usage[]> {
let result = await this._listUsages(
resourceGroupName,
accountName,
options
);
yield result.value || [];
}
private async *listUsagesPagingAll(
resourceGroupName: string,
accountName: string,
options?: DatabaseAccountsListUsagesOptionalParams
): AsyncIterableIterator<Usage> {
for await (const page of this.listUsagesPagingPage(
resourceGroupName,
accountName,
options
)) {
yield* page;
}
}
/**
* Retrieves metric definitions for the given database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
public listMetricDefinitions(
resourceGroupName: string,
accountName: string,
options?: DatabaseAccountsListMetricDefinitionsOptionalParams
): PagedAsyncIterableIterator<MetricDefinition> {
const iter = this.listMetricDefinitionsPagingAll(
resourceGroupName,
accountName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listMetricDefinitionsPagingPage(
resourceGroupName,
accountName,
options
);
}
};
}
private async *listMetricDefinitionsPagingPage(
resourceGroupName: string,
accountName: string,
options?: DatabaseAccountsListMetricDefinitionsOptionalParams
): AsyncIterableIterator<MetricDefinition[]> {
let result = await this._listMetricDefinitions(
resourceGroupName,
accountName,
options
);
yield result.value || [];
}
private async *listMetricDefinitionsPagingAll(
resourceGroupName: string,
accountName: string,
options?: DatabaseAccountsListMetricDefinitionsOptionalParams
): AsyncIterableIterator<MetricDefinition> {
for await (const page of this.listMetricDefinitionsPagingPage(
resourceGroupName,
accountName,
options
)) {
yield* page;
}
}
/**
* Retrieves the properties of an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
accountName: string,
options?: DatabaseAccountsGetOptionalParams
): Promise<DatabaseAccountsGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, options },
getOperationSpec
);
}
/**
* Updates the properties of an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param updateParameters The parameters to provide for the current database account.
* @param options The options parameters.
*/
async beginUpdate(
resourceGroupName: string,
accountName: string,
updateParameters: DatabaseAccountUpdateParameters,
options?: DatabaseAccountsUpdateOptionalParams
): Promise<
PollerLike<
PollOperationState<DatabaseAccountsUpdateResponse>,
DatabaseAccountsUpdateResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<DatabaseAccountsUpdateResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, accountName, updateParameters, options },
updateOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Updates the properties of an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param updateParameters The parameters to provide for the current database account.
* @param options The options parameters.
*/
async beginUpdateAndWait(
resourceGroupName: string,
accountName: string,
updateParameters: DatabaseAccountUpdateParameters,
options?: DatabaseAccountsUpdateOptionalParams
): Promise<DatabaseAccountsUpdateResponse> {
const poller = await this.beginUpdate(
resourceGroupName,
accountName,
updateParameters,
options
);
return poller.pollUntilDone();
}
/**
* Creates or updates an Azure Cosmos DB database account. The "Update" method is preferred when
* performing updates on an account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param createUpdateParameters The parameters to provide for the current database account.
* @param options The options parameters.
*/
async beginCreateOrUpdate(
resourceGroupName: string,
accountName: string,
createUpdateParameters: DatabaseAccountCreateUpdateParameters,
options?: DatabaseAccountsCreateOrUpdateOptionalParams
): Promise<
PollerLike<
PollOperationState<DatabaseAccountsCreateOrUpdateResponse>,
DatabaseAccountsCreateOrUpdateResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<DatabaseAccountsCreateOrUpdateResponse> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, accountName, createUpdateParameters, options },
createOrUpdateOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Creates or updates an Azure Cosmos DB database account. The "Update" method is preferred when
* performing updates on an account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param createUpdateParameters The parameters to provide for the current database account.
* @param options The options parameters.
*/
async beginCreateOrUpdateAndWait(
resourceGroupName: string,
accountName: string,
createUpdateParameters: DatabaseAccountCreateUpdateParameters,
options?: DatabaseAccountsCreateOrUpdateOptionalParams
): Promise<DatabaseAccountsCreateOrUpdateResponse> {
const poller = await this.beginCreateOrUpdate(
resourceGroupName,
accountName,
createUpdateParameters,
options
);
return poller.pollUntilDone();
}
/**
* Deletes an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
async beginDelete(
resourceGroupName: string,
accountName: string,
options?: DatabaseAccountsDeleteOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<void> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, accountName, options },
deleteOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Deletes an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
async beginDeleteAndWait(
resourceGroupName: string,
accountName: string,
options?: DatabaseAccountsDeleteOptionalParams
): Promise<void> {
const poller = await this.beginDelete(
resourceGroupName,
accountName,
options
);
return poller.pollUntilDone();
}
/**
* Changes the failover priority for the Azure Cosmos DB database account. A failover priority of 0
* indicates a write region. The maximum value for a failover priority = (total number of regions - 1).
* Failover priority values must be unique for each of the regions in which the database account
* exists.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param failoverParameters The new failover policies for the database account.
* @param options The options parameters.
*/
async beginFailoverPriorityChange(
resourceGroupName: string,
accountName: string,
failoverParameters: FailoverPolicies,
options?: DatabaseAccountsFailoverPriorityChangeOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<void> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, accountName, failoverParameters, options },
failoverPriorityChangeOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Changes the failover priority for the Azure Cosmos DB database account. A failover priority of 0
* indicates a write region. The maximum value for a failover priority = (total number of regions - 1).
* Failover priority values must be unique for each of the regions in which the database account
* exists.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param failoverParameters The new failover policies for the database account.
* @param options The options parameters.
*/
async beginFailoverPriorityChangeAndWait(
resourceGroupName: string,
accountName: string,
failoverParameters: FailoverPolicies,
options?: DatabaseAccountsFailoverPriorityChangeOptionalParams
): Promise<void> {
const poller = await this.beginFailoverPriorityChange(
resourceGroupName,
accountName,
failoverParameters,
options
);
return poller.pollUntilDone();
}
/**
* Lists all the Azure Cosmos DB database accounts available under the subscription.
* @param options The options parameters.
*/
private _list(
options?: DatabaseAccountsListOptionalParams
): Promise<DatabaseAccountsListResponse> {
return this.client.sendOperationRequest({ options }, listOperationSpec);
}
/**
* Lists all the Azure Cosmos DB database accounts available under the given resource group.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param options The options parameters.
*/
private _listByResourceGroup(
resourceGroupName: string,
options?: DatabaseAccountsListByResourceGroupOptionalParams
): Promise<DatabaseAccountsListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, options },
listByResourceGroupOperationSpec
);
}
/**
* Lists the access keys for the specified Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
listKeys(
resourceGroupName: string,
accountName: string,
options?: DatabaseAccountsListKeysOptionalParams
): Promise<DatabaseAccountsListKeysResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, options },
listKeysOperationSpec
);
}
/**
* Lists the connection strings for the specified Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
listConnectionStrings(
resourceGroupName: string,
accountName: string,
options?: DatabaseAccountsListConnectionStringsOptionalParams
): Promise<DatabaseAccountsListConnectionStringsResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, options },
listConnectionStringsOperationSpec
);
}
/**
* Offline the specified region for the specified Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param regionParameterForOffline Cosmos DB region to offline for the database account.
* @param options The options parameters.
*/
async beginOfflineRegion(
resourceGroupName: string,
accountName: string,
regionParameterForOffline: RegionForOnlineOffline,
options?: DatabaseAccountsOfflineRegionOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<void> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, accountName, regionParameterForOffline, options },
offlineRegionOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Offline the specified region for the specified Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param regionParameterForOffline Cosmos DB region to offline for the database account.
* @param options The options parameters.
*/
async beginOfflineRegionAndWait(
resourceGroupName: string,
accountName: string,
regionParameterForOffline: RegionForOnlineOffline,
options?: DatabaseAccountsOfflineRegionOptionalParams
): Promise<void> {
const poller = await this.beginOfflineRegion(
resourceGroupName,
accountName,
regionParameterForOffline,
options
);
return poller.pollUntilDone();
}
/**
* Online the specified region for the specified Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param regionParameterForOnline Cosmos DB region to online for the database account.
* @param options The options parameters.
*/
async beginOnlineRegion(
resourceGroupName: string,
accountName: string,
regionParameterForOnline: RegionForOnlineOffline,
options?: DatabaseAccountsOnlineRegionOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<void> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, accountName, regionParameterForOnline, options },
onlineRegionOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Online the specified region for the specified Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param regionParameterForOnline Cosmos DB region to online for the database account.
* @param options The options parameters.
*/
async beginOnlineRegionAndWait(
resourceGroupName: string,
accountName: string,
regionParameterForOnline: RegionForOnlineOffline,
options?: DatabaseAccountsOnlineRegionOptionalParams
): Promise<void> {
const poller = await this.beginOnlineRegion(
resourceGroupName,
accountName,
regionParameterForOnline,
options
);
return poller.pollUntilDone();
}
/**
* Lists the read-only access keys for the specified Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
getReadOnlyKeys(
resourceGroupName: string,
accountName: string,
options?: DatabaseAccountsGetReadOnlyKeysOptionalParams
): Promise<DatabaseAccountsGetReadOnlyKeysResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, options },
getReadOnlyKeysOperationSpec
);
}
/**
* Lists the read-only access keys for the specified Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
listReadOnlyKeys(
resourceGroupName: string,
accountName: string,
options?: DatabaseAccountsListReadOnlyKeysOptionalParams
): Promise<DatabaseAccountsListReadOnlyKeysResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, options },
listReadOnlyKeysOperationSpec
);
}
/**
* Regenerates an access key for the specified Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param keyToRegenerate The name of the key to regenerate.
* @param options The options parameters.
*/
async beginRegenerateKey(
resourceGroupName: string,
accountName: string,
keyToRegenerate: DatabaseAccountRegenerateKeyParameters,
options?: DatabaseAccountsRegenerateKeyOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<void> => {
return this.client.sendOperationRequest(args, spec);
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ resourceGroupName, accountName, keyToRegenerate, options },
regenerateKeyOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Regenerates an access key for the specified Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param keyToRegenerate The name of the key to regenerate.
* @param options The options parameters.
*/
async beginRegenerateKeyAndWait(
resourceGroupName: string,
accountName: string,
keyToRegenerate: DatabaseAccountRegenerateKeyParameters,
options?: DatabaseAccountsRegenerateKeyOptionalParams
): Promise<void> {
const poller = await this.beginRegenerateKey(
resourceGroupName,
accountName,
keyToRegenerate,
options
);
return poller.pollUntilDone();
}
/**
* Checks that the Azure Cosmos DB account name already exists. A valid account name may contain only
* lowercase letters, numbers, and the '-' character, and must be between 3 and 50 characters.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
checkNameExists(
accountName: string,
options?: DatabaseAccountsCheckNameExistsOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ accountName, options },
checkNameExistsOperationSpec
);
}
/**
* Retrieves the metrics determined by the given filter for the given database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param filter An OData filter expression that describes a subset of metrics to return. The
* parameters that can be filtered are name.value (name of the metric, can have an or of multiple
* names), startTime, endTime, and timeGrain. The supported operator is eq.
* @param options The options parameters.
*/
private _listMetrics(
resourceGroupName: string,
accountName: string,
filter: string,
options?: DatabaseAccountsListMetricsOptionalParams
): Promise<DatabaseAccountsListMetricsResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, filter, options },
listMetricsOperationSpec
);
}
/**
* Retrieves the usages (most recent data) for the given database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
private _listUsages(
resourceGroupName: string,
accountName: string,
options?: DatabaseAccountsListUsagesOptionalParams
): Promise<DatabaseAccountsListUsagesResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, options },
listUsagesOperationSpec
);
}
/**
* Retrieves metric definitions for the given database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
private _listMetricDefinitions(
resourceGroupName: string,
accountName: string,
options?: DatabaseAccountsListMetricDefinitionsOptionalParams
): Promise<DatabaseAccountsListMetricDefinitionsResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, accountName, options },
listMetricDefinitionsOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.DatabaseAccountGetResults
},
404: {}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName
],
headerParameters: [Parameters.accept],
serializer
};
const updateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}",
httpMethod: "PATCH",
responses: {
200: {
bodyMapper: Mappers.DatabaseAccountGetResults
},
201: {
bodyMapper: Mappers.DatabaseAccountGetResults
},
202: {
bodyMapper: Mappers.DatabaseAccountGetResults
},
204: {
bodyMapper: Mappers.DatabaseAccountGetResults
}
},
requestBody: Parameters.updateParameters,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const createOrUpdateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.DatabaseAccountGetResults
},
201: {
bodyMapper: Mappers.DatabaseAccountGetResults
},
202: {
bodyMapper: Mappers.DatabaseAccountGetResults
},
204: {
bodyMapper: Mappers.DatabaseAccountGetResults
}
},
requestBody: Parameters.createUpdateParameters,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}",
httpMethod: "DELETE",
responses: { 200: {}, 201: {}, 202: {}, 204: {} },
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName
],
serializer
};
const failoverPriorityChangeOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/failoverPriorityChange",
httpMethod: "POST",
responses: { 200: {}, 201: {}, 202: {}, 204: {} },
requestBody: Parameters.failoverParameters,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName
],
headerParameters: [Parameters.contentType],
mediaType: "json",
serializer
};
const listOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/databaseAccounts",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.DatabaseAccountsListResult
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.subscriptionId],
headerParameters: [Parameters.accept],
serializer
};
const listByResourceGroupOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.DatabaseAccountsListResult
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
headerParameters: [Parameters.accept],
serializer
};
const listKeysOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/listKeys",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.DatabaseAccountListKeysResult
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName
],
headerParameters: [Parameters.accept],
serializer
};
const listConnectionStringsOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/listConnectionStrings",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.DatabaseAccountListConnectionStringsResult
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName
],
headerParameters: [Parameters.accept],
serializer
};
const offlineRegionOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/offlineRegion",
httpMethod: "POST",
responses: {
200: {},
201: {},
202: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.regionParameterForOffline,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const onlineRegionOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/onlineRegion",
httpMethod: "POST",
responses: {
200: {},
201: {},
202: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.regionParameterForOnline,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const getReadOnlyKeysOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/readonlykeys",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.DatabaseAccountListReadOnlyKeysResult
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName
],
headerParameters: [Parameters.accept],
serializer
};
const listReadOnlyKeysOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/readonlykeys",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.DatabaseAccountListReadOnlyKeysResult
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName
],
headerParameters: [Parameters.accept],
serializer
};
const regenerateKeyOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/regenerateKey",
httpMethod: "POST",
responses: { 200: {}, 201: {}, 202: {}, 204: {} },
requestBody: Parameters.keyToRegenerate,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName
],
headerParameters: [Parameters.contentType],
mediaType: "json",
serializer
};
const checkNameExistsOperationSpec: coreClient.OperationSpec = {
path: "/providers/Microsoft.DocumentDB/databaseAccountNames/{accountName}",
httpMethod: "HEAD",
responses: { 200: {}, 404: {} },
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.accountName],
serializer
};
const listMetricsOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/metrics",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.MetricListResult
}
},
queryParameters: [Parameters.apiVersion, Parameters.filter],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName
],
headerParameters: [Parameters.accept],
serializer
};
const listUsagesOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/usages",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.UsagesResult
}
},
queryParameters: [Parameters.apiVersion, Parameters.filter1],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName
],
headerParameters: [Parameters.accept],
serializer
};
const listMetricDefinitionsOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/metricDefinitions",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.MetricDefinitionsListResult
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import classnames from 'classnames';
import * as React from 'react';
import TextArea from './TextArea';
import { InputPropsType } from './PropsType';
import { formatNumber } from '../../utils/format/number';
import InputItem from './InputItem';
export type HTMLInputProps = Omit<
React.HTMLProps<HTMLInputElement>,
'onChange' | 'onFocus' | 'onBlur' | 'value' | 'defaultValue' | 'type'
>;
export interface InputProps extends InputPropsType, HTMLInputProps {
prefixCls?: string;
className?: string;
autoAdjustHeight?: boolean;
onExtraClick?: React.MouseEventHandler<HTMLDivElement>;
}
function normalizeValue(value?: string) {
if (typeof value === 'undefined' || value === null) {
return '';
}
return String(value);
}
function noop() {}
class Input extends React.Component<InputProps, any> {
static TextArea: typeof TextArea;
static defaultProps = {
prefixCls: 'fm-input',
type: 'text',
editable: true,
disabled: false,
placeholder: '',
clear: false,
center: false,
onChange: noop,
onBlur: noop,
onFocus: noop,
extra: '',
onExtraClick: noop,
error: false,
errorMessage: '',
labelWidth: 90,
updatePlaceholder: false,
};
inputRef!: Input | null;
private debounceTimeout!: number | null;
constructor(props: InputProps) {
super(props);
this.state = {
placeholder: props.placeholder,
value: normalizeValue(props.value || props.defaultValue),
};
}
// eslint-disable-next-line react/no-deprecated
componentWillReceiveProps(nextProps: InputProps) {
if ('placeholder' in nextProps && !nextProps.updatePlaceholder) {
this.setState({
placeholder: nextProps.placeholder,
});
}
if ('value' in nextProps) {
this.setState({
value: nextProps.value,
});
}
}
componentWillUnmount() {
if (this.debounceTimeout) {
window.clearTimeout(this.debounceTimeout);
this.debounceTimeout = null;
}
}
onInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const el = e.target;
const { value: rawVal } = el;
let prePos = 0;
try {
// some input type do not support selection, see https://html.spec.whatwg.org/multipage/input.html#do-not-apply
prePos = el.selectionEnd || 0;
} catch (error) {
console.warn('Get selection error:', error);
}
const { value: preCtrlVal = '' } = this.state;
const { type } = this.props;
let ctrlValue = rawVal;
let valueLen;
switch (type) {
case 'bankCard':
ctrlValue = rawVal.replace(/\D/g, '').replace(/(....)(?=.)/g, '$1 ');
break;
case 'phone':
ctrlValue = rawVal.replace(/\D/g, '').substring(0, 11);
valueLen = ctrlValue.length;
if (valueLen > 3 && valueLen < 8) {
ctrlValue = `${ctrlValue.substr(0, 3)} ${ctrlValue.substr(3)}`;
} else if (valueLen >= 8) {
ctrlValue = `${ctrlValue.substr(0, 3)} ${ctrlValue.substr(3, 4)} ${ctrlValue.substr(7)}`;
}
break;
case 'number':
ctrlValue = rawVal.replace(/\D/g, '');
break;
case 'digit':
ctrlValue = formatNumber(rawVal, true);
el.value = ctrlValue;
break;
case 'text':
case 'password':
default:
break;
}
this.handleOnChange(ctrlValue, ctrlValue !== rawVal, () => {
switch (type) {
case 'bankCard':
case 'phone':
case 'number':
// controlled input type needs to adjust the position of the caret
try {
// some input type do not support selection, see https://html.spec.whatwg.org/multipage/input.html#do-not-apply
let pos = this.calcPos(prePos, preCtrlVal, rawVal, ctrlValue, [' '], /\D/g);
if ((type === 'phone' && (pos === 4 || pos === 9)) || (type === 'bankCard' && pos > 0 && pos % 5 === 0)) {
pos -= 1;
}
el.selectionStart = el.selectionEnd = pos;
} catch (error) {
console.warn('Set selection error:', error);
}
break;
default:
break;
}
});
};
handleOnChange = (value: string, isMutated: boolean = false, adjustPos: Function = noop) => {
const { onChange } = this.props;
if (!('value' in this.props)) {
this.setState({ value });
} else {
this.setState({ value: this.props.value });
}
if (onChange) {
if (isMutated) {
setTimeout(() => {
onChange(value);
adjustPos();
});
} else {
onChange(value);
adjustPos();
}
} else {
adjustPos();
}
};
// calculate the position of the caret
calcPos = (
prePos: number,
preCtrlVal: string,
rawVal: string,
ctrlVal: string,
placeholderChars: Array<string>,
maskReg: RegExp,
) => {
const editLength = rawVal.length - preCtrlVal.length;
const isAddition = editLength > 0;
let pos = prePos;
if (isAddition) {
const additionStr = rawVal.substr(pos - editLength, editLength);
let ctrlCharCount = additionStr.replace(maskReg, '').length;
pos -= editLength - ctrlCharCount;
let placeholderCharCount = 0;
while (ctrlCharCount > 0) {
if (placeholderChars.indexOf(ctrlVal.charAt(pos - ctrlCharCount + placeholderCharCount)) === -1) {
ctrlCharCount--;
} else {
placeholderCharCount++;
}
}
pos += placeholderCharCount;
}
return pos;
};
onInputFocus = (value?: string) => {
if (this.debounceTimeout) {
clearTimeout(this.debounceTimeout);
this.debounceTimeout = null;
}
this.setState({
focus: true,
});
if (this.props.onFocus) {
this.props.onFocus(value);
}
};
onInputBlur = (value?: string) => {
if (this.inputRef) {
// this.inputRef may be null if customKeyboard unmount
this.debounceTimeout = window.setTimeout(() => {
if (document.activeElement !== (this.inputRef && this.inputRef.inputRef)) {
this.setState({
focus: false,
});
}
}, 200);
}
if (this.props.onBlur) {
// fix autoFocus item blur with flash
setTimeout(() => {
// fix ios12 wechat browser click failure after input
if (document.body) {
// eslint-disable-next-line no-self-assign
document.body.scrollTop = document.body.scrollTop;
}
}, 100);
this.props.onBlur(value);
}
};
clearInput = () => {
if (this.props.type !== 'password' && this.props.updatePlaceholder) {
this.setState({
placeholder: this.props.value,
});
}
this.setState({
value: '',
});
if (this.props.onChange) {
this.props.onChange('');
}
this.focus();
};
// this is instance method for user to use
focus = () => {
if (this.inputRef) {
this.inputRef.focus();
}
};
render() {
const props = { ...this.props };
delete props.updatePlaceholder;
const {
prefixCls,
editable,
style,
clear,
children,
error,
errorMessage,
center,
className,
extra,
labelWidth,
type,
onExtraClick,
autoAdjustHeight,
...restProps
} = props;
const { name, disabled, maxLength } = restProps;
const { value } = this.state;
const { focus, placeholder } = this.state;
const wrapCls = classnames(`${prefixCls}-item`, className, {
[`${prefixCls}-disabled`]: disabled,
[`${prefixCls}-error`]: error,
[`${prefixCls}-focus`]: focus,
[`${prefixCls}-center`]: center,
});
const labelCls = classnames(`${prefixCls}-label`);
const controlCls = `${prefixCls}-control`;
let inputType: any = 'text';
let inputMode: any = 'text';
if (type === 'bankCard' || type === 'phone') {
inputType = 'tel';
inputMode = 'numeric';
} else if (type === 'password') {
inputType = 'password';
} else if (type === 'digit') {
inputType = 'text';
inputMode = 'decimal';
} else if (type !== 'text' && type !== 'number') {
inputType = type;
}
let patternProps;
if (type === 'number') {
inputMode = 'decimal';
patternProps = {
pattern: '[0-9]*',
};
}
let classNameProps;
if (type === 'digit') {
classNameProps = {
className: 'h5numInput', // the name is bad! todos rename.
};
}
return (
<div className={wrapCls}>
{children ? (
<div className={labelCls} style={{ width: labelWidth }}>
{children}
</div>
) : null}
<div className={controlCls}>
<div className={`${prefixCls}-body`}>
<InputItem
{...patternProps}
{...restProps}
{...classNameProps}
value={normalizeValue(value)}
defaultValue={undefined}
ref={(el: any) => (this.inputRef = el)}
style={style}
type={inputType}
inputMode={inputMode}
maxLength={maxLength}
name={name}
placeholder={placeholder}
onChange={this.onInputChange}
onFocus={this.onInputFocus}
onBlur={this.onInputBlur}
readOnly={!editable}
disabled={disabled}
/>
{clear && editable && !disabled && value && `${value}`.length > 0 ? (
<div className={`${prefixCls}-clear`} onClick={this.clearInput} />
) : null}
{extra !== '' ? (
<div className={`${prefixCls}-extra`} onClick={onExtraClick}>
{extra}
</div>
) : null}
</div>
{error && errorMessage && <div className={`${prefixCls}-errorMessage`}>{errorMessage}</div>}
</div>
</div>
);
}
}
export default Input; | the_stack |
/// <reference types="node" />
declare module 'bitcoinjs-lib' {
export interface Out {
script: Buffer;
value: number;
}
export interface In {
script: Buffer;
hash: Buffer;
index: number;
sequence: number;
witness: Buffer[];
}
export interface Network {
bech32?: string;
bip32: {
public: number;
private: number;
};
messagePrefix: string;
pubKeyHash: number;
scriptHash: number;
wif: number;
}
export class Block {
constructor();
byteLength(headersOnly?: boolean): number;
checkMerkleRoot(): any;
checkProofOfWork(): any;
getHash(): Buffer;
getId(): string;
getUTCDate(): any;
toBuffer(headersOnly?: boolean): Buffer;
toHex(headersOnly?: boolean): string;
static calculateMerkleRoot(transactions: Transaction[] | Array<{ getHash(): Buffer; }>): Buffer;
static calculateTarget(bits: number): Buffer;
static fromBuffer(buffer: Buffer): Block;
static fromHex(hex: string): Block;
}
export class ECPair {
d: string;
readonly compressed: boolean;
readonly network: Network;
readonly publicKey: string;
readonly privateKey: string;
sign(hash: Buffer): Buffer;
toWIF(): string;
verify(hash: Buffer, signature: Buffer): boolean;
static fromPublicKey(buffer: Buffer, network: Network): ECPair;
static fromPrivateKey(buffer: Buffer, network: Network): ECPair;
static fromWIF(string: string, network?: Network): ECPair;
static makeRandom(options?: { compressed?: boolean, network?: Network, rng?: Rng }): ECPair;
}
export type Rng = (size: number) => Buffer;
export namespace bip32 {
type BIP32Network = Pick<Network, 'wif' | 'bip32'>
interface BIP32 {
chainCode: Buffer;
depth: number;
index: number;
network: BIP32Network;
parentFingerprint: number;
keyPair: ECPair;
readonly identifier: Buffer;
readonly fingerprint: Buffer;
readonly privateKey: Buffer;
readonly publicKey: Buffer;
isNeutered(): boolean;
neutered(): BIP32;
toBase58(): string;
toWIF(): string;
derive(index: number): BIP32;
deriveHardened(index: number): BIP32;
derivePath(path: string): BIP32;
sign(hash: Buffer): Buffer;
verify(hash: Buffer, signature: Buffer): boolean;
}
function fromBase58(string: string, network?: BIP32Network): BIP32;
function fromPrivateKey(publicKey: Buffer, chainCode: Buffer, network?: BIP32Network): BIP32;
function fromPublicKey(publicKey: Buffer, chainCode: Buffer, network?: BIP32Network): BIP32;
function fromSeed(seed: Buffer, network?: BIP32Network): BIP32;
}
export class Transaction {
version: number;
locktime: number;
ins: In[];
outs: Out[];
constructor();
addInput(hash: Buffer, index: number, sequence?: number, scriptSig?: Buffer): number;
addOutput(scriptPubKey: Buffer | string, value: number): number;
byteLength(): number;
clone(): Transaction;
getHash(): Buffer;
getId(): string;
/** @since 3.0.0 */
hasWitnesses(): boolean;
hashForSignature(inIndex: number, prevOutScript: Buffer, hashType: number): Buffer;
/** @since 3.0.0 */
hashForWitnessV0(inIndex: number, prevOutScript: Buffer, value: number, hashType: number): Buffer;
isCoinbase(): boolean;
setInputScript(index: number, scriptSig: Buffer): void;
/** @since 3.0.0 */
setWitness(index: number, witness: any, ...args: any[]): void;
/** @since 3.0.0 */
toBuffer(buffer?: Buffer, initialOffset?: number): Buffer;
toHex(): string;
/** @since 3.1.0 */
virtualSize(): number;
/** @since 3.1.0 */
weight(): number;
static ADVANCED_TRANSACTION_FLAG: number;
static ADVANCED_TRANSACTION_MARKER: number;
static DEFAULT_SEQUENCE: number;
static SIGHASH_ALL: number;
static SIGHASH_ANYONECANPAY: number;
static SIGHASH_NONE: number;
static SIGHASH_SINGLE: number;
static fromBuffer(buffer: Buffer, __noStrict?: boolean): Transaction;
static fromHex(hex: string): Transaction;
static isCoinbaseHash(buffer: Buffer): boolean;
}
export interface Input {
pubKeys: Buffer[];
signatures: Buffer[];
prevOutScript: Buffer;
prevOutType: string;
signType: string;
signScript: Buffer;
witness: boolean;
}
export class TransactionBuilder {
constructor(network?: Network, maximumFeeRate?: number);
addInput(txhash: Buffer | string | Transaction, vout: number, sequence?: number, prevOutScript?: Buffer): number;
addOutput(scriptPubKey: Buffer | string, value: number): number;
build(): Transaction;
buildIncomplete(): Transaction;
setLockTime(locktime: number): void;
setVersion(version: number): void;
/** @since 3.0.0 */
sign(vin: number, keyPair: ECPair, redeemScript?: Buffer, hashType?: number, witnessValue?: number, witnessScript?: Buffer): void;
static fromTransaction(transaction: Transaction, network: Network): TransactionBuilder;
}
export const networks: {
bitcoin: Network;
testnet: Network;
};
export const opcodes: {
OP_0: number;
OP_0NOTEQUAL: number;
OP_1: number;
OP_10: number;
OP_11: number;
OP_12: number;
OP_13: number;
OP_14: number;
OP_15: number;
OP_16: number;
OP_1ADD: number;
OP_1NEGATE: number;
OP_1SUB: number;
OP_2: number;
OP_2DIV: number;
OP_2DROP: number;
OP_2DUP: number;
OP_2MUL: number;
OP_2OVER: number;
OP_2ROT: number;
OP_2SWAP: number;
OP_3: number;
OP_3DUP: number;
OP_4: number;
OP_5: number;
OP_6: number;
OP_7: number;
OP_8: number;
OP_9: number;
OP_ABS: number;
OP_ADD: number;
OP_AND: number;
OP_BOOLAND: number;
OP_BOOLOR: number;
OP_CAT: number;
OP_CHECKLOCKTIMEVERIFY: number;
OP_CHECKMULTISIG: number;
OP_CHECKMULTISIGVERIFY: number;
OP_CHECKSIG: number;
OP_CHECKSIGVERIFY: number;
OP_CODESEPARATOR: number;
OP_DEPTH: number;
OP_DIV: number;
OP_DROP: number;
OP_DUP: number;
OP_ELSE: number;
OP_ENDIF: number;
OP_EQUAL: number;
OP_EQUALVERIFY: number;
OP_FALSE: number;
OP_FROMALTSTACK: number;
OP_GREATERTHAN: number;
OP_GREATERTHANOREQUAL: number;
OP_HASH160: number;
OP_HASH256: number;
OP_IF: number;
OP_IFDUP: number;
OP_INVALIDOPCODE: number;
OP_INVERT: number;
OP_LEFT: number;
OP_LESSTHAN: number;
OP_LESSTHANOREQUAL: number;
OP_LSHIFT: number;
OP_MAX: number;
OP_MIN: number;
OP_MOD: number;
OP_MUL: number;
OP_NEGATE: number;
OP_NIP: number;
OP_NOP: number;
OP_NOP1: number;
OP_NOP10: number;
OP_NOP2: number;
OP_NOP3: number;
OP_NOP4: number;
OP_NOP5: number;
OP_NOP6: number;
OP_NOP7: number;
OP_NOP8: number;
OP_NOP9: number;
OP_NOT: number;
OP_NOTIF: number;
OP_NUMEQUAL: number;
OP_NUMEQUALVERIFY: number;
OP_NUMNOTEQUAL: number;
OP_OR: number;
OP_OVER: number;
OP_PICK: number;
OP_PUBKEY: number;
OP_PUBKEYHASH: number;
OP_PUSHDATA1: number;
OP_PUSHDATA2: number;
OP_PUSHDATA4: number;
OP_RESERVED: number;
OP_RESERVED1: number;
OP_RESERVED2: number;
OP_RETURN: number;
OP_RIGHT: number;
OP_RIPEMD160: number;
OP_ROLL: number;
OP_ROT: number;
OP_RSHIFT: number;
OP_SHA1: number;
OP_SHA256: number;
OP_SIZE: number;
OP_SUB: number;
OP_SUBSTR: number;
OP_SWAP: number;
OP_TOALTSTACK: number;
OP_TRUE: number;
OP_TUCK: number;
OP_VER: number;
OP_VERIF: number;
OP_VERIFY: number;
OP_VERNOTIF: number;
OP_WITHIN: number;
OP_XOR: number;
};
export namespace address {
function fromBase58Check(address: string): { hash: Buffer, version: number };
/** @since 3.2.0 */
function fromBech32(address: string): { data: Buffer, prefix: string, version: number };
function fromOutputScript(outputScript: Buffer, network?: Network): string;
function toBase58Check(hash: Buffer, version: number): string;
/** @since 3.2.0 */
function toBech32(data: Buffer, version: number, prefix: string): string;
function toOutputScript(address: string, network?: Network): Buffer;
}
export namespace payments {
type MaybeNetwork = {
network?: Network
}
type WithNetwork = {
network: Network
}
type WithWitness = {
witness?: Buffer[]
}
type WithAddressHash = {
hash?: Buffer,
address?: string
}
type WithInputOutput = {
input?: Buffer,
output?: Buffer
}
type PaymentOpts = {
validate?: boolean
}
type PaymentEmbed = {
output?: Buffer,
data?: Buffer[]
}
type PaymentP2ms = WithInputOutput & {
m?: number,
n?: number,
signatures?: Buffer[],
pubkeys?: Buffer[]
}
type PaymentPk = WithInputOutput & {
pubkey?: Buffer,
signature?: Buffer
}
type PaymentP2pkh = PaymentPk & WithAddressHash
type PaymentRedeem = WithInputOutput & WithWitness & MaybeNetwork
type PaymentP2sh = WithInputOutput & WithWitness & WithAddressHash & {
redeem?: PaymentRedeem
}
type PaymentP2wpkh = PaymentPk & WithWitness & WithAddressHash
type PaymentP2wsh = PaymentP2sh
function embed(
a: PaymentEmbed & MaybeNetwork,
opts?: PaymentOpts
): PaymentEmbed & WithNetwork;
function p2ms(
a: PaymentP2ms & MaybeNetwork,
opts?: PaymentOpts
): PaymentP2ms & WithNetwork & WithWitness;
function p2pk(
a: PaymentPk & MaybeNetwork,
opts?: PaymentOpts
): PaymentPk & WithNetwork & WithWitness;
function p2pkh(
a: PaymentP2pkh & MaybeNetwork,
opts?: PaymentOpts
): PaymentP2pkh & WithNetwork & WithWitness;
function p2sh(
a: PaymentP2sh & MaybeNetwork,
opts?: PaymentOpts
): PaymentP2sh & WithNetwork;
function p2wpkh(
a: PaymentP2wpkh & MaybeNetwork,
opts?: PaymentOpts
): PaymentP2wpkh & WithNetwork;
function p2wsh(
a: PaymentP2wsh & MaybeNetwork,
opts?: PaymentOpts
): PaymentP2wsh & WithNetwork;
}
export namespace crypto {
function hash160(buffer: Buffer): Buffer;
function hash256(buffer: Buffer): Buffer;
function ripemd160(buffer: Buffer): Buffer;
function sha1(buffer: Buffer): Buffer;
function sha256(buffer: Buffer): Buffer;
}
export namespace script {
function classifyInput(script: Buffer | Array<Buffer | number>, allowIncomplete?: boolean): "pubkeyhash" | "scripthash" | "multisig" | "pubkey" | "nonstandard";
function classifyOutput(script: Buffer | Array<Buffer | number>): "witnesspubkeyhash" | "witnessscripthash" | "pubkeyhash"
| "scripthash" | "multisig" | "pubkey" | "witnesscommitment" | "nulldata" | "nonstandard";
function classifyWitness(script: Buffer | Array<Buffer | number>, allowIncomplete: boolean): "witnesspubkeyhash" | "witnessscripthash" | "nonstandard";
function compile(chunks: Array<Buffer | number>): Buffer;
function decompile(buffer: Buffer): Array<Buffer | number>;
function fromASM(asm: string): Buffer;
function isCanonicalPubKey(buffer: Buffer): boolean;
function isCanonicalScriptSignature(buffer: Buffer): boolean;
function isDefinedHashType(hashType: any): boolean;
function isPushOnly(value: any): boolean;
function toASM(chunks: Buffer | Array<Buffer | number>): string;
function toStack(chunks: Buffer | Array<Buffer | number>): Buffer[];
namespace number {
function decode(buffer: Buffer, maxLength: number, minimal: boolean): number;
function encode(number: number): Buffer;
}
const multisig: {
input: {
decode(buffer: Buffer): Array<Buffer | number>;
decodeStack(stack: Buffer[], allowIncomplete: boolean): Array<Buffer | number>;
encode(signatures: Buffer[], scriptPubKey: Buffer): Buffer;
encodeStack(signatures: Buffer[], scriptPubKey: Buffer): Buffer[];
};
output: {
decode(buffer: Buffer, allowIncomplete: boolean): { m: number; pubKeys: Array<Buffer | number> };
encode(m: number, pubKeys: Array<Buffer | number>): Buffer;
};
};
const pubKey: {
input: {
decode(buffer: Buffer): Array<Buffer | number>;
decodeStack(stack: Buffer[]): Array<Buffer | number>;
encode(signature: Buffer): Buffer;
encodeStack(signature: Buffer): Buffer[];
};
output: {
decode(buffer: Buffer): Buffer | number;
encode(pubKey: Buffer): Buffer;
};
};
const pubKeyHash: {
input: {
decode(buffer: Buffer): { signature: Buffer; pubKey: Buffer };
decodeStack(stack: Buffer[]): { signature: Buffer; pubKey: Buffer };
encode(signature: Buffer, pubKey: Buffer): Buffer;
encodeStack(signature: Buffer, pubKey: Buffer): [Buffer, Buffer];
};
output: {
decode(buffer: Buffer): Buffer;
encode(pubKeyHash: Buffer): Buffer;
};
};
const scriptHash: {
input: {
decode(buffer: Buffer): { redeemScriptStack: Buffer[]; redeemScript: Buffer };
decodeStack(stack: Buffer[]): { redeemScriptStack: Buffer[]; redeemScript: Buffer };
encode(redeemScriptSig: Array<Buffer | number>, redeemScript: Buffer): Buffer;
encodeStack(redeemScriptStack: Buffer[], redeemScript: Buffer): Buffer[];
};
output: {
decode(buffer: Buffer): Buffer;
encode(scriptHash: Buffer): Buffer;
};
};
const witnessCommitment: {
output: {
decode(buffer: Buffer): Buffer[];
encode(commitment: Buffer): Buffer;
};
};
const witnessPubKeyHash: {
input: {
decodeStack(stack: Buffer[]): { signature: Buffer; pubKey: Buffer };
encodeStack(signature: Buffer, pubKey: Buffer): [Buffer, Buffer];
};
output: {
decode(buffer: Buffer): Buffer;
encode(pubKeyHash: Buffer): Buffer;
};
};
const witnessScriptHash: {
input: {
decodeStack(stack: Buffer[]): { redeemScriptStack: Buffer[]; redeemScript: Buffer };
encodeStack(redeemScriptStack: Buffer[], redeemScript: Buffer): Buffer[];
};
output: {
decode(buffer: Buffer): Buffer;
encode(scriptHash: Buffer): Buffer;
};
};
const nullData: {
output: {
decode(buffer: Buffer): Buffer;
encode(data: Buffer): Buffer;
};
};
}
} | the_stack |
import * as React from 'react';
import clsx from 'clsx';
import { useForkRef } from '@mui/material/utils';
import { styled } from '@mui/material/styles';
import { composeClasses } from '../utils/material-ui-utils';
import { useGridRootProps } from '../hooks/utils/useGridRootProps';
import { useGridApiContext } from '../hooks/utils/useGridApiContext';
import { useGridSelector } from '../hooks/utils/useGridSelector';
import { gridScrollBarSizeSelector } from '../hooks/features/container/gridContainerSizesSelector';
import {
visibleGridColumnsSelector,
gridColumnsMetaSelector,
} from '../hooks/features/columns/gridColumnsSelector';
import {
gridFocusCellSelector,
gridTabIndexCellSelector,
} from '../hooks/features/focus/gridFocusStateSelector';
import { visibleSortedGridRowsAsArraySelector } from '../hooks/features/filter/gridFilterSelector';
import { gridDensityRowHeightSelector } from '../hooks/features/density/densitySelector';
import { gridEditRowsStateSelector } from '../hooks/features/editRows/gridEditRowsSelector';
import { GridEvents } from '../constants/eventsConstants';
import { gridPaginationSelector } from '../hooks/features/pagination/gridPaginationSelector';
import { useGridApiEventHandler } from '../hooks/utils/useGridApiEventHandler';
import { getDataGridUtilityClass } from '../gridClasses';
import { GridComponentProps } from '../GridComponentProps';
import { GridRowId } from '../models/gridRows';
type OwnerState = { classes: GridComponentProps['classes'] };
const useUtilityClasses = (ownerState: OwnerState) => {
const { classes } = ownerState;
const slots = {
root: ['virtualScroller'],
content: ['virtualScrollerContent'],
renderZone: ['virtualScrollerRenderZone'],
};
return composeClasses(slots, getDataGridUtilityClass, classes);
};
const VirtualScrollerRoot = styled('div', {
name: 'MuiDataGrid',
slot: 'VirtualScroller',
})({
overflow: 'auto',
'@media print': {
overflow: 'hidden',
},
});
const VirtualScrollerContent = styled('div', {
name: 'MuiDataGrid',
slot: 'Content',
})({
position: 'relative',
overflow: 'hidden',
});
const VirtualScrollerRenderZone = styled('div', {
name: 'MuiDataGrid',
slot: 'RenderingZone',
})({
position: 'absolute',
});
// Uses binary search to avoid looping through all possible positions
export function getIndexFromScroll(
offset: number,
positions: number[],
sliceStart = 0,
sliceEnd = positions.length,
): number {
if (positions.length <= 0) {
return -1;
}
if (sliceStart >= sliceEnd) {
return sliceStart;
}
const pivot = sliceStart + Math.floor((sliceEnd - sliceStart) / 2);
const itemOffset = positions[pivot];
return offset <= itemOffset
? getIndexFromScroll(offset, positions, sliceStart, pivot)
: getIndexFromScroll(offset, positions, pivot + 1, sliceEnd);
}
export interface RenderContext {
firstRowIndex: number;
lastRowIndex: number;
firstColumnIndex: number;
lastColumnIndex: number;
}
interface GridVirtualScrollerProps extends React.HTMLAttributes<HTMLDivElement> {
selectionLookup: Record<string, GridRowId>;
disableVirtualization?: boolean;
}
const GridVirtualScroller = React.forwardRef<HTMLDivElement, GridVirtualScrollerProps>(
function GridVirtualScroller(props, ref) {
const { className, selectionLookup, disableVirtualization, ...other } = props;
const apiRef = useGridApiContext();
const rootProps = useGridRootProps();
const visibleColumns = useGridSelector(apiRef, visibleGridColumnsSelector);
const columnsMeta = useGridSelector(apiRef, gridColumnsMetaSelector);
const visibleSortedRowsAsArray = useGridSelector(apiRef, visibleSortedGridRowsAsArraySelector);
const rowHeight = useGridSelector(apiRef, gridDensityRowHeightSelector);
const cellFocus = useGridSelector(apiRef, gridFocusCellSelector);
const cellTabIndex = useGridSelector(apiRef, gridTabIndexCellSelector);
const editRowsState = useGridSelector(apiRef, gridEditRowsStateSelector);
const scrollBarState = useGridSelector(apiRef, gridScrollBarSizeSelector);
const paginationState = useGridSelector(apiRef, gridPaginationSelector);
const renderZoneRef = React.useRef<HTMLDivElement>(null);
const rootRef = React.useRef<HTMLDivElement>(null);
const handleRef = useForkRef<HTMLDivElement>(ref, rootRef);
const [renderContext, setRenderContext] = React.useState<RenderContext | null>(null);
const prevRenderContext = React.useRef<RenderContext | null>(renderContext);
const scrollPosition = React.useRef({ top: 0, left: 0 });
const [containerWidth, setContainerWidth] = React.useState<number | null>(null);
const ownerState = { classes: rootProps.classes };
const classes = useUtilityClasses(ownerState);
const prevTotalWidth = React.useRef(columnsMeta.totalWidth);
const rowsInCurrentPage = React.useMemo(() => {
if (rootProps.pagination && rootProps.paginationMode === 'client') {
const start = paginationState.pageSize * paginationState.page;
return visibleSortedRowsAsArray.slice(start, start + paginationState.pageSize);
}
return visibleSortedRowsAsArray;
}, [paginationState, rootProps.pagination, rootProps.paginationMode, visibleSortedRowsAsArray]);
const computeRenderContext = React.useCallback(() => {
if (disableVirtualization) {
return {
firstRowIndex: 0,
lastRowIndex: rowsInCurrentPage.length,
firstColumnIndex: 0,
lastColumnIndex: visibleColumns.length,
};
}
const { top, left } = scrollPosition.current!;
const numberOfRowsToRender = rootProps.autoHeight
? rowsInCurrentPage.length
: Math.floor(rootRef.current!.clientHeight / rowHeight);
const firstRowIndex = Math.floor(top / rowHeight);
const lastRowIndex = firstRowIndex + numberOfRowsToRender;
const { positions } = gridColumnsMetaSelector(apiRef.current.state); // To avoid infinite loop
const firstColumnIndex = getIndexFromScroll(left, positions);
const lastColumnIndex = getIndexFromScroll(left + containerWidth!, positions);
return {
firstRowIndex,
lastRowIndex,
firstColumnIndex,
lastColumnIndex,
};
}, [
apiRef,
containerWidth,
rootProps.autoHeight,
disableVirtualization,
rowHeight,
rowsInCurrentPage.length,
visibleColumns.length,
]);
React.useEffect(() => {
if (disableVirtualization) {
renderZoneRef.current!.style.transform = `translate3d(0px, 0px, 0px)`;
} else {
// TODO a scroll reset should not be necessary
rootRef.current!.scrollLeft = 0;
rootRef.current!.scrollTop = 0;
}
setContainerWidth(rootRef.current!.clientWidth);
}, [disableVirtualization]);
React.useEffect(() => {
if (containerWidth == null) {
return;
}
const initialRenderContext = computeRenderContext();
prevRenderContext.current = initialRenderContext;
setRenderContext(initialRenderContext);
const { top, left } = scrollPosition.current!;
const params = { top, left, renderContext: initialRenderContext };
apiRef.current.publishEvent(GridEvents.rowsScroll, params);
}, [apiRef, computeRenderContext, containerWidth]);
const handleResize = React.useCallback(() => {
if (rootRef.current) {
setContainerWidth(rootRef.current.clientWidth);
}
}, []);
useGridApiEventHandler(apiRef, GridEvents.resize, handleResize);
const handleScroll = (event: React.UIEvent) => {
const { scrollTop, scrollLeft } = event.currentTarget;
scrollPosition.current.top = scrollTop;
scrollPosition.current.left = scrollLeft;
// On iOS and macOS, negative offsets are possible when swiping past the start
if (scrollLeft < 0 || scrollTop < 0 || !prevRenderContext.current) {
return;
}
// When virtualization is disabled, the context never changes during scroll
const nextRenderContext = disableVirtualization
? prevRenderContext.current
: computeRenderContext();
const rowsScrolledSincePreviousRender = Math.abs(
nextRenderContext.firstRowIndex - prevRenderContext.current.firstRowIndex,
);
const columnsScrolledSincePreviousRender = Math.abs(
nextRenderContext.firstColumnIndex - prevRenderContext.current.firstColumnIndex,
);
const shouldSetState =
rowsScrolledSincePreviousRender >= rootProps.rowThreshold ||
columnsScrolledSincePreviousRender >= rootProps.columnThreshold ||
prevTotalWidth.current !== columnsMeta.totalWidth;
// TODO rename event to a wider name, it's not only fired for row scrolling
// TODO create a interface to type correctly the params
apiRef.current.publishEvent(GridEvents.rowsScroll, {
top: scrollTop,
left: scrollLeft,
renderContext: shouldSetState ? nextRenderContext : prevRenderContext.current,
});
if (shouldSetState) {
setRenderContext(nextRenderContext);
prevRenderContext.current = nextRenderContext;
prevTotalWidth.current = columnsMeta.totalWidth;
const top = Math.max(nextRenderContext.firstRowIndex - rootProps.rowBuffer, 0) * rowHeight;
const firstColumnToRender = Math.max(
nextRenderContext.firstColumnIndex - rootProps.columnBuffer,
0,
);
const left = columnsMeta.positions[firstColumnToRender];
renderZoneRef.current!.style.transform = `translate3d(${left}px, ${top}px, 0px)`;
}
};
const getRows = () => {
if (!renderContext || containerWidth == null) {
return null;
}
const rowBuffer = !disableVirtualization ? rootProps.rowBuffer : 0;
const columnBuffer = !disableVirtualization ? rootProps.columnBuffer : 0;
const firstRowToRender = Math.max(renderContext.firstRowIndex - rowBuffer, 0);
const lastRowToRender = Math.min(
renderContext.lastRowIndex! + rowBuffer,
rowsInCurrentPage.length,
);
const firstColumnToRender = Math.max(renderContext.firstColumnIndex - columnBuffer, 0);
const lastColumnToRender = Math.min(
renderContext.lastColumnIndex + columnBuffer,
visibleColumns.length,
);
const renderedRows = rowsInCurrentPage.slice(firstRowToRender, lastRowToRender);
const renderedColumns = visibleColumns.slice(firstColumnToRender, lastColumnToRender);
const startIndex = paginationState.pageSize * paginationState.page;
const rows: JSX.Element[] = [];
for (let i = 0; i < renderedRows.length; i += 1) {
const [id, row] = renderedRows[i];
rows.push(
<rootProps.components.Row
key={i}
row={row}
rowId={id}
rowHeight={rowHeight}
cellFocus={cellFocus} // TODO move to inside the row
cellTabIndex={cellTabIndex} // TODO move to inside the row
editRowsState={editRowsState} // TODO move to inside the row
scrollBarState={scrollBarState} // TODO remove once useGridContainerProps is deleted
renderedColumns={renderedColumns}
visibleColumns={visibleColumns}
firstColumnToRender={firstColumnToRender}
lastColumnToRender={lastColumnToRender}
selected={selectionLookup[id] !== undefined}
index={startIndex + renderContext.firstRowIndex! + i}
containerWidth={containerWidth}
{...rootProps.componentsProps?.row}
/>,
);
}
return rows;
};
const needsHorizontalScrollbar = containerWidth && columnsMeta.totalWidth > containerWidth;
const contentSize = {
width: needsHorizontalScrollbar ? columnsMeta.totalWidth : 'auto',
// In cases where the columns exceed the available width,
// the horizontal scrollbar should be shown even when there're no rows.
// Keeping 1px as minimum height ensures that the scrollbar will visible if necessary.
height: Math.max(rowsInCurrentPage.length * rowHeight, 1),
};
if (rootProps.autoHeight && rowsInCurrentPage.length === 0) {
contentSize.height = 2 * rowHeight; // Give room to show the overlay when there no rows.
}
return (
<VirtualScrollerRoot
ref={handleRef}
className={clsx(classes.root, className)}
onScroll={handleScroll}
{...other}
>
<VirtualScrollerContent className={classes.content} style={contentSize}>
<VirtualScrollerRenderZone ref={renderZoneRef} className={classes.renderZone}>
{getRows()}
</VirtualScrollerRenderZone>
</VirtualScrollerContent>
</VirtualScrollerRoot>
);
},
);
export { GridVirtualScroller }; | the_stack |
import {
applyBindings
} from '@tko/bind'
import {
triggerEvent
} from '@tko/utils'
import { DataBindProvider } from '@tko/provider.databind'
import {
observable
} from '@tko/observable'
import {
options
} from '@tko/utils'
import {bindings as coreBindings} from '../dist'
import '@tko/utils/helpers/jasmine-13-helper'
describe('Binding: Event', function () {
beforeEach(jasmine.prepareTestNode)
beforeEach(function () {
var provider = new DataBindProvider()
options.bindingProviderInstance = provider
provider.bindingHandlers.set(coreBindings)
})
it('Should invoke the supplied function when the event occurs, using model as \'this\' param and first arg, and event as second arg', function () {
var model = {
firstWasCalled: false,
firstHandler: function (passedModel, evt) {
expect(evt.type).toEqual('click')
expect(this).toEqual(model)
expect(passedModel).toEqual(model)
expect(model.firstWasCalled).toEqual(false)
model.firstWasCalled = true
},
secondWasCalled: false,
secondHandler: function (passedModel, evt) {
expect(evt.type).toEqual('mouseover')
expect(this).toEqual(model)
expect(passedModel).toEqual(model)
expect(model.secondWasCalled).toEqual(false)
model.secondWasCalled = true
}
}
testNode.innerHTML = "<button data-bind='event:{click:firstHandler, mouseover:secondHandler, mouseout:null}'>hey</button>"
applyBindings(model, testNode)
triggerEvent(testNode.childNodes[0], 'click')
expect(model.firstWasCalled).toEqual(true)
expect(model.secondWasCalled).toEqual(false)
triggerEvent(testNode.childNodes[0], 'mouseover')
expect(model.secondWasCalled).toEqual(true)
triggerEvent(testNode.childNodes[0], 'mouseout') // Shouldn't do anything (specifically, shouldn't throw)
})
it('Should prevent default action', function () {
testNode.innerHTML = "<a href='http://www.example.com/' data-bind='event: { click: noop }'>hey</a>"
applyBindings({ noop: function () {} }, testNode)
triggerEvent(testNode.childNodes[0], 'click')
// Assuming we haven't been redirected to http://www.example.com/, this spec has now passed
})
it('Should allow default action by setting preventDefault:false', function () {
testNode.innerHTML = "<div data-bind='event: {click: test}'><a href='#' data-bind='event: {click: {preventDefault: false}}'>hey</a></div>"
let prevented
applyBindings({
test: (_, event) => prevented = event.defaultPrevented,
}, testNode)
triggerEvent(testNode.childNodes[0].childNodes[0], 'click')
expect(prevented).toEqual(false)
})
it('Should conditionally allow default action when preventDefault is observable', function () {
testNode.innerHTML = "<div data-bind='event: {click: test}'><a href='#' data-bind='event: {click: {preventDefault: obs}}'>hey</a></div>"
let prevented
const obs = observable(true)
applyBindings({
test: (_, event) => prevented = event.defaultPrevented,
obs: obs
}, testNode)
triggerEvent(testNode.childNodes[0].childNodes[0], 'click')
expect(prevented).toEqual(true)
obs(false)
triggerEvent(testNode.childNodes[0].childNodes[0], 'click')
expect(prevented).toEqual(false)
})
it('Should let bubblable events bubble to parent elements by default', function () {
var model = {
innerWasCalled: false,
innerDoCall: function () { this.innerWasCalled = true },
outerWasCalled: false,
outerDoCall: function () { this.outerWasCalled = true }
}
testNode.innerHTML = "<div data-bind='event:{click:outerDoCall}'><button data-bind='event:{click:innerDoCall}'>hey</button></div>"
applyBindings(model, testNode)
triggerEvent(testNode.childNodes[0].childNodes[0], 'click')
expect(model.innerWasCalled).toEqual(true)
expect(model.outerWasCalled).toEqual(true)
})
it('Should be able to prevent bubbling of bubblable events using the (eventname)Bubble:false option', function () {
var model = {
innerWasCalled: false,
innerDoCall: function () { this.innerWasCalled = true },
outerWasCalled: false,
outerDoCall: function () { this.outerWasCalled = true }
}
testNode.innerHTML = "<div data-bind='event:{click:outerDoCall}'><button data-bind='event:{click:innerDoCall}, clickBubble:false'>hey</button></div>"
applyBindings(model, testNode)
triggerEvent(testNode.childNodes[0].childNodes[0], 'click')
expect(model.innerWasCalled).toEqual(true)
expect(model.outerWasCalled).toEqual(false)
})
it('Should be able to supply handler params using "bind" helper', function () {
// Using "bind" like this just eliminates the function literal wrapper - it's purely stylistic
var didCallHandler = false, someObj = {}
var myHandler = function () {
expect(this).toEqual(someObj)
expect(arguments.length).toEqual(5)
// First x args will be the ones you bound
expect(arguments[0]).toEqual(123)
expect(arguments[1]).toEqual('another')
expect(arguments[2].something).toEqual(true)
// Then you get the args we normally pass to handlers, i.e., the model then the event
expect(arguments[3]).toEqual(viewModel)
expect(arguments[4].type).toEqual('mouseover')
didCallHandler = true
}
testNode.innerHTML = "<button data-bind='event:{ mouseover: myHandler.bind(someObj, 123, \"another\", { something: true }) }'>hey</button>"
var viewModel = { myHandler: myHandler, someObj: someObj }
applyBindings(viewModel, testNode)
triggerEvent(testNode.childNodes[0], 'mouseover')
expect(didCallHandler).toEqual(true)
})
it("ordinarily bubbles and is neither passive nor capturing nore 'once'", function () {
let handlerCalls = 0
testNode.innerHTML = "<a data-bind='event: {click: { handler: fn }}'><b></b></a>"
const fn = (vm, evt) => {
handlerCalls++
expect(evt.eventPhase).toEqual(3) // bubbling
}
applyBindings({ fn }, testNode)
triggerEvent(testNode.childNodes[0].childNodes[0], 'click')
expect(handlerCalls).toEqual(1)
triggerEvent(testNode.childNodes[0].childNodes[0], 'click')
expect(handlerCalls).toEqual(2)
})
it("prevents bubble", function () {
let handlerCalls = 0
testNode.innerHTML = "<a data-bind='click: fn'><b data-bind='event: {click: { bubble: false }}'></b></a>"
const fn = () => handlerCalls++
applyBindings({ fn }, testNode)
triggerEvent(testNode.childNodes[0].childNodes[0], 'click')
expect(handlerCalls).toEqual(0)
})
it('respects the `once` param', function () {
let handlerCalls = 0
testNode.innerHTML = "<a data-bind='event: {click: {handler: fn, once: true}}'></a>"
const fn = () => handlerCalls++
applyBindings({ fn }, testNode)
triggerEvent(testNode.childNodes[0], 'click')
expect(handlerCalls).toEqual(1)
triggerEvent(testNode.childNodes[0], 'click')
expect(handlerCalls).toEqual(1)
})
it('respects the `capture` param', function () {
testNode.innerHTML = "<a data-bind='event: {click: {handler: fn, capture: true}}'><b></b></a>"
const fn = (vm, evt) => {
expect(evt.eventPhase).toEqual(1) // capturing
}
applyBindings({ fn }, testNode)
triggerEvent(testNode.childNodes[0].childNodes[0], 'click')
})
xit('respects the `passive` param', function () {
/**
* This does not appear to be testable. The evt.preventDefault below
* throws an uncatchable error in Chrome 63.
*/
testNode.innerHTML = "<a data-bind='event: {click: {handler: fn, passive: true}}'><b></b></a>"
let preventDefaultThrows = false
const fn = (vm, evt) => {
// test passive
try {
evt.preventDefault()
} catch (e) {
preventDefaultThrows = true
}
}
applyBindings({ fn }, testNode)
triggerEvent(testNode.childNodes[0].childNodes[0], 'click')
expect(preventDefaultThrows).toEqual(true)
})
it("respects the `debounce` property", function () {
jasmine.Clock.useMock()
testNode.innerHTML = "<a data-bind='event: {click: {handler: fn, debounce: 50}}'></a>"
var calls = 0
const fn = () => calls++
applyBindings({ fn }, testNode)
triggerEvent(testNode.childNodes[0], 'click')
triggerEvent(testNode.childNodes[0], 'click')
triggerEvent(testNode.childNodes[0], 'click')
triggerEvent(testNode.childNodes[0], 'click')
triggerEvent(testNode.childNodes[0], 'click')
expect(calls).toEqual(0)
jasmine.Clock.tick(500)
expect(calls).toEqual(1)
})
it("respects the `throttle` property", function () {
jasmine.Clock.useMock()
testNode.innerHTML = "<a data-bind='event: {click: {handler: fn, throttle: 50}}'></a>"
let calls = 0
const fn = () => calls++
applyBindings({ fn }, testNode)
triggerEvent(testNode.childNodes[0], 'click')
expect(calls).toEqual(0)
jasmine.Clock.tick(100)
expect(calls).toEqual(1)
triggerEvent(testNode.childNodes[0], 'click')
expect(calls).toEqual(1)
jasmine.Clock.tick(100)
expect(calls).toEqual(2)
triggerEvent(testNode.childNodes[0], 'click')
triggerEvent(testNode.childNodes[0], 'click')
triggerEvent(testNode.childNodes[0], 'click')
expect(calls).toEqual(2)
jasmine.Clock.tick(100)
expect(calls).toEqual(3)
})
})
describe('Binding: on.', function () {
beforeEach(jasmine.prepareTestNode)
beforeEach(function () {
var provider = new DataBindProvider()
options.bindingProviderInstance = provider
provider.bindingHandlers.set(coreBindings)
})
it('invokes argument as a function on event', function () {
var obs = observable(false)
testNode.innerHTML = "<button data-bind='on.click: obs(true)'>hey</button>"
applyBindings({ obs: obs }, testNode)
expect(obs()).toEqual(false)
triggerEvent(testNode.childNodes[0], 'click')
expect(obs()).toEqual(true)
})
}) | the_stack |
import * as gax from 'google-gax';
import { Callback, ClientOptions, LROperation } from 'google-gax';
import { Transform } from 'stream';
import * as protosTypes from '../../protos/firestore_admin_v1_proto_api';
/**
* Operations are created by service `FirestoreAdmin`, but are accessed via
* service `google.longrunning.Operations`.
* @class
* @memberof v1
*/
export declare class FirestoreAdminClient {
private _descriptors;
private _innerApiCalls;
private _pathTemplates;
private _terminated;
auth: gax.GoogleAuth;
operationsClient: gax.OperationsClient;
firestoreAdminStub: Promise<{
[name: string]: Function;
}>;
/**
* Construct an instance of FirestoreAdminClient.
*
* @param {object} [options] - The configuration object. See the subsequent
* parameters for more details.
* @param {object} [options.credentials] - Credentials object.
* @param {string} [options.credentials.client_email]
* @param {string} [options.credentials.private_key]
* @param {string} [options.email] - Account email address. Required when
* using a .pem or .p12 keyFilename.
* @param {string} [options.keyFilename] - Full path to the a .json, .pem, or
* .p12 key downloaded from the Google Developers Console. If you provide
* a path to a JSON file, the projectId option below is not necessary.
* NOTE: .pem and .p12 require you to specify options.email as well.
* @param {number} [options.port] - The port on which to connect to
* the remote host.
* @param {string} [options.projectId] - The project ID from the Google
* Developer's Console, e.g. 'grape-spaceship-123'. We will also check
* the environment variable GCLOUD_PROJECT for your project ID. If your
* app is running in an environment which supports
* {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials},
* your project ID will be detected automatically.
* @param {function} [options.promise] - Custom promise module to use instead
* of native Promises.
* @param {string} [options.apiEndpoint] - The domain name of the
* API remote host.
*/
constructor(opts?: ClientOptions);
/**
* The DNS address for this API service.
*/
static readonly servicePath: string;
/**
* The DNS address for this API service - same as servicePath(),
* exists for compatibility reasons.
*/
static readonly apiEndpoint: string;
/**
* The port for this API service.
*/
static readonly port: number;
/**
* The scopes needed to make gRPC calls for every method defined
* in this service.
*/
static readonly scopes: string[];
getProjectId(): Promise<string>;
getProjectId(callback: Callback<string, undefined, undefined>): void;
getIndex(request: protosTypes.google.firestore.admin.v1.IGetIndexRequest, options?: gax.CallOptions): Promise<[protosTypes.google.firestore.admin.v1.IIndex, protosTypes.google.firestore.admin.v1.IGetIndexRequest | undefined, {} | undefined]>;
getIndex(request: protosTypes.google.firestore.admin.v1.IGetIndexRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.firestore.admin.v1.IIndex, protosTypes.google.firestore.admin.v1.IGetIndexRequest | undefined, {} | undefined>): void;
deleteIndex(request: protosTypes.google.firestore.admin.v1.IDeleteIndexRequest, options?: gax.CallOptions): Promise<[protosTypes.google.protobuf.IEmpty, protosTypes.google.firestore.admin.v1.IDeleteIndexRequest | undefined, {} | undefined]>;
deleteIndex(request: protosTypes.google.firestore.admin.v1.IDeleteIndexRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.protobuf.IEmpty, protosTypes.google.firestore.admin.v1.IDeleteIndexRequest | undefined, {} | undefined>): void;
getField(request: protosTypes.google.firestore.admin.v1.IGetFieldRequest, options?: gax.CallOptions): Promise<[protosTypes.google.firestore.admin.v1.IField, protosTypes.google.firestore.admin.v1.IGetFieldRequest | undefined, {} | undefined]>;
getField(request: protosTypes.google.firestore.admin.v1.IGetFieldRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.firestore.admin.v1.IField, protosTypes.google.firestore.admin.v1.IGetFieldRequest | undefined, {} | undefined>): void;
createIndex(request: protosTypes.google.firestore.admin.v1.ICreateIndexRequest, options?: gax.CallOptions): Promise<[LROperation<protosTypes.google.firestore.admin.v1.IIndex, protosTypes.google.firestore.admin.v1.IIndexOperationMetadata>, protosTypes.google.longrunning.IOperation | undefined, {} | undefined]>;
createIndex(request: protosTypes.google.firestore.admin.v1.ICreateIndexRequest, options: gax.CallOptions, callback: Callback<LROperation<protosTypes.google.firestore.admin.v1.IIndex, protosTypes.google.firestore.admin.v1.IIndexOperationMetadata>, protosTypes.google.longrunning.IOperation | undefined, {} | undefined>): void;
updateField(request: protosTypes.google.firestore.admin.v1.IUpdateFieldRequest, options?: gax.CallOptions): Promise<[LROperation<protosTypes.google.firestore.admin.v1.IField, protosTypes.google.firestore.admin.v1.IFieldOperationMetadata>, protosTypes.google.longrunning.IOperation | undefined, {} | undefined]>;
updateField(request: protosTypes.google.firestore.admin.v1.IUpdateFieldRequest, options: gax.CallOptions, callback: Callback<LROperation<protosTypes.google.firestore.admin.v1.IField, protosTypes.google.firestore.admin.v1.IFieldOperationMetadata>, protosTypes.google.longrunning.IOperation | undefined, {} | undefined>): void;
exportDocuments(request: protosTypes.google.firestore.admin.v1.IExportDocumentsRequest, options?: gax.CallOptions): Promise<[LROperation<protosTypes.google.firestore.admin.v1.IExportDocumentsResponse, protosTypes.google.firestore.admin.v1.IExportDocumentsMetadata>, protosTypes.google.longrunning.IOperation | undefined, {} | undefined]>;
exportDocuments(request: protosTypes.google.firestore.admin.v1.IExportDocumentsRequest, options: gax.CallOptions, callback: Callback<LROperation<protosTypes.google.firestore.admin.v1.IExportDocumentsResponse, protosTypes.google.firestore.admin.v1.IExportDocumentsMetadata>, protosTypes.google.longrunning.IOperation | undefined, {} | undefined>): void;
importDocuments(request: protosTypes.google.firestore.admin.v1.IImportDocumentsRequest, options?: gax.CallOptions): Promise<[LROperation<protosTypes.google.protobuf.IEmpty, protosTypes.google.firestore.admin.v1.IImportDocumentsMetadata>, protosTypes.google.longrunning.IOperation | undefined, {} | undefined]>;
importDocuments(request: protosTypes.google.firestore.admin.v1.IImportDocumentsRequest, options: gax.CallOptions, callback: Callback<LROperation<protosTypes.google.protobuf.IEmpty, protosTypes.google.firestore.admin.v1.IImportDocumentsMetadata>, protosTypes.google.longrunning.IOperation | undefined, {} | undefined>): void;
listIndexes(request: protosTypes.google.firestore.admin.v1.IListIndexesRequest, options?: gax.CallOptions): Promise<[protosTypes.google.firestore.admin.v1.IIndex[], protosTypes.google.firestore.admin.v1.IListIndexesRequest | null, protosTypes.google.firestore.admin.v1.IListIndexesResponse]>;
listIndexes(request: protosTypes.google.firestore.admin.v1.IListIndexesRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.firestore.admin.v1.IIndex[], protosTypes.google.firestore.admin.v1.IListIndexesRequest | null, protosTypes.google.firestore.admin.v1.IListIndexesResponse>): void;
/**
* Equivalent to {@link listIndexes}, but returns a NodeJS Stream object.
*
* This fetches the paged responses for {@link listIndexes} continuously
* and invokes the callback registered for 'data' event for each element in the
* responses.
*
* The returned object has 'end' method when no more elements are required.
*
* autoPaginate option will be ignored.
*
* @see {@link https://nodejs.org/api/stream.html}
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. A parent name of the form
* `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}`
* @param {string} request.filter
* The filter to apply to list results.
* @param {number} request.pageSize
* The number of results to return.
* @param {string} request.pageToken
* A page token, returned from a previous call to
* [FirestoreAdmin.ListIndexes][google.firestore.admin.v1.FirestoreAdmin.ListIndexes], that may be used to get the next
* page of results.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Stream}
* An object stream which emits an object representing [Index]{@link google.firestore.admin.v1.Index} on 'data' event.
*/
listIndexesStream(request?: protosTypes.google.firestore.admin.v1.IListIndexesRequest, options?: gax.CallOptions | {}): Transform;
listFields(request: protosTypes.google.firestore.admin.v1.IListFieldsRequest, options?: gax.CallOptions): Promise<[protosTypes.google.firestore.admin.v1.IField[], protosTypes.google.firestore.admin.v1.IListFieldsRequest | null, protosTypes.google.firestore.admin.v1.IListFieldsResponse]>;
listFields(request: protosTypes.google.firestore.admin.v1.IListFieldsRequest, options: gax.CallOptions, callback: Callback<protosTypes.google.firestore.admin.v1.IField[], protosTypes.google.firestore.admin.v1.IListFieldsRequest | null, protosTypes.google.firestore.admin.v1.IListFieldsResponse>): void;
/**
* Equivalent to {@link listFields}, but returns a NodeJS Stream object.
*
* This fetches the paged responses for {@link listFields} continuously
* and invokes the callback registered for 'data' event for each element in the
* responses.
*
* The returned object has 'end' method when no more elements are required.
*
* autoPaginate option will be ignored.
*
* @see {@link https://nodejs.org/api/stream.html}
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.parent
* Required. A parent name of the form
* `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}`
* @param {string} request.filter
* The filter to apply to list results. Currently,
* [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields] only supports listing fields
* that have been explicitly overridden. To issue this query, call
* [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields] with the filter set to
* `indexConfig.usesAncestorConfig:false`.
* @param {number} request.pageSize
* The number of results to return.
* @param {string} request.pageToken
* A page token, returned from a previous call to
* [FirestoreAdmin.ListFields][google.firestore.admin.v1.FirestoreAdmin.ListFields], that may be used to get the next
* page of results.
* @param {object} [options]
* Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
* @returns {Stream}
* An object stream which emits an object representing [Field]{@link google.firestore.admin.v1.Field} on 'data' event.
*/
listFieldsStream(request?: protosTypes.google.firestore.admin.v1.IListFieldsRequest, options?: gax.CallOptions | {}): Transform;
/**
* Return a fully-qualified collectiongroup resource name string.
*
* @param {string} project
* @param {string} database
* @param {string} collection
* @returns {string} Resource name string.
*/
collectiongroupPath(project: string, database: string, collection: string): string;
/**
* Parse the project from CollectionGroup resource.
*
* @param {string} collectiongroupName
* A fully-qualified path representing CollectionGroup resource.
* @returns {string} A string representing the project.
*/
matchProjectFromCollectionGroupName(collectiongroupName: string): string;
/**
* Parse the database from CollectionGroup resource.
*
* @param {string} collectiongroupName
* A fully-qualified path representing CollectionGroup resource.
* @returns {string} A string representing the database.
*/
matchDatabaseFromCollectionGroupName(collectiongroupName: string): string;
/**
* Parse the collection from CollectionGroup resource.
*
* @param {string} collectiongroupName
* A fully-qualified path representing CollectionGroup resource.
* @returns {string} A string representing the collection.
*/
matchCollectionFromCollectionGroupName(collectiongroupName: string): string;
/**
* Return a fully-qualified index resource name string.
*
* @param {string} project
* @param {string} database
* @param {string} collection
* @param {string} index
* @returns {string} Resource name string.
*/
indexPath(project: string, database: string, collection: string, index: string): string;
/**
* Parse the project from Index resource.
*
* @param {string} indexName
* A fully-qualified path representing Index resource.
* @returns {string} A string representing the project.
*/
matchProjectFromIndexName(indexName: string): string;
/**
* Parse the database from Index resource.
*
* @param {string} indexName
* A fully-qualified path representing Index resource.
* @returns {string} A string representing the database.
*/
matchDatabaseFromIndexName(indexName: string): string;
/**
* Parse the collection from Index resource.
*
* @param {string} indexName
* A fully-qualified path representing Index resource.
* @returns {string} A string representing the collection.
*/
matchCollectionFromIndexName(indexName: string): string;
/**
* Parse the index from Index resource.
*
* @param {string} indexName
* A fully-qualified path representing Index resource.
* @returns {string} A string representing the index.
*/
matchIndexFromIndexName(indexName: string): string;
/**
* Return a fully-qualified field resource name string.
*
* @param {string} project
* @param {string} database
* @param {string} collection
* @param {string} field
* @returns {string} Resource name string.
*/
fieldPath(project: string, database: string, collection: string, field: string): string;
/**
* Parse the project from Field resource.
*
* @param {string} fieldName
* A fully-qualified path representing Field resource.
* @returns {string} A string representing the project.
*/
matchProjectFromFieldName(fieldName: string): string;
/**
* Parse the database from Field resource.
*
* @param {string} fieldName
* A fully-qualified path representing Field resource.
* @returns {string} A string representing the database.
*/
matchDatabaseFromFieldName(fieldName: string): string;
/**
* Parse the collection from Field resource.
*
* @param {string} fieldName
* A fully-qualified path representing Field resource.
* @returns {string} A string representing the collection.
*/
matchCollectionFromFieldName(fieldName: string): string;
/**
* Parse the field from Field resource.
*
* @param {string} fieldName
* A fully-qualified path representing Field resource.
* @returns {string} A string representing the field.
*/
matchFieldFromFieldName(fieldName: string): string;
/**
* Return a fully-qualified database resource name string.
*
* @param {string} project
* @param {string} database
* @returns {string} Resource name string.
*/
databasePath(project: string, database: string): string;
/**
* Parse the project from Database resource.
*
* @param {string} databaseName
* A fully-qualified path representing Database resource.
* @returns {string} A string representing the project.
*/
matchProjectFromDatabaseName(databaseName: string): string;
/**
* Parse the database from Database resource.
*
* @param {string} databaseName
* A fully-qualified path representing Database resource.
* @returns {string} A string representing the database.
*/
matchDatabaseFromDatabaseName(databaseName: string): string;
/**
* Terminate the GRPC channel and close the client.
*
* The client will no longer be usable and all future behavior is undefined.
*/
close(): Promise<void>;
} | the_stack |
// Note: replicate changes to all overloads in both definition and test file
// Note: keep both static and instance members inline (so similar)
// Note: try to maintain the ordering and separators, and keep to the pattern
import * as Bluebird from "bluebird";
let obj: object = {};
let bool = false;
let num = 0;
let str = '';
let err: Error = new Error();
let x: any = 0;
let f: (...args: any[]) => any = () => {};
let asyncfunc: (...args: any[]) => Bluebird<any>;
let arr: any[];
let exp: RegExp;
let anyArr: any[];
let strArr: string[];
let numArr: number[];
// - - - - - - - - - - - - - - - - -
let value: any;
let reason: any;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
interface Foo {
foo(): string;
}
interface Bar {
bar(): string;
}
interface Baz {
baz(): string;
}
interface Qux {
qux: string;
}
// - - - - - - - - - - - - - - - - -
interface StrFooMap {
[key: string]: Foo;
}
interface StrBarMap {
[key: string]: Bar;
}
// - - - - - - - - - - - - - - - - -
interface StrFooArrMap {
[key: string]: Foo[];
}
interface StrBarArrMap {
[key: string]: Bar[];
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
let foo: Foo = { foo() { return 'foo'; } };
let bar: Bar = { bar() { return 'bar'; } };
let baz: Baz = { baz() { return 'baz'; } };
let qux: Qux = { qux: 'quix' };
let fooArr: Foo[] = [foo];
let barArr: Bar[];
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
let numProm: Bluebird<number>;
let strProm: Bluebird<string>;
let anyProm: Bluebird<any>;
let boolProm: Bluebird<boolean>;
let objProm: Bluebird<object> = Bluebird.resolve(obj);
let voidProm: Bluebird<void>;
let fooProm: Bluebird<Foo> = Bluebird.resolve(foo);
let barProm: Bluebird<Bar> = Bluebird.resolve(bar);
let fooOrBarProm: Bluebird<Foo | Bar>;
let bazProm: Bluebird<Baz> = Bluebird.resolve(baz);
let quxProm: Bluebird<Qux> = Bluebird.resolve(qux);
// - - - - - - - - - - - - - - - - -
let numThen: PromiseLike<number>;
let strThen: PromiseLike<string>;
let anyThen: PromiseLike<any>;
let boolThen: PromiseLike<boolean>;
let objThen: PromiseLike<object>;
let voidThen: PromiseLike<void>;
let fooThen: PromiseLike<Foo> = fooProm;
let barThen: PromiseLike<Bar> = barProm;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
let numArrProm: Bluebird<number[]>;
let strArrProm: Bluebird<string[]>;
let anyArrProm: Bluebird<any[]>;
let fooArrProm: Bluebird<Foo[]> = Bluebird.resolve(fooArr);
let barArrProm: Bluebird<Bar[]>;
let fooOrNullArrProm: Bluebird<Array<Foo | null>> = Bluebird.resolve(fooArr);
// - - - - - - - - - - - - - - - - -
let numArrThen: PromiseLike<number[]>;
let strArrThen: PromiseLike<string[]>;
let anyArrThen: PromiseLike<any[]>;
let fooArrThen: PromiseLike<Foo[]> = fooArrProm;
let barArrThen: PromiseLike<Bar[]>;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
let numPromArr: Array<Bluebird<number>>;
let strPromArr: Array<Bluebird<string>>;
let anyPromArr: Array<Bluebird<any>>;
let fooPromArr: Array<Bluebird<Foo>>;
let barPromArr: Array<Bluebird<Bar>>;
// - - - - - - - - - - - - - - - - -
let numThenArr: Array<PromiseLike<number>>;
let strThenArr: Array<PromiseLike<string>>;
let anyThenArr: Array<PromiseLike<any>>;
let fooThenArr: Array<PromiseLike<Foo>> = [fooThen];
let barThenArr: Array<PromiseLike<Bar>>;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// booya!
let fooThenArrThen: PromiseLike<Array<PromiseLike<Foo>>> = Bluebird.resolve(fooThenArr);
let fooResolver: Bluebird.Resolver<Foo>;
let fooInspection: Bluebird.Inspection<Foo>;
let fooInspectionPromise: Bluebird<Bluebird.Inspection<Foo>>;
let fooInspectionArrProm: Bluebird<Array<Bluebird.Inspection<Foo>>>;
let BlueBird: typeof Bluebird;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
let nativeFooProm: Promise<Foo>;
let nativeBarProm: Promise<Bar>;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
let version: string = Bluebird.version;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
let nodeCallbackFunc = (callback: (err: any, result: string) => void) => {};
let nodeCallbackFuncErrorOnly = (callback: (err: any) => void) => {};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooThen = fooProm;
barThen = barProm;
nativeFooProm = fooProm;
nativeBarProm = barProm;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = new Bluebird((resolve: (value: Foo) => void, reject: (reason: any) => void) => {
if (bool) {
resolve(foo);
} else {
reject(new Error(str));
}
});
fooProm = new Bluebird((resolve: (value: Foo) => void) => {
if (bool) {
resolve(foo);
}
});
// - - - - - - - - - - - - - - - - - - - - - - -
// needs a hint when used untyped?
fooProm = new Bluebird<Foo>((resolve, reject) => {
if (bool) {
resolve(fooThen);
} else {
reject(new Error(str));
}
});
fooProm = new Bluebird<Foo>((resolve) => {
resolve(fooThen);
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooInspectionPromise = fooProm.reflect();
fooInspectionPromise.then(value => {
fooInspection = value;
bool = fooInspection.isFulfilled();
bool = fooInspection.isRejected();
bool = fooInspection.isPending();
foo = fooInspection.value();
x = fooInspection.reason();
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barProm = fooProm.then((value: Foo) => {
return bar;
}, (reason: any) => {
return bar;
});
barProm = fooProm.then((value: Foo) => {
return bar;
}, (reason: any) => {
return barProm;
});
// $ExpectType Bluebird<void | Bar>
fooProm.then((value: Foo) => {
return bar;
}, (reason: any) => {
return;
});
// $ExpectType Bluebird<void | Bar>
fooProm.then((value: Foo) => {
return bar;
}, (reason: any) => {
return voidProm;
});
barProm = fooProm.then((value: Foo) => {
return bar;
});
barProm = barProm.then((value: Bar) => {
if (value) return value;
return Bluebird.resolve(bar);
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// $ExpectType Bluebird<void | Foo>
fooProm.catch((reason: any) => {
return;
});
// $ExpectType Bluebird<void | Foo>
fooProm.caught((reason: any) => {
return;
});
// $ExpectType Bluebird<void | Foo>
fooProm.catch((error: any) => {
return true;
}, (reason: any) => {
return;
});
// $ExpectType Bluebird<void | Foo>
fooProm.caught((error: any) => {
return true;
}, (reason: any) => {
return;
});
// $ExpectType Bluebird<void | Foo>
fooProm.catch((reason: any) => {
return voidProm;
});
// $ExpectType Bluebird<void | Foo>
fooProm.caught((reason: any) => {
return voidProm;
});
// $ExpectType Bluebird<void | Foo>
fooProm.catch((error: any) => {
return true;
}, (reason: any) => {
return voidProm;
});
// $ExpectType Bluebird<void | Foo>
fooProm.caught((error: any) => {
return true;
}, (reason: any) => {
return voidProm;
});
// $ExpectType Bluebird<void | Foo>
fooProm.catch<void | Foo>((reason: any) => { // tslint:disable-line:void-return
// handle multiple valid return types simultaneously
if (foo === null) {
return;
} else if (!reason) {
return voidProm;
} else if (foo) {
return foo;
}
});
fooOrBarProm = fooProm.catch((reason: any) => {
return bar;
});
fooOrBarProm = fooProm.caught((reason: any) => {
return bar;
});
fooOrBarProm = fooProm.catch((error: any) => {
return true;
}, (reason: any) => {
return bar;
});
fooOrBarProm = fooProm.caught((error: any) => {
return true;
}, (reason: any) => {
return bar;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// $ExpectType Bluebird<void | Foo>
fooProm.catch(Error, (reason: any) => {
return;
});
// $ExpectType Bluebird<void | Foo>
fooProm.catch(Bluebird.CancellationError, (reason: any) => {
return;
});
// $ExpectType Bluebird<void | Foo>
fooProm.caught(Error, (reason: any) => {
return;
});
// $ExpectType Bluebird<void | Foo>
fooProm.caught(Bluebird.CancellationError, (reason: any) => {
return;
});
fooOrBarProm = fooProm.catch(Error, (reason: any) => {
return bar;
});
fooOrBarProm = fooProm.catch(Bluebird.CancellationError, (reason: any) => {
return bar;
});
fooOrBarProm = fooProm.caught(Error, (reason: any) => {
return bar;
});
fooOrBarProm = fooProm.caught(Bluebird.CancellationError, (reason: any) => {
return bar;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class CustomError extends Error {
customField: number;
}
// $ExpectType Bluebird<void | Foo>
fooProm.catch(CustomError, reason => {
let a: number = reason.customField;
});
class CustomErrorWithConstructor extends Error {
arg1: boolean;
arg2: number;
constructor(arg1: boolean, arg2: number) {
super();
this.arg1 = arg1;
this.arg2 = arg2;
}
}
// $ExpectType Bluebird<void | Foo>
fooProm.catch(CustomErrorWithConstructor, reason => {
let a: boolean = reason.arg1;
let b: number = reason.arg2;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class CustomError1 extends Error {}
class CustomError2 extends Error {}
class CustomError3 extends Error {}
class CustomError4 extends Error {}
class CustomError5 extends Error {}
// $ExpectType Bluebird<void | Foo>
fooProm.catch(CustomError1, error => {});
// $ExpectType Bluebird<void | Foo>
fooProm.catch(CustomError1, CustomError2, error => {});
// $ExpectType Bluebird<void | Foo>
fooProm.catch(CustomError1, CustomError2, CustomError3, error => {});
// $ExpectType Bluebird<void | Foo>
fooProm.catch(CustomError1, CustomError2, CustomError3, CustomError4, error => {});
// $ExpectType Bluebird<void | Foo>
fooProm.catch(CustomError1, CustomError2, CustomError3, CustomError4, CustomError5, error => {});
const booPredicate1 = (error: CustomError1) => true;
const booPredicate2 = (error: [number]) => true;
const booPredicate3 = (error: string) => true;
const booPredicate4 = (error: object) => true;
const booPredicate5 = (error: any) => true;
// $ExpectType Bluebird<void | Foo>
fooProm.catch(booPredicate1, error => {});
// $ExpectType Bluebird<void | Foo>
fooProm.catch(booPredicate1, booPredicate2, error => {});
// $ExpectType Bluebird<void | Foo>
fooProm.catch(booPredicate1, booPredicate2, booPredicate3, error => {});
// $ExpectType Bluebird<void | Foo>
fooProm.catch(booPredicate1, booPredicate2, booPredicate3, booPredicate4, error => {});
// $ExpectType Bluebird<void | Foo>
fooProm.catch(booPredicate1, booPredicate2, booPredicate3, booPredicate4, booPredicate5, error => {});
const booObject1 = new CustomError1();
const booObject2 = [400, 500];
const booObject3 = ["Error1", "Error2"];
const booObject4 = {code: 400};
const booObject5: any = null;
// $ExpectType Bluebird<void | Foo>
fooProm.catch(booObject1, error => {});
// $ExpectType Bluebird<void | Foo>
fooProm.catch(booObject1, booObject2, error => {});
// $ExpectType Bluebird<void | Foo>
fooProm.catch(booObject1, booObject2, booObject3, error => {});
// $ExpectType Bluebird<void | Foo>
fooProm.catch(booObject1, booObject2, booObject3, booObject4, error => {});
// $ExpectType Bluebird<void | Foo>
fooProm.catch(booObject1, booObject2, booObject3, booObject4, booObject5, error => {});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barProm = fooProm.error((reason: any) => {
return bar;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = fooProm.finally(() => {
// non-Thenable return is ignored
return "foo";
});
fooProm = fooProm.finally(() => {
return fooThen;
});
fooProm = fooProm.finally(() => {
// non-Thenable return is ignored
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = fooProm.lastly(() => {
// non-Thenable return is ignored
return "foo";
});
fooProm = fooProm.lastly(() => {
return fooThen;
});
fooProm = fooProm.lastly(() => {
// non-Thenable return is ignored
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = fooProm.bind(obj);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// $ExpectType void
fooProm.done((value: Foo) => {
return bar;
}, (reason: any) => {
return bar;
});
// $ExpectType void
fooProm.done((value: Foo) => {
return bar;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// $ExpectType void
fooProm.done((value: Foo) => {
return barThen;
}, (reason: any) => {
return barThen;
});
// $ExpectType void
fooProm.done((value: Foo) => {
return barThen;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = fooProm.tap((value: Foo) => {
// non-Thenable return is ignored
return "foo";
});
fooProm = fooProm.tap((value: Foo) => {
return fooThen;
});
fooProm = fooProm.tap((value: Foo) => {
return voidThen;
});
fooProm = fooProm.tap(() => {
// non-Thenable return is ignored
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = fooProm.tapCatch((err) => {
return "foo";
});
fooProm = fooProm.tapCatch(err => {
return Bluebird.resolve("foo");
});
fooProm.tapCatch(CustomError, (err: CustomError) => {
return err.customField;
});
fooProm.tapCatch((e: any) => e instanceof CustomError, (err: CustomError) => {
return err.customField;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = fooProm.delay(num);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = fooProm.timeout(num);
fooProm = fooProm.timeout(num, str);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm.nodeify();
fooProm = fooProm.nodeify((err: any) => { });
fooProm = fooProm.nodeify((err: any, foo?: Foo) => { });
fooProm.nodeify({ spread: true });
fooProm = fooProm.nodeify((err: any) => { }, { spread: true });
fooProm = fooProm.nodeify((err: any, foo?: Foo) => { }, { spread: true });
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// $ExpectType void
fooProm.cancel();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool = fooProm.isCancelled();
bool = fooProm.isFulfilled();
bool = fooProm.isRejected();
bool = fooProm.isPending();
bool = fooProm.isResolved();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
strProm = fooProm.call("foo");
strProm = fooProm.call("foo", 1, 2, 3);
// $ExpectType Bluebird<never>
quxProm.call("qux");
strProm = fooProm.get("foo").then(method => method());
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barProm = fooProm.return(bar);
barProm = fooProm.thenReturn(bar);
voidProm = fooProm.return();
voidProm = fooProm.thenReturn();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooProm
fooProm = fooProm.throw(err);
fooProm = fooProm.thenThrow(err);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooOrBarProm = fooProm.return(foo).catchReturn(bar);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooProm
fooProm = fooProm.catchThrow(err);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
str = fooProm.toString();
obj = fooProm.toJSON();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barProm = fooArrProm.spread((one: Foo, two: Foo, twotwo: Foo) => {
return bar;
});
// - - - - - - - - - - - - - - - - -
barProm = fooArrProm.spread((one: Foo, two: Foo, twotwo: Foo) => {
return barThen;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// $ExpectType Bluebird<Foo[]>
fooArrProm = fooArrProm.all();
// $ExpectType Bluebird<(Foo | null)[]>
fooOrNullArrProm = fooOrNullArrProm.all();
// $ExpectType Bluebird<never>
fooProm.all();
fooProm = fooArrProm.any();
// $ExpectType Bluebird<never>
fooProm.any();
// $ExpectType Bluebird<Foo[]>
fooArrProm = fooArrProm.some(num);
// $ExpectType Bluebird<(Foo | null)[]>
fooOrNullArrProm = fooOrNullArrProm.some(num);
// $ExpectType Bluebird<never>
fooProm.some(num);
fooProm = fooArrProm.race();
// $ExpectType Bluebird<never>
fooProm.race();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
let propsValue: { num: number, str: string };
Bluebird.resolve({ num: 1, str: Bluebird.resolve('a') }).props().then(val => { propsValue = val; });
Bluebird.props({ num: 1, str: Bluebird.resolve('a') }).then(val => { propsValue = val; });
Bluebird.props(Bluebird.props({ num: 1, str: Bluebird.resolve('a') })).then(val => { propsValue = val; });
let propsMapValue: Map<number, string>;
Bluebird.resolve(new Map<number, string>()).props().then(val => { propsMapValue = val; });
Bluebird.resolve(new Map<number, PromiseLike<string>>()).props().then(val => { propsMapValue = val; });
Bluebird.props(new Map<number, string>()).then(val => { propsMapValue = val; });
Bluebird.props(new Map<number, PromiseLike<string>>()).then(val => { propsMapValue = val; });
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Bluebird.all([fooProm, barProm]).then(result => {
foo = result[0];
bar = result[1];
});
Bluebird.all([fooProm, fooProm]).then(result => {
foo = result[0];
foo = result[1];
});
Bluebird.all([fooProm, barProm, bazProm]).then(result => {
foo = result[0];
bar = result[1];
baz = result[2];
});
Bluebird.all([fooProm, barProm, fooProm]).then(result => {
foo = result[0];
bar = result[1];
foo = result[2];
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Bluebird.allSettled([fooProm, barProm]).then(result => {
foo = result[0].value();
bar = result[1].value();
});
Bluebird.allSettled([fooProm, fooProm]).then(result => {
foo = result[0].value();
foo = result[1].value();
});
Bluebird.allSettled([fooProm, barProm, bazProm]).then(result => {
foo = result[0].value();
bar = result[1].value();
baz = result[2].value();
});
Bluebird.allSettled([fooProm, barProm, fooProm]).then(result => {
foo = result[0].value();
bar = result[1].value();
foo = result[2].value();
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barArrProm = fooArrProm.map((item: Foo, index: number, arrayLength: number) => {
return bar;
});
barArrProm = fooArrProm.map((item: Foo) => {
return bar;
});
barArrProm = fooArrProm.map((item: Foo, index: number, arrayLength: number) => {
return bar;
}, {
concurrency: 1
});
barArrProm = fooArrProm.map((item: Foo) => {
return bar;
}, {
concurrency: 1
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barArrProm = fooArrProm.mapSeries((item: Foo, index: number, arrayLength: number) => {
return bar;
});
barArrProm = fooArrProm.mapSeries((item: Foo) => {
return bar;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barProm = fooArrProm.reduce((memo: Bar, item: Foo, index: number, arrayLength: number) => {
return memo;
});
barProm = fooArrProm.reduce((memo: Bar, item: Foo) => {
return memo;
}, bar);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooArrProm = fooArrProm.filter((item: Foo, index: number, arrayLength: number) => {
return bool;
});
fooArrProm = fooArrProm.filter((item: Foo) => {
return bool;
});
fooArrProm = fooArrProm.filter((item: Foo, index: number, arrayLength: number) => {
return bool;
}, {
concurrency: 1
});
fooArrProm = fooArrProm.filter((item: Foo) => {
return bool;
}, {
concurrency: 1
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooArrProm = fooArrProm.each((item: Foo): Bar => bar);
fooArrProm = fooArrProm.each((item: Foo, index: number) => index ? bar : null);
fooArrProm = fooArrProm.each((item: Foo, index: number, arrayLength: number): Bar => bar);
fooArrProm = fooArrProm.each((item: Foo, index: number, arrayLength: number): Bluebird<Bar> => barProm);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = new Bluebird.Promise<Foo>((resolve, reject) => {
resolve(foo);
});
fooProm = Bluebird.Promise.try<Foo>(() => {
return foo;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function getMaybePromise(): Foo|Bluebird<Foo> {
return foo;
}
fooProm = Bluebird.try(() => {
return getMaybePromise();
});
fooProm = Bluebird.try<Foo>(() => {
return getMaybePromise();
});
fooProm = Bluebird.try(() => {
return foo;
});
// - - - - - - - - - - - - - - - - -
fooProm = Bluebird.try(() => {
return fooThen;
});
// - - - - - - - - - - - - - - - - -
fooProm = Bluebird.try(() => {
if (!!fooProm) {
return fooProm;
}
return foo;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = Bluebird.attempt(() => {
return getMaybePromise();
});
fooProm = Bluebird.attempt<Foo>(() => {
return getMaybePromise();
});
fooProm = Bluebird.attempt(() => {
return foo;
});
// - - - - - - - - - - - - - - - - -
fooProm = Bluebird.attempt(() => {
if (!!fooProm) {
return fooProm;
}
return foo;
});
// - - - - - - - - - - - - - - - - -
fooProm = Bluebird.attempt(() => {
return fooThen;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
asyncfunc = Bluebird.method(() => {});
{
const noArg: () => Bluebird<void> = Bluebird.method(() => {});
const oneArg: (x1: number) => Bluebird<void> = Bluebird.method((x1: number) => {});
const twoArg: (x1: number, x2: string) => Bluebird<void> = Bluebird.method((x1: number, x2: string) => {});
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = Bluebird.resolve(foo);
fooProm = Bluebird.resolve(fooThen);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
voidProm = Bluebird.reject(reason);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooResolver = Bluebird.defer<Foo>();
fooResolver.resolve(foo);
fooResolver.reject(err);
fooResolver.callback = (err: any, value: Foo) => {};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooProm = Bluebird.cast(foo);
fooProm = Bluebird.cast(fooThen);
voidProm = Bluebird.bind(x);
bool = Bluebird.is(value);
Bluebird.longStackTraces();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// TODO enable delay
fooProm = Bluebird.delay(num, fooThen);
fooProm = Bluebird.delay(num, foo);
voidProm = Bluebird.delay(num);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
asyncfunc = Bluebird.promisify(f);
asyncfunc = Bluebird.promisify(f, obj);
obj = Bluebird.promisifyAll(obj);
anyProm = Bluebird.fromNode(nodeCallbackFunc);
anyProm = Bluebird.fromNode(nodeCallbackFuncErrorOnly);
anyProm = Bluebird.fromNode(nodeCallbackFunc, {multiArgs : true});
anyProm = Bluebird.fromNode(nodeCallbackFuncErrorOnly, {multiArgs : true});
anyProm = Bluebird.fromCallback(nodeCallbackFunc);
anyProm = Bluebird.fromCallback(nodeCallbackFuncErrorOnly);
anyProm = Bluebird.fromCallback(nodeCallbackFunc, {multiArgs : true});
anyProm = Bluebird.fromCallback(nodeCallbackFuncErrorOnly, {multiArgs : true});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
declare let util: any;
function defaultFilter(name: string, func: (...args: any[]) => any) {
return util.isIdentifier(name) &&
name.charAt(0) !== "_" &&
!util.isClass(func);
}
function DOMPromisifier(originalMethod: (...args: any[]) => any) {
// return a function
return function promisified(this: object, ...args: any[]) {
// which returns a promise
return new Bluebird((resolve, reject) => {
args.push(resolve, reject);
originalMethod.apply(this, args);
});
};
}
obj = Bluebird.promisifyAll(obj, {
suffix: "",
filter: defaultFilter,
promisifier: DOMPromisifier
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
const generator1 = function*(a: number, b: string) { return "string"; };
const coroutine1 = Bluebird.coroutine<string, number, string>(generator1);
strProm = coroutine1(5, "foo");
const generator2 = function*(a: number, b: string) {
yield foo;
return bar;
};
const coroutine2 = Bluebird.coroutine<Bar, number, string>(generator2);
barProm = coroutine2(5, "foo");
const coroutineCustomYield = Bluebird.coroutine(generator1, { yieldHandler: (value) => "whatever" });
/*
barProm = Bluebird.spawn<number>(f);
*/
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
BlueBird = Bluebird.getNewLibraryCopy();
BlueBird = Bluebird.noConflict();
Bluebird.onPossiblyUnhandledRejection((reason: any) => {});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// TODO expand tests to overloads
fooArrProm = Bluebird.all(fooThenArrThen);
fooArrProm = Bluebird.all(fooArrProm);
fooArrProm = Bluebird.all(fooThenArr);
fooArrProm = Bluebird.all(fooArr);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
objProm = Bluebird.props(objProm);
objProm = Bluebird.props(obj);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// TODO expand tests to overloads
fooProm = Bluebird.any(fooThenArrThen);
fooProm = Bluebird.any(fooArrProm);
fooProm = Bluebird.any(fooThenArr);
fooProm = Bluebird.any(fooArr);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// TODO expand tests to overloads
fooProm = Bluebird.race(fooThenArrThen);
fooProm = Bluebird.race(fooArrProm);
fooProm = Bluebird.race(fooThenArr);
fooProm = Bluebird.race(fooArr);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// TODO expand tests to overloads
fooArrProm = Bluebird.some(fooThenArrThen, num);
fooArrProm = Bluebird.some(fooThenArr, num);
fooArrProm = Bluebird.some(fooArr, num);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooArrProm = Bluebird.join(foo, foo, foo);
fooArrProm = Bluebird.join(fooThen, fooThen, fooThen);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// map()
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooThenArrThen
barArrProm = Bluebird.map(fooThenArrThen, (item: Foo) => {
return bar;
});
barArrProm = Bluebird.map(fooThenArrThen, (item: Foo) => {
return barThen;
});
barArrProm = Bluebird.map(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => {
return bar;
});
barArrProm = Bluebird.map(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => {
return barThen;
});
barArrProm = Bluebird.map(fooThenArrThen, (item: Foo) => {
return bar;
}, {
concurrency: 1
});
barArrProm = Bluebird.map(fooThenArrThen, (item: Foo) => {
return barThen;
}, {
concurrency: 1
});
barArrProm = Bluebird.map(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => {
return bar;
}, {
concurrency: 1
});
barArrProm = Bluebird.map(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => {
return barThen;
}, {
concurrency: 1
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooArrThen
barArrProm = Bluebird.map(fooArrThen, (item: Foo) => {
return bar;
});
barArrProm = Bluebird.map(fooArrThen, (item: Foo) => {
return barThen;
});
barArrProm = Bluebird.map(fooArrThen, (item: Foo, index: number, arrayLength: number) => {
return bar;
});
barArrProm = Bluebird.map(fooArrThen, (item: Foo, index: number, arrayLength: number) => {
return barThen;
});
barArrProm = Bluebird.map(fooArrThen, (item: Foo) => {
return bar;
}, {
concurrency: 1
});
barArrProm = Bluebird.map(fooArrThen, (item: Foo) => {
return barThen;
}, {
concurrency: 1
});
barArrProm = Bluebird.map(fooArrThen, (item: Foo, index: number, arrayLength: number) => {
return bar;
}, {
concurrency: 1
});
barArrProm = Bluebird.map(fooArrThen, (item: Foo, index: number, arrayLength: number) => {
return barThen;
}, {
concurrency: 1
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooThenArr
barArrProm = Bluebird.map(fooThenArr, (item: Foo) => {
return bar;
});
barArrProm = Bluebird.map(fooThenArr, (item: Foo) => {
return barThen;
});
barArrProm = Bluebird.map(fooThenArr, (item: Foo, index: number, arrayLength: number) => {
return bar;
});
barArrProm = Bluebird.map(fooThenArr, (item: Foo, index: number, arrayLength: number) => {
return barThen;
});
barArrProm = Bluebird.map(fooThenArr, (item: Foo) => {
return bar;
}, {
concurrency: 1
});
barArrProm = Bluebird.map(fooThenArr, (item: Foo) => {
return barThen;
}, {
concurrency: 1
});
barArrProm = Bluebird.map(fooThenArr, (item: Foo, index: number, arrayLength: number) => {
return bar;
}, {
concurrency: 1
});
barArrProm = Bluebird.map(fooThenArr, (item: Foo, index: number, arrayLength: number) => {
return barThen;
}, {
concurrency: 1
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooArr
barArrProm = Bluebird.map(fooArr, (item: Foo) => {
return bar;
});
barArrProm = Bluebird.map(fooArr, (item: Foo) => {
return barThen;
});
barArrProm = Bluebird.map(fooArr, (item: Foo, index: number, arrayLength: number) => {
return bar;
});
barArrProm = Bluebird.map(fooArr, (item: Foo, index: number, arrayLength: number) => {
return barThen;
});
barArrProm = Bluebird.map(fooArr, (item: Foo) => {
return bar;
}, {
concurrency: 1
});
barArrProm = Bluebird.map(fooArr, (item: Foo) => {
return barThen;
}, {
concurrency: 1
});
barArrProm = Bluebird.map(fooArr, (item: Foo, index: number, arrayLength: number) => {
return bar;
}, {
concurrency: 1
});
barArrProm = Bluebird.map(fooArr, (item: Foo, index: number, arrayLength: number) => {
return barThen;
}, {
concurrency: 1
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// mapSeries()
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooThenArrThen
barArrProm = Bluebird.mapSeries(fooThenArrThen, (item: Foo) => {
return bar;
});
barArrProm = Bluebird.mapSeries(fooThenArrThen, (item: Foo) => {
return barThen;
});
barArrProm = Bluebird.mapSeries(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => {
return bar;
});
barArrProm = Bluebird.mapSeries(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => {
return barThen;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooArrThen
barArrProm = Bluebird.mapSeries(fooArrThen, (item: Foo) => {
return bar;
});
barArrProm = Bluebird.mapSeries(fooArrThen, (item: Foo) => {
return barThen;
});
barArrProm = Bluebird.mapSeries(fooArrThen, (item: Foo, index: number, arrayLength: number) => {
return bar;
});
barArrProm = Bluebird.mapSeries(fooArrThen, (item: Foo, index: number, arrayLength: number) => {
return barThen;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooThenArr
barArrProm = Bluebird.mapSeries(fooThenArr, (item: Foo) => {
return bar;
});
barArrProm = Bluebird.mapSeries(fooThenArr, (item: Foo) => {
return barThen;
});
barArrProm = Bluebird.mapSeries(fooThenArr, (item: Foo, index: number, arrayLength: number) => {
return bar;
});
barArrProm = Bluebird.mapSeries(fooThenArr, (item: Foo, index: number, arrayLength: number) => {
return barThen;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooArr
barArrProm = Bluebird.mapSeries(fooArr, (item: Foo) => {
return bar;
});
barArrProm = Bluebird.mapSeries(fooArr, (item: Foo) => {
return barThen;
});
barArrProm = Bluebird.mapSeries(fooArr, (item: Foo, index: number, arrayLength: number) => {
return bar;
});
barArrProm = Bluebird.mapSeries(fooArr, (item: Foo, index: number, arrayLength: number) => {
return barThen;
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// reduce()
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooThenArrThen
barProm = Bluebird.reduce(fooThenArrThen, (memo: Bar, item: Foo) => {
return memo;
}, bar);
barProm = Bluebird.reduce(fooThenArrThen, (memo: Bar, item: Foo) => {
return barThen;
}, bar);
barProm = Bluebird.reduce(fooThenArrThen, (memo: Bar, item: Foo, index: number, arrayLength: number) => {
return memo;
}, bar);
barProm = Bluebird.reduce(fooThenArrThen, (memo: Bar, item: Foo, index: number, arrayLength: number) => {
return barThen;
}, bar);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooArrThen
barProm = Bluebird.reduce(fooArrThen, (memo: Bar, item: Foo) => {
return memo;
}, bar);
barProm = Bluebird.reduce(fooArrThen, (memo: Bar, item: Foo) => {
return barThen;
}, bar);
barProm = Bluebird.reduce(fooArrThen, (memo: Bar, item: Foo, index: number, arrayLength: number) => {
return memo;
}, bar);
barProm = Bluebird.reduce(fooArrThen, (memo: Bar, item: Foo, index: number, arrayLength: number) => {
return barThen;
}, bar);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooThenArr
barProm = Bluebird.reduce(fooThenArr, (memo: Bar, item: Foo) => {
return memo;
}, bar);
barProm = Bluebird.reduce(fooThenArr, (memo: Bar, item: Foo) => {
return barThen;
}, bar);
barProm = Bluebird.reduce(fooThenArr, (memo: Bar, item: Foo, index: number, arrayLength: number) => {
return memo;
}, bar);
barProm = Bluebird.reduce(fooThenArr, (memo: Bar, item: Foo, index: number, arrayLength: number) => {
return barThen;
}, bar);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooArr
barProm = Bluebird.reduce(fooArr, (memo: Bar, item: Foo) => {
return memo;
}, bar);
barProm = Bluebird.reduce(fooArr, (memo: Bar, item: Foo) => {
return barThen;
}, bar);
barProm = Bluebird.reduce(fooArr, (memo: Bar, item: Foo, index: number, arrayLength: number) => {
return memo;
}, bar);
barProm = Bluebird.reduce(fooArr, (memo: Bar, item: Foo, index: number, arrayLength: number) => {
return barThen;
}, bar);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// filter()
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooThenArrThen
fooArrProm = Bluebird.filter(fooThenArrThen, (item: Foo) => {
return bool;
});
fooArrProm = Bluebird.filter(fooThenArrThen, (item: Foo) => {
return boolThen;
});
fooArrProm = Bluebird.filter(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => {
return bool;
});
fooArrProm = Bluebird.filter(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => {
return boolThen;
});
fooArrProm = Bluebird.filter(fooThenArrThen, (item: Foo) => {
return bool;
}, {
concurrency: 1
});
fooArrProm = Bluebird.filter(fooThenArrThen, (item: Foo) => {
return boolThen;
}, {
concurrency: 1
});
fooArrProm = Bluebird.filter(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => {
return bool;
}, {
concurrency: 1
});
fooArrProm = Bluebird.filter(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => {
return boolThen;
}, {
concurrency: 1
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooArrThen
fooArrProm = Bluebird.filter(fooArrThen, (item: Foo) => {
return bool;
});
fooArrProm = Bluebird.filter(fooArrThen, (item: Foo) => {
return boolThen;
});
fooArrProm = Bluebird.filter(fooArrThen, (item: Foo, index: number, arrayLength: number) => {
return bool;
});
fooArrProm = Bluebird.filter(fooArrThen, (item: Foo, index: number, arrayLength: number) => {
return boolThen;
});
fooArrProm = Bluebird.filter(fooArrThen, (item: Foo) => {
return bool;
}, {
concurrency: 1
});
fooArrProm = Bluebird.filter(fooArrThen, (item: Foo) => {
return boolThen;
}, {
concurrency: 1
});
fooArrProm = Bluebird.filter(fooArrThen, (item: Foo, index: number, arrayLength: number) => {
return bool;
}, {
concurrency: 1
});
fooArrProm = Bluebird.filter(fooArrThen, (item: Foo, index: number, arrayLength: number) => {
return boolThen;
}, {
concurrency: 1
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooThenArr
fooArrProm = Bluebird.filter(fooThenArr, (item: Foo) => {
return bool;
});
fooArrProm = Bluebird.filter(fooThenArr, (item: Foo) => {
return boolThen;
});
fooArrProm = Bluebird.filter(fooThenArr, (item: Foo, index: number, arrayLength: number) => {
return bool;
});
fooArrProm = Bluebird.filter(fooThenArr, (item: Foo, index: number, arrayLength: number) => {
return boolThen;
});
fooArrProm = Bluebird.filter(fooThenArr, (item: Foo) => {
return bool;
}, {
concurrency: 1
});
fooArrProm = Bluebird.filter(fooThenArr, (item: Foo) => {
return boolThen;
}, {
concurrency: 1
});
fooArrProm = Bluebird.filter(fooThenArr, (item: Foo, index: number, arrayLength: number) => {
return bool;
}, {
concurrency: 1
});
fooArrProm = Bluebird.filter(fooThenArr, (item: Foo, index: number, arrayLength: number) => {
return boolThen;
}, {
concurrency: 1
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooArr
fooArrProm = Bluebird.filter(fooArr, (item: Foo) => {
return bool;
});
fooArrProm = Bluebird.filter(fooArr, (item: Foo) => {
return boolThen;
});
fooArrProm = Bluebird.filter(fooArr, (item: Foo, index: number, arrayLength: number) => {
return bool;
});
fooArrProm = Bluebird.filter(fooArr, (item: Foo, index: number, arrayLength: number) => {
return boolThen;
});
fooArrProm = Bluebird.filter(fooArr, (item: Foo) => {
return bool;
}, {
concurrency: 1
});
fooArrProm = Bluebird.filter(fooArr, (item: Foo) => {
return boolThen;
}, {
concurrency: 1
});
fooArrProm = Bluebird.filter(fooArr, (item: Foo, index: number, arrayLength: number) => {
return bool;
}, {
concurrency: 1
});
fooArrProm = Bluebird.filter(fooArr, (item: Foo, index: number, arrayLength: number) => {
return boolThen;
}, {
concurrency: 1
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// each()
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooThenArrThen
fooArrThen = Bluebird.each(fooThenArrThen, (item: Foo) => bar);
fooArrThen = Bluebird.each(fooThenArrThen, (item: Foo) => barThen);
fooArrThen = Bluebird.each(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => bar);
fooArrThen = Bluebird.each(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => barThen);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooArrThen
fooArrThen = Bluebird.each(fooArrThen, (item: Foo) => bar);
fooArrThen = Bluebird.each(fooArrThen, (item: Foo) => barThen);
fooArrThen = Bluebird.each(fooArrThen, (item: Foo, index: number, arrayLength: number) => bar);
fooArrThen = Bluebird.each(fooArrThen, (item: Foo, index: number, arrayLength: number) => barThen);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooThenArr
fooArrThen = Bluebird.each(fooThenArr, (item: Foo) => bar);
fooArrThen = Bluebird.each(fooThenArr, (item: Foo) => barThen);
fooArrThen = Bluebird.each(fooThenArr, (item: Foo, index: number, arrayLength: number) => bar);
fooArrThen = Bluebird.each(fooThenArr, (item: Foo, index: number, arrayLength: number) => barThen);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// fooArr
fooArrThen = Bluebird.each(fooArr, (item: Foo) => bar);
fooArrThen = Bluebird.each(fooArr, (item: Foo) => barThen);
fooArrThen = Bluebird.each(fooArr, (item: Foo, index: number, arrayLength: number) => bar);
fooArrThen = Bluebird.each(fooArr, (item: Foo, index: number, arrayLength: number) => barThen);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | the_stack |
import {EventEmitter} from "events";
import * as EBML from './EBML';
import * as tools from './tools';
/**
* This is an informal code for reference.
* EBMLReader is a class for getting information to enable seeking Webm recorded by MediaRecorder.
* So please do not use for regular WebM files.
*/
export default class EBMLReader extends EventEmitter {
private metadataloaded: boolean;
private stack: (EBML.MasterElement & EBML.ElementDetail)[];
private chunks: EBML.EBMLElementDetail[];
private segmentOffset: number;
private last2SimpleBlockVideoTrackTimecode: [number, number];
private last2SimpleBlockAudioTrackTimecode: [number, number];
private lastClusterTimecode: number;
private lastClusterPosition: number;
private firstVideoBlockRead: boolean;
private firstAudioBlockRead: boolean;
timecodeScale: number;
metadataSize: number;
metadatas: EBML.EBMLElementDetail[];
private currentTrack: {TrackNumber: number, TrackType: number, DefaultDuration: (number | null), CodecDelay: (number | null) };
private trackTypes: number[]; // equals { [trackID: number]: number };
private trackDefaultDuration: (number | null)[];
private trackCodecDelay: (number | null)[];
private first_video_simpleblock_of_cluster_is_loaded: boolean;
private ended: boolean;
trackInfo: { type: "video" | "audio" | "both"; trackNumber: number; } | { type: "nothing" };
/**
* usefull for thumbnail creation.
*/
use_webp: boolean;
use_duration_every_simpleblock: boolean; // heavy
logging: boolean;
logGroup: string = "";
private hasLoggingStarted: boolean = false;
/**
* usefull for recording chunks.
*/
use_segment_info: boolean;
/** see: https://bugs.chromium.org/p/chromium/issues/detail?id=606000#c22 */
drop_default_duration: boolean;
cues: {CueTrack: number; CueClusterPosition: number; CueTime: number; }[];
constructor(){
super();
this.metadataloaded = false;
this.chunks = [];
this.stack = [];
this.segmentOffset = 0;
this.last2SimpleBlockVideoTrackTimecode = [0, 0];
this.last2SimpleBlockAudioTrackTimecode = [0, 0];
this.lastClusterTimecode = 0;
this.lastClusterPosition = 0;
this.timecodeScale = 1000000; // webm default TimecodeScale is 1ms
this.metadataSize = 0;
this.metadatas = [];
this.cues = [];
this.firstVideoBlockRead = false;
this.firstAudioBlockRead = false;
this.currentTrack = {TrackNumber: -1, TrackType: -1, DefaultDuration: null, CodecDelay: null};
this.trackTypes = [];
this.trackDefaultDuration = [];
this.trackCodecDelay = [];
this.trackInfo = { type: "nothing" };
this.ended = false;
this.logging = false;
this.use_duration_every_simpleblock = false;
this.use_webp = false;
this.use_segment_info = true;
this.drop_default_duration = true;
}
/**
* emit final state.
*/
stop() {
this.ended = true;
this.emit_segment_info();
// clean up any unclosed Master Elements at the end of the stream.
while (this.stack.length) {
this.stack.pop();
if (this.logging) {
console.groupEnd();
}
}
// close main group if set, logging is enabled, and has actually logged anything.
if (this.logging && this.hasLoggingStarted && this.logGroup) {
console.groupEnd();
}
}
/**
* emit chunk info
*/
private emit_segment_info(){
const data = this.chunks;
this.chunks = [];
if(!this.metadataloaded){
this.metadataloaded = true;
this.metadatas = data;
const videoTrackNum = this.trackTypes.indexOf(1); // find first video track
const audioTrackNum = this.trackTypes.indexOf(2); // find first audio track
this.trackInfo = videoTrackNum >= 0 && audioTrackNum >= 0 ? {type: "both", trackNumber: videoTrackNum }
: videoTrackNum >= 0 ? {type: "video", trackNumber: videoTrackNum }
: audioTrackNum >= 0 ? {type: "audio", trackNumber: audioTrackNum }
: {type: "nothing" };
if(!this.use_segment_info){ return; }
this.emit("metadata", {data, metadataSize: this.metadataSize});
}else{
if(!this.use_segment_info){ return; }
const timecode = this.lastClusterTimecode;
const duration = this.duration;
const timecodeScale = this.timecodeScale;
this.emit("cluster", {timecode, data});
this.emit("duration", {timecodeScale, duration});
}
}
read(elm: EBML.EBMLElementDetail){
let drop = false;
if(this.ended){
// reader is finished
return;
}
if(elm.type === "m"){
// 閉じタグの自動挿入
if(elm.isEnd){
this.stack.pop();
}else{
const parent = this.stack[this.stack.length-1];
if(parent != null && parent.level >= elm.level){
// 閉じタグなしでレベルが下がったら閉じタグを挿入
this.stack.pop();
// From http://w3c.github.io/media-source/webm-byte-stream-format.html#webm-media-segments
// This fixes logging for webm streams with Cluster of unknown length and no Cluster closing elements.
if (this.logging){
console.groupEnd();
}
parent.dataEnd = elm.dataEnd;
parent.dataSize = elm.dataEnd - parent.dataStart;
parent.unknownSize = false;
const o = Object.assign({}, parent, {name: parent.name, type: parent.type, isEnd: true});
this.chunks.push(o);
}
this.stack.push(elm);
}
}
if(elm.type === "m" && elm.name == "Segment"){
if(this.segmentOffset != 0) {
console.warn("Multiple segments detected!");
}
this.segmentOffset = elm.dataStart;
this.emit("segment_offset", this.segmentOffset);
}else if(elm.type === "b" && elm.name === "SimpleBlock"){
const {timecode, trackNumber, frames} = tools.ebmlBlock(elm.data);
if(this.trackTypes[trackNumber] === 1){ // trackType === 1 => video track
if(!this.firstVideoBlockRead){
this.firstVideoBlockRead = true;
if(this.trackInfo.type === "both" || this.trackInfo.type === "video"){
const CueTime = this.lastClusterTimecode + timecode;
this.cues.push({CueTrack: trackNumber, CueClusterPosition: this.lastClusterPosition, CueTime});
this.emit("cue_info", {CueTrack: trackNumber, CueClusterPosition: this.lastClusterPosition, CueTime: this.lastClusterTimecode});
this.emit("cue", {CueTrack: trackNumber, CueClusterPosition: this.lastClusterPosition, CueTime});
}
}
this.last2SimpleBlockVideoTrackTimecode = [this.last2SimpleBlockVideoTrackTimecode[1], timecode];
}else if(this.trackTypes[trackNumber] === 2){ // trackType === 2 => audio track
if(!this.firstAudioBlockRead){
this.firstAudioBlockRead = true;
if(this.trackInfo.type === "audio"){
const CueTime = this.lastClusterTimecode + timecode;
this.cues.push({CueTrack: trackNumber, CueClusterPosition: this.lastClusterPosition, CueTime});
this.emit("cue_info", {CueTrack: trackNumber, CueClusterPosition: this.lastClusterPosition, CueTime: this.lastClusterTimecode});
this.emit("cue", {CueTrack: trackNumber, CueClusterPosition: this.lastClusterPosition, CueTime});
}
}
this.last2SimpleBlockAudioTrackTimecode = [this.last2SimpleBlockAudioTrackTimecode[1], timecode];
}
if(this.use_duration_every_simpleblock){
this.emit("duration", {timecodeScale: this.timecodeScale, duration: this.duration});
}
if(this.use_webp){
frames.forEach((frame)=>{
const startcode = frame.slice(3, 6).toString("hex");
if(startcode !== "9d012a"){ return; }; // VP8 の場合
const webpBuf = tools.VP8BitStreamToRiffWebPBuffer(frame);
const webp = new Blob([webpBuf], {type: "image/webp"});
const currentTime = this.duration;
this.emit("webp", {currentTime, webp});
});
}
}else if(elm.type === "m" && elm.name === "Cluster" && elm.isEnd === false){
this.firstVideoBlockRead = false;
this.firstAudioBlockRead = false;
this.emit_segment_info();
this.emit("cluster_ptr", elm.tagStart);
this.lastClusterPosition = elm.tagStart;
}else if(elm.type === "u" && elm.name === "Timecode"){
this.lastClusterTimecode = elm.value;
}else if(elm.type === "u" && elm.name === "TimecodeScale"){
this.timecodeScale = elm.value;
}else if(elm.type === "m" && elm.name === "TrackEntry"){
if(elm.isEnd){
this.trackTypes[this.currentTrack.TrackNumber] = this.currentTrack.TrackType;
this.trackDefaultDuration[this.currentTrack.TrackNumber] = this.currentTrack.DefaultDuration;
this.trackCodecDelay[this.currentTrack.TrackNumber] = this.currentTrack.CodecDelay;
}else{
this.currentTrack = {TrackNumber: -1, TrackType: -1, DefaultDuration: null, CodecDelay: null };
}
}else if(elm.type === "u" && elm.name === "TrackType"){
this.currentTrack.TrackType = elm.value;
}else if(elm.type === "u" && elm.name === "TrackNumber"){
this.currentTrack.TrackNumber = elm.value;
}else if(elm.type === "u" && elm.name === "CodecDelay"){
this.currentTrack.CodecDelay = elm.value;
}else if(elm.type === "u" && elm.name === "DefaultDuration"){
// media source api は DefaultDuration を計算するとバグる。
// https://bugs.chromium.org/p/chromium/issues/detail?id=606000#c22
// chrome 58 ではこれを回避するために DefaultDuration 要素を抜き取った。
// chrome 58 以前でもこのタグを抜き取ることで回避できる
if(this.drop_default_duration){
console.warn("DefaultDuration detected!, remove it");
drop = true;
}else{
this.currentTrack.DefaultDuration = elm.value;
}
}else if(elm.name === "unknown"){
console.warn(elm);
}
if(!this.metadataloaded && elm.dataEnd > 0){
this.metadataSize = elm.dataEnd;
}
if(!drop){ this.chunks.push(elm); }
if(this.logging){ this.put(elm); }
}
/**
* DefaultDuration が定義されている場合は最後のフレームのdurationも考慮する
* 単位 timecodeScale
*
* !!! if you need duration with seconds !!!
* ```js
* const nanosec = reader.duration * reader.timecodeScale;
* const sec = nanosec / 1000 / 1000 / 1000;
* ```
*/
get duration(){
if(this.trackInfo.type === "nothing"){
console.warn("no video, no audio track");
return 0;
}
// defaultDuration は 生の nano sec
let defaultDuration = 0;
// nanoseconds
let codecDelay = 0;
let lastTimecode = 0;
const _defaultDuration = this.trackDefaultDuration[this.trackInfo.trackNumber];
if(typeof _defaultDuration === "number"){
defaultDuration = _defaultDuration;
}else{
// https://bugs.chromium.org/p/chromium/issues/detail?id=606000#c22
// default duration がないときに使う delta
if(this.trackInfo.type === "both"){
if(this.last2SimpleBlockAudioTrackTimecode[1] > this.last2SimpleBlockVideoTrackTimecode[1]){
// audio diff
defaultDuration = (this.last2SimpleBlockAudioTrackTimecode[1] - this.last2SimpleBlockAudioTrackTimecode[0]) * this.timecodeScale;
// audio delay
const delay = this.trackCodecDelay[this.trackTypes.indexOf(2)]; // 2 => audio
if(typeof delay === "number"){ codecDelay = delay; }
// audio timecode
lastTimecode = this.last2SimpleBlockAudioTrackTimecode[1];
}else{
// video diff
defaultDuration = (this.last2SimpleBlockVideoTrackTimecode[1] - this.last2SimpleBlockVideoTrackTimecode[0]) * this.timecodeScale;
// video delay
const delay = this.trackCodecDelay[this.trackTypes.indexOf(1)]; // 1 => video
if(typeof delay === "number"){ codecDelay = delay; }
// video timecode
lastTimecode = this.last2SimpleBlockVideoTrackTimecode[1];
}
}else if(this.trackInfo.type === "video"){
defaultDuration = (this.last2SimpleBlockVideoTrackTimecode[1] - this.last2SimpleBlockVideoTrackTimecode[0]) * this.timecodeScale;
const delay = this.trackCodecDelay[this.trackInfo.trackNumber]; // 2 => audio
if(typeof delay === "number"){ codecDelay = delay; }
lastTimecode = this.last2SimpleBlockVideoTrackTimecode[1];
}else if(this.trackInfo.type === "audio"){
defaultDuration = (this.last2SimpleBlockAudioTrackTimecode[1] - this.last2SimpleBlockAudioTrackTimecode[0]) * this.timecodeScale;
const delay = this.trackCodecDelay[this.trackInfo.trackNumber]; // 1 => video
if(typeof delay === "number"){ codecDelay = delay; }
lastTimecode = this.last2SimpleBlockAudioTrackTimecode[1];
}// else { not reached }
}
// convert to timecodescale
const duration_nanosec = ((this.lastClusterTimecode + lastTimecode) * this.timecodeScale) + defaultDuration - codecDelay;
const duration = duration_nanosec / this.timecodeScale;
return Math.floor(duration);
}
/**
* @deprecated
* emit on every segment
* https://www.matroska.org/technical/specs/notes.html#Position_References
*/
addListener(event: "segment_offset", listener: (ev: number )=> void): this;
/**
* @deprecated
* emit on every cluster element start.
* Offset byte from __file start__. It is not an offset from the Segment element.
*/
addListener(event: "cluster_ptr", listener: (ev: number )=> void): this;
/** @deprecated
* emit on every cue point for cluster to create seekable webm file from MediaRecorder
* */
addListener(event: "cue_info", listener: (ev: CueInfo )=> void): this;
/** emit on every cue point for cluster to create seekable webm file from MediaRecorder */
addListener(event: "cue", listener: (ev: CueInfo )=> void): this;
/** latest EBML > Info > TimecodeScale and EBML > Info > Duration to create seekable webm file from MediaRecorder */
addListener(event: "duration", listener: (ev: DurationInfo )=> void): this;
/** EBML header without Cluster Element for recording metadata chunk */
addListener(event: "metadata", listener: (ev: SegmentInfo & {metadataSize: number})=> void): this;
/** emit every Cluster Element and its children for recording chunk */
addListener(event: "cluster", listener: (ev: SegmentInfo & {timecode: number})=> void): this;
/** for thumbnail */
addListener(event: "webp", listener: (ev: ThumbnailInfo)=> void): this;
addListener(event: string, listener: (ev: any)=> void): this {
return super.addListener(event, listener);
}
put(elm: EBML.EBMLElementDetail) {
if (!this.hasLoggingStarted) {
this.hasLoggingStarted = true;
if (this.logging && this.logGroup) {
console.groupCollapsed(this.logGroup);
}
}
if(elm.type === "m"){
if(elm.isEnd){
console.groupEnd();
}else{
console.group(elm.name+":"+elm.tagStart);
}
}else if(elm.type === "b"){
// for debug
//if(elm.name === "SimpleBlock"){
//const o = EBML.tools.ebmlBlock(elm.value);
//console.log(elm.name, elm.type, o.trackNumber, o.timecode);
//}else{
console.log(elm.name, elm.type);
//}
}else{
console.log(elm.name, elm.tagStart, elm.type, elm.value);
}
}
}
/** CueClusterPosition: Offset byte from __file start__. It is not an offset from the Segment element. */
export interface CueInfo {CueTrack: number; CueClusterPosition: number; CueTime: number; };
export interface SegmentInfo {data: EBML.EBMLElementDetail[];};
export interface DurationInfo {duration: number; timecodeScale: number;};
export interface ThumbnailInfo {webp: Blob; currentTime: number;}; | the_stack |
import $ from "jquery";
import * as d3 from "d3";
import * as color from "color";
import { PersistentState } from "./lib/savedstate";
import { categoricalColorScheme } from "./lib/categoricalcolors";
import { d3_scale_percentile, d3_scale_timestamp, scale_add_outliers, is_special_numeric, d3_scale_categorical, get_numeric_values_sorted } from "./lib/d3_scales";
import { Datapoint, ParamType, HiPlotValueDef } from "./types";
export interface ParamDef extends HiPlotValueDef {
name: string,
optional: boolean,
numeric: boolean,
distinct_values: Array<any>,
type_options: Array<ParamType>,
__val2color?: {[k: string]: any};
__colorscale?: any;
__colormap?: any;
}
function get_min_max_for_numeric_scale(pd: ParamDef): [number, number] {
var min = pd.force_value_min;
var max = pd.force_value_max;
pd.distinct_values.forEach(function(value: any) {
const parsed = parseFloat(value);
if (is_special_numeric(parsed)) {
return;
}
if (min === null || parsed < min) {
min = parsed;
}
if (max === null || parsed > max) {
max = parsed;
}
});
return [min, max];
}
function has_inf_or_nans(pd: ParamDef): boolean {
for (var i = 0; i < pd.distinct_values.length; ++i) {
const parsed = parseFloat(pd.distinct_values[i]);
if (is_special_numeric(parsed)) {
return true;
}
}
return false;
}
export function create_d3_scale_without_outliers(pd: ParamDef): any {
var dv = pd.distinct_values;
if (pd.type == ParamType.CATEGORICAL) {
return d3_scale_categorical(dv);
}
else {
if (pd.type == ParamType.NUMERICPERCENTILE) {
return d3_scale_percentile(dv);
}
const [min, max] = get_min_max_for_numeric_scale(pd);
console.assert(!isNaN(min));
console.assert(!isNaN(max));
console.assert(min <= max);
if (pd.type == ParamType.TIMESTAMP) {
return d3_scale_timestamp().domain([min, max]);
}
if (pd.type == ParamType.NUMERICLOG) {
console.assert(min > 0, `Min value for "${pd.name}" is negative (${min}), can't use log-scale`);
return d3.scaleLog().domain([min, max]);
}
console.assert(pd.type == ParamType.NUMERIC, "Unknown variable type " + pd.type);
return d3.scaleLinear().domain([min, max]);
}
}
export function create_d3_scale(pd: ParamDef): any {
var scale = create_d3_scale_without_outliers(pd);
if (has_inf_or_nans(pd) && [ParamType.NUMERIC, ParamType.NUMERICLOG, ParamType.NUMERICPERCENTILE].indexOf(pd.type) >= 0) {
scale = scale_add_outliers(scale);
}
scale.hip_type = pd.type;
scale.hip_num_values = pd.distinct_values.length;
return scale;
}
export interface ScaleDomainRange {
type: ParamType,
brush_extents_normalized: [number, number],
values?: Array<any>,
range?: [number, number],
include_infnans?: boolean;
};
export function scale_pixels_range(scale: any, extents: [number, number]): ScaleDomainRange {
/**
* Converts scale range in pixels back to domain (aka inverts the scale)
*/
console.assert(scale, "No scale provided to `scale_pixels_range`");
console.assert(extents, "No extents provided to `scale_pixels_range`", extents);
const scaleToNorm = d3.scaleLinear().domain(scale.range()).range([0, 1]);
const normalized = [scaleToNorm(extents[0]), scaleToNorm(extents[1])] as [number, number];
switch (scale.hip_type as ParamType) {
case ParamType.CATEGORICAL:
const domain: Array<string> = scale.domain();
const firstIdx = Math.ceil(Math.min(normalized[0], normalized[1]) * (domain.length - 1));
const lastIdx = Math.floor(Math.max(normalized[0], normalized[1]) * (domain.length - 1) + 1);
return {
"type": scale.hip_type,
"brush_extents_normalized": normalized,
"values": domain.slice(firstIdx, lastIdx),
};
case ParamType.NUMERIC:
case ParamType.NUMERICLOG:
case ParamType.NUMERICPERCENTILE:
case ParamType.TIMESTAMP:
const pxlRange: Array<number> = scale.range();
// Small hack to make sure we can always select the extrema
// (considering loss of precision in computations, especially for logscale)
for (var i = 0; i < 2; ++i) {
if (extents[i] == Math.min(...pxlRange)) {
--extents[i];
}
if (extents[i] == Math.max(...pxlRange)) {
++extents[i];
}
}
const range = [scale.invert(extents[0]), scale.invert(extents[1])] as [number, number];
return {
"type": scale.hip_type,
"brush_extents_normalized": normalized,
"range": range,
"include_infnans": extents[0] <= scale(Infinity) && scale(Infinity) <= extents[1]
};
}
}
function compute_val2color(pd: ParamDef) {
if (pd.__val2color !== undefined) {
return;
}
pd.__val2color = pd.colors !== null ? pd.colors : {};
for (var i = 0; i < pd.distinct_values.length; ++i) {
if (pd.__val2color[pd.distinct_values[i]]) {
continue;
}
if (pd.distinct_values.length <= 20) {
const scheme = ["#1f77b4", "#ff7f0e", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf", "#1f77b4", "#aec7e8", "#ffbb78", "#ff9896", "#c5b0d5", "#c49c94", "#f7b6d2", "#c7c7c7", "#dbdb8d", "#9edae5", "#2ca02c"];
pd.__val2color[pd.distinct_values[i]] = color(scheme[i]).rgb().string();
continue;
}
pd.__val2color[pd.distinct_values[i]] = categoricalColorScheme(pd.distinct_values[i]);
}
};
function parseColorMap(full_name: string, description: string) {
if (!full_name) {
// @ts-ignore
return d3.interpolateTurbo;
}
const parts = full_name.split("#");
const name = parts[0];
var fn = d3[name];
if (!fn) {
throw new Error(`Invalid color map ${name} ${description}`);
}
// Assume this is a scheme (eg array of colors)
if (!name.startsWith("interpolate")) {
if (typeof fn[0] != "string") {
fn = fn[fn.length - 1];
}
const array_of_colors = fn;
fn = function(colr: number) {
return array_of_colors[Math.max(0, Math.min(array_of_colors.length - 1, Math.floor(colr * array_of_colors.length)))];
};
}
// Apply modifiers
if (parts.length > 1) {
parts[1].split(",").forEach(function(modifier_name) {
if (modifier_name == "inverse") {
const orig_fn = fn;
fn = function(colr: number) {
return orig_fn(-colr);
};
}
});
}
return fn;
}
function getColorMap(pd: ParamDef, defaultColorMap: string) {
if (pd.colormap) {
if (pd.__colormap) {
return pd.__colormap;
}
pd.__colormap = parseColorMap(pd.colormap, `for column ${pd.name}`);
return pd.__colormap;
}
return parseColorMap(defaultColorMap, `(global default color map)`);
}
export function colorScheme(pd: ParamDef, value: any, alpha: number, defaultColorMap: string): string {
if (pd.type == ParamType.CATEGORICAL) {
compute_val2color(pd);
var c = pd.__val2color[value];
if (c === undefined) {
return `rgb(100,100,100,${alpha})`;
}
console.assert((c.startsWith('rgb(') || c.startsWith('hsl(')), c);
return c.slice(0, 3) + 'a' + c.slice(3, c.length - 1) + ',' + alpha + ')';
}
else {
if (value === undefined || value === null || is_special_numeric(value)) {
return `rgb(100,100,100,${alpha})`;
}
if (!pd.__colorscale || pd.__colorscale.__type !== pd.type) {
pd.__colorscale = create_d3_scale_without_outliers(pd);
pd.__colorscale.range([0, 1]);
pd.__colorscale.__type = pd.type;
}
const colr = Math.max(0, Math.min(1, pd.__colorscale(value)));
const interpColFn = getColorMap(pd, defaultColorMap);
try {
const code = interpColFn(colr);
const rgb = color(code).rgb().object();
return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${alpha})`;
} catch (err) {
throw new Error(`Error below happened while computing color using color map "${pd.colormap}" for column ${pd.name}: is the colormap valid? (${err.toString()})`);
}
}
}
export interface ParamDefMap { [key: string]: ParamDef; };
/**
* Ideally we want to infer:
* - If a variable is categorical
* - If a variable is numeric
* - If a variable is log-scaled
*/
export function infertypes(url_states: PersistentState, table: Array<Datapoint>, hints: {[key:string]: HiPlotValueDef}): ParamDefMap {
if (hints === undefined) {
hints = {};
}
function infertype(key: string, hint: HiPlotValueDef): ParamDef {
var url_state = url_states.children(key);
var optional = false;
var numeric = ["uid", "from_uid"].indexOf(key) == -1;
var can_be_timestamp = numeric;
var setVals = [];
var addValue = function(v) {
if (v === undefined) {
optional = true;
return;
}
var is_special_num = is_special_numeric(v);
setVals.push(v);
// Detect non-numeric column
if ((typeof v != "number" && !is_special_num && isNaN(v)) ||
v === true || v === false) {
numeric = false;
can_be_timestamp = false;
}
if (!Number.isSafeInteger(v) || v < 0) {
can_be_timestamp = false;
}
}
table.forEach(function(row) {
addValue(row[key]);
});
var values = setVals;
var distinct_values = Array.from(new Set(values));
const numericSorted = numeric ? get_numeric_values_sorted(distinct_values) : [];
var spansMultipleOrdersOfMagnitude = false;
if (numericSorted.length > 10 && numericSorted[0] > 0) {
var top5pct = numericSorted[Math.min(numericSorted.length - 1, ~~(19 * numericSorted.length / 20))];
var bot5pct = numericSorted[~~(numericSorted.length / 20)];
spansMultipleOrdersOfMagnitude = (top5pct / bot5pct) > 100;
}
var categorical = !numeric || ((Math.max(values.length, 10) / distinct_values.length) > 10 && distinct_values.length < 6);
var type = ParamType.CATEGORICAL;
if (numeric && !categorical) {
type = ParamType.NUMERIC;
if (spansMultipleOrdersOfMagnitude) {
type = numericSorted[0] > 0 ? ParamType.NUMERICLOG : ParamType.NUMERICPERCENTILE;
}
}
if (hint !== undefined && hint.type !== null) {
type = hint.type;
} else {
type = url_state.get('type', type);
}
var info = {
'name': key,
'optional': optional,
'numeric': numeric,
'distinct_values': distinct_values,
'type_options': [ParamType.CATEGORICAL],
'type': type,
'colors': hint !== undefined ? hint.colors : null,
'colormap': hint !== undefined ? hint.colormap : null,
'force_value_min': hint !== undefined && hint.force_value_min != null ? hint.force_value_min : null,
'force_value_max': hint !== undefined && hint.force_value_max != null ? hint.force_value_max : null,
'label_css': hint !== undefined && hint.label_css !== null ? hint.label_css : "",
'label_html': hint !== undefined && hint.label_html !== null && hint.label_html !== undefined ? hint.label_html : $("<div>").text(key).html(),
};
// What other types we can render as?
if (numeric) {
info.type_options.push(ParamType.NUMERIC);
if (numericSorted[0] > 0) {
info.type_options.push(ParamType.NUMERICLOG);
}
info.type_options.push(ParamType.NUMERICPERCENTILE);
if (can_be_timestamp) {
info.type_options.push(ParamType.TIMESTAMP);
}
}
return info;
}
// First, get a set of all the types
var allKeys = new Set<string>();
table.forEach(function(row) {
Object.keys(row).forEach(function(k: string) {
allKeys.add(k);
})
});
var ret = {};
allKeys.forEach(function(key) {
ret[key] = infertype(key, hints[key]);
});
return ret;
}; | the_stack |
import { expect } from '@open-wc/testing';
import type { ReactiveController } from 'lit';
import { FluxConnection } from '../src/FluxConnection';
import type { ClientCompleteMessage, ClientErrorMessage, ClientUpdateMessage } from '../src/FluxMessages';
function expectNoDataRetained(fluxConnectionAny: any) {
expect(fluxConnectionAny.endpointInfos.size).to.equal(0);
expect(fluxConnectionAny.onNextCallbacks.size).to.equal(0);
expect(fluxConnectionAny.onCompleteCallbacks.size).to.equal(0);
expect(fluxConnectionAny.onErrorCallbacks.size).to.equal(0);
}
describe('FluxConnection', () => {
let fluxConnection: FluxConnection;
let fluxConnectionAny: any;
beforeEach(() => {
(window as any).Vaadin = { featureFlags: { hillaPush: true } }; // Remove when removing feature flag
fluxConnection = new FluxConnection();
fluxConnectionAny = fluxConnection;
});
it('should be exported', () => {
expect(FluxConnection).to.be.ok;
});
it('requires a feature flag', () => {
delete (window as any).Vaadin;
try {
new FluxConnection(); // eslint-disable-line no-new
expect.fail('Should not work without a feature flag');
} catch (e) {
// Just to ensure something is thrown
}
});
it('should establish a websocket connection when using an endpoint', () => {
fluxConnection.subscribe('MyEndpoint', 'myMethod');
expect(fluxConnectionAny.socket).not.to.equal(undefined);
});
it('should reuse the websocket connection for all endpoints', () => {
fluxConnection.subscribe('MyEndpoint', 'myMethod');
const { socket } = fluxConnectionAny;
fluxConnection.subscribe('OtherEndpoint', 'otherMethod');
expect(fluxConnectionAny.socket).to.equal(socket);
});
it('should send a subscribe server message when subscribing', () => {
fluxConnection.subscribe('MyEndpoint', 'myMethod');
expect(fluxConnectionAny.socket.sentMessages[0]).to.eql({
'@type': 'subscribe',
id: '0',
endpointName: 'MyEndpoint',
methodName: 'myMethod',
params: [],
});
});
it('should immediately return a Subscription when subscribing', () => {
const sub = fluxConnection.subscribe('MyEndpoint', 'myMethod');
expect(sub).to.not.equal(undefined);
expect(sub.onNext).to.not.equal(undefined);
expect(sub.onComplete).to.not.equal(undefined);
expect(sub.onError).to.not.equal(undefined);
});
it('should call onNext when receiving a server message', () => {
const sub = fluxConnection.subscribe('MyEndpoint', 'myMethod');
const receivedValues: any[] = [];
sub.onNext((value) => {
receivedValues.push(value);
});
const msg: ClientUpdateMessage = { '@type': 'update', id: '0', item: { foo: 'bar' } };
fluxConnectionAny.handleMessage(msg);
expect(receivedValues.length).to.equal(1);
expect(receivedValues[0]).to.eql({ foo: 'bar' });
});
it('should call onComplete when receiving a server message', () => {
const sub = fluxConnection.subscribe('MyEndpoint', 'myMethod');
let completeCalled = 0;
sub.onComplete(() => {
completeCalled += 1;
});
const msg: ClientCompleteMessage = { '@type': 'complete', id: '0' };
fluxConnectionAny.handleMessage(msg);
expect(completeCalled).to.eq(1);
});
it('should call onError when receiving a server message', () => {
const sub = fluxConnection.subscribe('MyEndpoint', 'myMethod');
let errorCalled = 0;
sub.onError(() => {
errorCalled += 1;
});
const msg: ClientErrorMessage = { '@type': 'error', id: '0', message: 'it failed' };
fluxConnectionAny.handleMessage(msg);
expect(errorCalled).to.eq(1);
});
it('should not deliver messages after completing', () => {
const sub = fluxConnection.subscribe('MyEndpoint', 'myMethod');
let onNextCalled = 0;
sub.onNext((_value) => {
onNextCalled += 1;
});
const completeMsg: ClientCompleteMessage = { '@type': 'complete', id: '0' };
const msg: ClientUpdateMessage = { '@type': 'update', id: '0', item: { foo: 'bar' } };
fluxConnectionAny.handleMessage(completeMsg);
try {
fluxConnectionAny.handleMessage(msg);
expect.fail('Should not fail silently');
} catch (e) {
// No need to handle the error
}
expect(onNextCalled).to.eq(0);
});
it('should cancel the server subscription on cancel', () => {
const sub = fluxConnection.subscribe('MyEndpoint', 'myMethod');
sub.onNext((_value) => {
// No need to handle the value
});
sub.cancel();
expect(fluxConnectionAny.socket.sentMessages.length).to.equal(2);
expect(fluxConnectionAny.socket.sentMessages[1]).to.eql({
'@type': 'unsubscribe',
id: '0',
});
});
it('should not deliver messages after canceling', () => {
const sub = fluxConnection.subscribe('MyEndpoint', 'myMethod');
let onNextCalled = 0;
sub.onNext((_value) => {
onNextCalled += 1;
});
sub.cancel();
const msg: ClientUpdateMessage = { '@type': 'update', id: '0', item: { foo: 'bar' } };
fluxConnectionAny.handleMessage(msg);
expect(onNextCalled).to.equal(0);
});
it('should throw an error for messages to unknown subscriptions', () => {
const msg: ClientUpdateMessage = { '@type': 'update', id: '0', item: { foo: 'bar' } };
try {
fluxConnectionAny.handleMessage(msg);
expect.fail('Should have thrown an error');
} catch (e) {
// No need to handle the error
}
});
it('should throw an error for flux errors without onError', () => {
const msg: ClientErrorMessage = { '@type': 'error', id: '0', message: 'foo' };
try {
fluxConnectionAny.handleMessage(msg);
expect.fail('Should have thrown an error');
} catch (e) {
// No need to handle the error
}
});
it('should throw an error for unknown messages', () => {
const msg: any = { '@type': 'unknown', id: '0' };
try {
fluxConnectionAny.handleMessage(msg);
expect.fail('Should have thrown an error');
} catch (e) {
// No need to handle the error
}
});
it('clean internal data on complete', () => {
const sub = fluxConnection.subscribe('MyEndpoint', 'myMethod');
sub.onComplete(() => {
// Just need a callback
});
sub.onError(() => {
// Just need a callback
});
sub.onNext((_value) => {
// Just need a callback
});
const completeMsg: ClientCompleteMessage = { '@type': 'complete', id: '0' };
fluxConnectionAny.handleMessage(completeMsg);
expectNoDataRetained(fluxConnectionAny);
});
it('clean internal data on error', () => {
const sub = fluxConnection.subscribe('MyEndpoint', 'myMethod');
sub.onComplete(() => {
// Just need a callback
});
sub.onError(() => {
// Just need a callback
});
sub.onNext((_value) => {
// Just need a callback
});
const completeMsg: ClientErrorMessage = { '@type': 'error', id: '0', message: 'foo' };
fluxConnectionAny.handleMessage(completeMsg);
expectNoDataRetained(fluxConnectionAny);
});
it('clean internal data on cancel', () => {
const sub = fluxConnection.subscribe('MyEndpoint', 'myMethod');
sub.onComplete(() => {
// Just need a callback
});
sub.onError(() => {
// Just need a callback
});
sub.onNext((_value) => {
// Just need a callback
});
sub.cancel();
expectNoDataRetained(fluxConnectionAny);
});
it('should ignore a second cancel call', () => {
const sub = fluxConnection.subscribe('MyEndpoint', 'myMethod');
sub.onComplete(() => {
// Just need a callback
});
sub.onError(() => {
// Just need a callback
});
sub.onNext((_value) => {
// Just need a callback
});
expect(fluxConnectionAny.socket.sentMessages.length).to.equal(1);
sub.cancel();
expect(fluxConnectionAny.socket.sentMessages.length).to.equal(2);
sub.cancel();
expect(fluxConnectionAny.socket.sentMessages.length).to.equal(2);
});
it('calls cancel when context is deactivated', () => {
const sub = fluxConnection.subscribe('MyEndpoint', 'myMethod');
sub.onComplete(() => {
// Just need a callback
});
sub.onError(() => {
// Just need a callback
});
sub.onNext((_value) => {
// Just need a callback
});
class FakeElement {
private controllers: ReactiveController[] = [];
addController(controller: ReactiveController) {
this.controllers.push(controller);
}
disconnectedCallback() {
this.controllers.forEach((controller) => controller.hostDisconnected && controller.hostDisconnected());
}
}
const fakeElement: any = new FakeElement();
sub.context(fakeElement);
fakeElement.disconnectedCallback();
expectNoDataRetained(fluxConnectionAny);
});
it('dispatches an active event on socket.io connect', () => {
const { socket } = fluxConnectionAny;
socket.connected = false;
let events = 0;
fluxConnection.addEventListener('state-changed', (e) => {
if (e.detail.active) {
events += 1;
}
});
socket.connected = true;
socket.emit('connect');
expect(events).to.equal(1);
});
it('dispatches an active event on socket.io reconnect', () => {
const { socket } = fluxConnectionAny;
socket.connected = false;
let events = 0;
fluxConnection.addEventListener('state-changed', (e) => {
if (e.detail.active) {
events += 1;
}
});
socket.connected = true;
socket.emit('connect');
socket.connected = false;
socket.emit('disconnect');
socket.connected = true;
socket.emit('connect');
expect(events).to.equal(2);
});
it('dispatches an inactive event on socket.io disconnect', () => {
const { socket } = fluxConnectionAny;
let events = 0;
fluxConnection.addEventListener('state-changed', (e) => {
if (!e.detail.active) {
events += 1;
}
});
socket.connected = true;
socket.emit('connect');
socket.connected = false;
socket.emit('disconnect');
expect(events).to.equal(1);
});
}); | the_stack |
import * as chai from 'chai';
import 'mocha';
import { AbiEncoder } from '../../src';
import { chaiSetup } from '../utils/chai_setup';
chaiSetup.configure();
const expect = chai.expect;
describe('ABI Encoder: Signatures', () => {
describe('Single type', () => {
it('Elementary', async () => {
const signature = 'uint256';
const dataType = AbiEncoder.create(signature);
const dataTypeId = dataType.getDataItem().type;
expect(dataTypeId).to.be.equal('uint256');
expect(dataType.getSignature()).to.be.equal(signature);
});
it('Array', async () => {
const signature = 'string[]';
const dataType = AbiEncoder.create(signature);
const dataItem = dataType.getDataItem();
const expectedDataItem = {
name: '',
type: 'string[]',
};
expect(dataItem).to.be.deep.equal(expectedDataItem);
expect(dataType.getSignature()).to.be.equal(signature);
});
it('Multidimensional Array', async () => {
// Decode return value
const signature = 'uint256[4][][5]';
const dataType = AbiEncoder.create(signature);
const dataTypeId = dataType.getDataItem().type;
expect(dataTypeId).to.be.equal(signature);
expect(dataType.getSignature()).to.be.equal(signature);
});
it('Tuple with single element', async () => {
const signature = '(uint256)';
const dataType = AbiEncoder.create(signature);
const dataItem = dataType.getDataItem();
const expectedDataItem = {
name: '',
type: 'tuple',
components: [
{
name: '',
type: 'uint256',
},
],
};
expect(dataItem).to.be.deep.equal(expectedDataItem);
expect(dataType.getSignature()).to.be.equal(signature);
});
it('Tuple with multiple elements', async () => {
const signature = '(uint256,string,bytes4)';
const dataType = AbiEncoder.create(signature);
const dataItem = dataType.getDataItem();
const expectedDataItem = {
name: '',
type: 'tuple',
components: [
{
name: '',
type: 'uint256',
},
{
name: '',
type: 'string',
},
{
name: '',
type: 'bytes4',
},
],
};
expect(dataItem).to.be.deep.equal(expectedDataItem);
expect(dataType.getSignature()).to.be.equal(signature);
});
it('Tuple with nested array and nested tuple', async () => {
const signature = '(uint256[],(bytes),string[4],bytes4)';
const dataType = AbiEncoder.create(signature);
const dataItem = dataType.getDataItem();
const expectedDataItem = {
name: '',
type: 'tuple',
components: [
{
name: '',
type: 'uint256[]',
},
{
name: '',
type: 'tuple',
components: [
{
name: '',
type: 'bytes',
},
],
},
{
name: '',
type: 'string[4]',
},
{
name: '',
type: 'bytes4',
},
],
};
expect(dataItem).to.be.deep.equal(expectedDataItem);
expect(dataType.getSignature()).to.be.equal(signature);
});
it('Array of complex tuples', async () => {
const signature = '(uint256[],(bytes),string[4],bytes4)[5][4][]';
const dataType = AbiEncoder.create(signature);
const dataItem = dataType.getDataItem();
const expectedDataItem = {
name: '',
type: 'tuple[5][4][]',
components: [
{
name: '',
type: 'uint256[]',
},
{
name: '',
type: 'tuple',
components: [
{
name: '',
type: 'bytes',
},
],
},
{
name: '',
type: 'string[4]',
},
{
name: '',
type: 'bytes4',
},
],
};
expect(dataItem).to.be.deep.equal(expectedDataItem);
expect(dataType.getSignature()).to.be.equal(signature);
});
});
describe('Function', () => {
it('No inputs and no outputs', async () => {
// create encoder
const functionName = 'foo';
const dataType = AbiEncoder.createMethod(functionName);
// create expected values
const expectedSignature = 'foo()';
const expectedInputDataItem = {
name: 'foo',
type: 'method',
components: [],
};
const expectedOutputDataItem = {
name: 'foo',
type: 'tuple',
components: [],
};
// check expected values
expect(dataType.getSignature()).to.be.equal(expectedSignature);
expect(dataType.getDataItem()).to.be.deep.equal(expectedInputDataItem);
expect(dataType.getReturnValueDataItem()).to.be.deep.equal(expectedOutputDataItem);
});
it('No inputs and no outputs (empty arrays as input)', async () => {
// create encoder
const functionName = 'foo';
const dataType = AbiEncoder.createMethod(functionName, [], []);
// create expected values
const expectedSignature = 'foo()';
const expectedInputDataItem = {
name: 'foo',
type: 'method',
components: [],
};
const expectedOutputDataItem = {
name: 'foo',
type: 'tuple',
components: [],
};
// check expected values
expect(dataType.getSignature()).to.be.equal(expectedSignature);
expect(dataType.getDataItem()).to.be.deep.equal(expectedInputDataItem);
expect(dataType.getReturnValueDataItem()).to.be.deep.equal(expectedOutputDataItem);
});
it('Single DataItem input and single DataItem output', async () => {
// create encoder
const functionName = 'foo';
const inputDataItem = {
name: 'input',
type: 'uint256',
};
const outputDataItem = {
name: 'output',
type: 'string',
};
const dataType = AbiEncoder.createMethod(functionName, inputDataItem, outputDataItem);
// create expected values
const expectedSignature = 'foo(uint256)';
const expectedInputDataItem = {
name: 'foo',
type: 'method',
components: [inputDataItem],
};
const expectedOutputDataItem = {
name: 'foo',
type: 'tuple',
components: [outputDataItem],
};
// check expected values
expect(dataType.getSignature()).to.be.equal(expectedSignature);
expect(dataType.getDataItem()).to.be.deep.equal(expectedInputDataItem);
expect(dataType.getReturnValueDataItem()).to.be.deep.equal(expectedOutputDataItem);
});
it('Single signature input and single signature output', async () => {
// create encoder
const functionName = 'foo';
const inputSignature = 'uint256';
const outputSignature = 'string';
const dataType = AbiEncoder.createMethod(functionName, inputSignature, outputSignature);
// create expected values
const expectedSignature = 'foo(uint256)';
const expectedInputDataItem = {
name: 'foo',
type: 'method',
components: [
{
name: '',
type: 'uint256',
},
],
};
const expectedOutputDataItem = {
name: 'foo',
type: 'tuple',
components: [
{
name: '',
type: 'string',
},
],
};
// check expected values
expect(dataType.getSignature()).to.be.equal(expectedSignature);
expect(dataType.getDataItem()).to.be.deep.equal(expectedInputDataItem);
expect(dataType.getReturnValueDataItem()).to.be.deep.equal(expectedOutputDataItem);
});
it('Single signature tuple input and single signature tuple output', async () => {
// create encoder
const functionName = 'foo';
const inputSignature = '(uint256,bytes[][4])';
const outputSignature = '(string,uint32)';
const dataType = AbiEncoder.createMethod(functionName, inputSignature, outputSignature);
// create expected values
const expectedSignature = 'foo((uint256,bytes[][4]))';
const expectedInputDataItem = {
name: 'foo',
type: 'method',
components: [
{
name: '',
type: 'tuple',
components: [
{
name: '',
type: 'uint256',
},
{
name: '',
type: 'bytes[][4]',
},
],
},
],
};
const expectedOutputDataItem = {
name: 'foo',
type: 'tuple',
components: [
{
name: '',
type: 'tuple',
components: [
{
name: '',
type: 'string',
},
{
name: '',
type: 'uint32',
},
],
},
],
};
// check expected values
expect(dataType.getSignature()).to.be.equal(expectedSignature);
expect(dataType.getDataItem()).to.be.deep.equal(expectedInputDataItem);
expect(dataType.getReturnValueDataItem()).to.be.deep.equal(expectedOutputDataItem);
});
it('Mutiple DataItem input and multiple DataItem output', async () => {
// create encoder
const functionName = 'foo';
const inputDataItems = [
{
name: '',
type: 'uint256',
},
{
name: '',
type: 'bytes[][4]',
},
];
const outputDataItems = [
{
name: '',
type: 'string',
},
{
name: '',
type: 'uint32',
},
];
const dataType = AbiEncoder.createMethod(functionName, inputDataItems, outputDataItems);
// create expected values
const expectedSignature = 'foo(uint256,bytes[][4])';
const expectedInputDataItem = {
name: 'foo',
type: 'method',
components: inputDataItems,
};
const expectedOutputDataItem = {
name: 'foo',
type: 'tuple',
components: outputDataItems,
};
// check expected values
expect(dataType.getSignature()).to.be.equal(expectedSignature);
expect(dataType.getDataItem()).to.be.deep.equal(expectedInputDataItem);
expect(dataType.getReturnValueDataItem()).to.be.deep.equal(expectedOutputDataItem);
});
it('Multiple signature input and multiple signature output', async () => {
// create encoder
const functionName = 'foo';
const inputSignatures = ['uint256', 'bytes[][4]'];
const outputSignatures = ['string', 'uint32'];
const dataType = AbiEncoder.createMethod(functionName, inputSignatures, outputSignatures);
// create expected values
const expectedSignature = 'foo(uint256,bytes[][4])';
const expectedInputDataItem = {
name: 'foo',
type: 'method',
components: [
{
name: '',
type: 'uint256',
},
{
name: '',
type: 'bytes[][4]',
},
],
};
const expectedOutputDataItem = {
name: 'foo',
type: 'tuple',
components: [
{
name: '',
type: 'string',
},
{
name: '',
type: 'uint32',
},
],
};
// check expected values
expect(dataType.getSignature()).to.be.equal(expectedSignature);
expect(dataType.getDataItem()).to.be.deep.equal(expectedInputDataItem);
expect(dataType.getReturnValueDataItem()).to.be.deep.equal(expectedOutputDataItem);
});
});
}); | the_stack |
import React, { useContext, useEffect, useMemo, useState } from "react";
import styled from "styled-components";
import { InviteType } from "shared/types";
import api from "shared/api";
import { Context } from "shared/Context";
import Loading from "components/Loading";
import InputRow from "components/form-components/InputRow";
import Helper from "components/form-components/Helper";
import Heading from "components/form-components/Heading";
import CopyToClipboard from "components/CopyToClipboard";
import { Column } from "react-table";
import Table from "components/Table";
import RadioSelector from "components/RadioSelector";
type Props = {};
export type Collaborator = {
id: string;
user_id: string;
project_id: string;
email: string;
kind: string;
};
const InvitePage: React.FunctionComponent<Props> = ({}) => {
const {
currentProject,
setCurrentModal,
setCurrentError,
user,
usage,
hasBillingEnabled,
} = useContext(Context);
const [isLoading, setIsLoading] = useState(true);
const [invites, setInvites] = useState<Array<InviteType>>([]);
const [email, setEmail] = useState("");
const [role, setRole] = useState("developer");
const [roleList, setRoleList] = useState([]);
const [isInvalidEmail, setIsInvalidEmail] = useState(false);
const [isHTTPS] = useState(() => window.location.protocol === "https:");
useEffect(() => {
api
.getAvailableRoles("<token>", {}, { project_id: currentProject.id })
.then(({ data }: { data: string[] }) => {
const availableRoleList = data?.map((role) => ({
value: role,
label: capitalizeFirstLetter(role),
}));
setRoleList(availableRoleList);
setRole("developer");
});
getData();
}, [currentProject]);
const capitalizeFirstLetter = (string: string) => {
return string.charAt(0).toUpperCase() + string.slice(1);
};
const getData = async () => {
setIsLoading(true);
let invites = [];
try {
const response = await api.getInvites(
"<token>",
{},
{
id: currentProject.id,
}
);
invites = response.data.filter((i: InviteType) => !i.accepted);
} catch (err) {
console.log(err);
}
let collaborators: any = [];
try {
const response = await api.getCollaborators(
"<token>",
{},
{
project_id: currentProject.id,
}
);
collaborators = parseCollaboratorsResponse(response.data);
} catch (err) {
console.log(err);
}
setInvites([...invites, ...collaborators]);
setIsLoading(false);
};
const parseCollaboratorsResponse = (
collaborators: Array<Collaborator>
): Array<InviteType> => {
return (
collaborators
// Parse role id to number
.map((c) => ({ ...c, id: Number(c.id) }))
// Sort them so the owner will be first allways
.sort((curr, prev) => curr.id - prev.id)
// Remove the owner from list
.slice(1)
// Parse the remainings to InviteType
.map((c) => ({
email: c.email,
expired: false,
id: Number(c.user_id),
kind: c.kind,
accepted: true,
token: "",
}))
);
};
const createInvite = () => {
api
.createInvite("<token>", { email, kind: role }, { id: currentProject.id })
.then(() => {
getData();
setEmail("");
})
.catch((err) => {
if (err.response.data?.error) {
setCurrentError(err.response.data?.error);
}
console.log(err);
});
};
const deleteInvite = (inviteId: number) => {
api
.deleteInvite(
"<token>",
{},
{
id: currentProject.id,
invId: inviteId,
}
)
.then(getData)
.catch((err) => console.log(err));
};
const replaceInvite = (
inviteEmail: string,
inviteId: number,
kind: string
) => {
api
.createInvite(
"<token>",
{ email: inviteEmail, kind },
{ id: currentProject.id }
)
.then(() =>
api.deleteInvite(
"<token>",
{},
{
id: currentProject.id,
invId: inviteId,
}
)
)
.then(getData)
.catch((err) => {
if (err.response.data?.error) {
setCurrentError(err.response.data?.error);
}
console.log(err);
});
};
const validateEmail = () => {
const regex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!regex.test(email.toLowerCase())) {
setIsInvalidEmail(true);
return;
}
setIsInvalidEmail(false);
createInvite();
};
const openEditModal = (user: any) => {
if (setCurrentModal) {
setCurrentModal("EditInviteOrCollaboratorModal", {
user,
isInvite: user.status !== "accepted",
refetchCallerData: getData,
});
}
};
const removeCollaborator = (user_id: number) => {
try {
api.removeCollaborator(
"<token>",
{ user_id },
{ project_id: currentProject.id }
);
getData();
} catch (error) {
console.log(error);
}
};
const columns = useMemo<
Column<{
email: string;
id: number;
status: string;
invite_link: string;
kind: string;
}>[]
>(
() => [
{
Header: "User",
accessor: "email",
},
{
Header: "Role",
accessor: "kind",
Cell: ({ row }) => {
return <Role>{row.values.kind || "Developer"}</Role>;
},
},
{
Header: "Status",
accessor: "status",
Cell: ({ row }) => {
return (
<Status status={row.values.status}>{row.values.status}</Status>
);
},
},
{
Header: "",
accessor: "invite_link",
Cell: ({ row }) => {
if (row.values.status === "expired") {
return (
<NewLinkButton
onClick={() =>
replaceInvite(
row.values.email,
row.values.id,
row.values.kind
)
}
>
<u>Generate a new link</u>
</NewLinkButton>
);
}
if (row.values.status === "accepted") {
return "";
}
return (
<>
<CopyToClipboard as={Url} text={row.values.invite_link}>
<span>{row.values.invite_link}</span>
<i className="material-icons-outlined">content_copy</i>
</CopyToClipboard>
</>
);
},
},
{
id: "edit_action",
Cell: ({ row }: any) => {
return <></>;
},
},
{
id: "remove_invite_action",
Cell: ({ row }: any) => {
if (row.values.status === "accepted") {
return (
<Flex>
<SettingsButton
invis={row.original.currentUser}
onClick={() => openEditModal(row.original)}
>
<i className="material-icons">more_vert</i>
</SettingsButton>
<DeleteButton
invis={row.original.currentUser}
onClick={() => removeCollaborator(row.original.id)}
>
<i className="material-icons">delete</i>
</DeleteButton>
</Flex>
);
}
return (
<Flex>
<SettingsButton
invis={row.original.currentUser}
onClick={() => openEditModal(row.original)}
>
<i className="material-icons">more_vert</i>
</SettingsButton>
<DeleteButton
invis={row.original.currentUser}
onClick={() => deleteInvite(row.original.id)}
>
<i className="material-icons">delete</i>
</DeleteButton>
</Flex>
);
},
},
],
[]
);
const data = useMemo(() => {
const inviteList = [...invites];
inviteList.sort((a: any, b: any) => (a.email > b.email ? 1 : -1));
inviteList.sort((a: any, b: any) => (a.accepted > b.accepted ? 1 : -1));
const buildInviteLink = (token: string) => `
${isHTTPS ? "https://" : ""}${window.location.host}/api/projects/${
currentProject.id
}/invites/${token}
`;
const mappedInviteList = inviteList.map(
({ accepted, expired, token, ...rest }) => {
const currentUser: boolean = user.email === rest.email;
if (accepted) {
return {
status: "accepted",
invite_link: buildInviteLink(token),
currentUser,
...rest,
};
}
if (!accepted && expired) {
return {
status: "expired",
invite_link: buildInviteLink(token),
currentUser,
...rest,
};
}
return {
status: "pending",
invite_link: buildInviteLink(token),
currentUser,
...rest,
};
}
);
return mappedInviteList || [];
}, [invites, currentProject?.id, window?.location?.host, isHTTPS, user?.id]);
const hasSeats = useMemo(() => {
if (!hasBillingEnabled) {
return true;
}
if (usage?.limit.users === 0) {
// If usage limit is 0, the project has unlimited seats. Otherwise, check
// the usage limit against the current usage.
return true;
}
return usage?.current.users < usage?.limit.users;
}, [hasBillingEnabled, usage]);
if (hasBillingEnabled === null && usage === null) {
<Loading height={"30%"} />;
}
return (
<>
<>
<Heading isAtTop={true}>Share Project</Heading>
<Helper>Generate a project invite for another user.</Helper>
<InputRowWrapper>
<InputRow
value={email}
type="text"
setValue={(newEmail: string) => setEmail(newEmail)}
width="100%"
placeholder="ex: mrp@getporter.dev"
/>
</InputRowWrapper>
<Helper>Specify a role for this user.</Helper>
<RoleSelectorWrapper>
<RadioSelector
selected={role}
setSelected={setRole}
options={roleList}
/>
</RoleSelectorWrapper>
<ButtonWrapper>
<InviteButton disabled={!hasSeats} onClick={() => validateEmail()}>
Create Invite
</InviteButton>
{isInvalidEmail && (
<Invalid>Invalid email address. Please try again.</Invalid>
)}
{!hasSeats && (
<Invalid>
You need to upgrade your plan to invite more users to the project
</Invalid>
)}
</ButtonWrapper>
</>
<Heading>Invites & Collaborators</Heading>
<Helper>Manage pending invites and view collaborators.</Helper>
{isLoading && <Loading height={"30%"} />}
{data?.length && !isLoading ? (
<Table
columns={columns}
data={data}
disableHover={true}
isLoading={false}
disableGlobalFilter={true}
/>
) : (
!isLoading && (
<Placeholder>
This project currently has no invites or collaborators.
</Placeholder>
)
)}
</>
);
};
export default InvitePage;
const Flex = styled.div`
display: flex;
align-items: center;
width: 70px;
float: right;
justify-content: space-between;
`;
const DeleteButton = styled.div`
display: flex;
visibility: ${(props: { invis?: boolean }) =>
props.invis ? "hidden" : "visible"};
align-items: center;
justify-content: center;
width: 30px;
float: right;
height: 30px;
:hover {
background: #ffffff11;
border-radius: 20px;
cursor: pointer;
}
> i {
font-size: 20px;
color: #ffffff44;
border-radius: 20px;
}
`;
const SettingsButton = styled(DeleteButton)`
margin-right: -60px;
`;
const Role = styled.div`
text-transform: capitalize;
margin-right: 50px;
`;
const RoleSelectorWrapper = styled.div`
font-size: 14px;
`;
const Placeholder = styled.div`
width: 100%;
height: 200px;
display: flex;
align-items: center;
margin-top: 23px;
justify-content: center;
background: #ffffff11;
border-radius: 5px;
color: #ffffff44;
font-size: 13px;
`;
const ButtonWrapper = styled.div`
display: flex;
align-items: center;
`;
const InputRowWrapper = styled.div`
width: 40%;
`;
const CopyButton = styled.div`
visibility: ${(props: { invis?: boolean }) =>
props.invis ? "hidden" : "visible"};
color: #ffffff;
font-weight: 400;
font-size: 13px;
margin: 8px 0 8px 12px;
float: right;
display: flex;
justify-content: center;
align-items: center;
width: 120px;
cursor: pointer;
height: 30px;
border-radius: 5px;
border: 1px solid #ffffff20;
background-color: #ffffff10;
overflow: hidden;
transition: all 0.1s ease-out;
:hover {
border: 1px solid #ffffff66;
background-color: #ffffff20;
}
`;
const NewLinkButton = styled(CopyButton)`
border: none;
width: auto;
float: none;
display: block;
margin: unset;
background-color: transparent;
:hover {
border: none;
background-color: transparent;
}
`;
const InviteButton = styled.div<{ disabled: boolean }>`
height: 35px;
font-size: 13px;
font-weight: 500;
font-family: "Work Sans", sans-serif;
color: white;
display: flex;
align-items: center;
padding: 0 15px;
margin-top: 13px;
text-align: left;
float: left;
margin-left: 0;
justify-content: center;
border: 0;
border-radius: 5px;
background: ${(props) => (!props.disabled ? "#616FEEcc" : "#aaaabb")};
box-shadow: ${(props) =>
!props.disabled ? "0 2px 5px 0 #00000030" : "none"};
cursor: ${(props) => (!props.disabled ? "pointer" : "default")};
user-select: none;
:focus {
outline: 0;
}
:hover {
filter: ${(props) => (!props.disabled ? "brightness(120%)" : "")};
}
margin-bottom: 10px;
`;
const Url = styled.a`
max-width: 300px;
font-size: 13px;
user-select: text;
font-weight: 400;
display: flex;
align-items: center;
justify-content: center;
> i {
margin-left: 10px;
font-size: 15px;
}
> span {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
:hover {
cursor: pointer;
}
`;
const Invalid = styled.div`
color: #f5cb42;
margin-left: 15px;
font-size: 13px;
font-family: "Work Sans", sans-serif;
`;
const Status = styled.div<{ status: "accepted" | "expired" | "pending" }>`
padding: 5px 10px;
margin-right: 12px;
background: ${(props) => {
if (props.status === "accepted") return "#38a88a";
if (props.status === "expired") return "#cc3d42";
if (props.status === "pending") return "#ffffff11";
}};
font-size: 13px;
border-radius: 3px;
display: flex;
align-items: center;
justify-content: center;
max-height: 25px;
max-width: 80px;
text-transform: capitalize;
font-weight: 400;
user-select: none;
`; | the_stack |
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import {
Stack,
Text,
getTheme,
Separator,
CommandBar,
ICommandBarItemProps,
Pivot,
PivotItem,
IDropdownOption,
Dropdown,
} from '@fluentui/react';
import { useSelector, useDispatch } from 'react-redux';
import { useBoolean } from '@uifabric/react-hooks';
import { formatDistanceToNow } from 'date-fns';
import * as R from 'ramda';
import { State } from 'RootStateType';
import { InferenceSource, Project, Status } from '../../store/project/projectTypes';
import {
thunkGetProject,
updateProjectData,
updateProbThreshold,
updateMaxPeople,
getConfigure,
} from '../../store/project/projectActions';
import { ConfigurationInfo } from '../ConfigurationInfo/ConfigurationInfo';
import { camerasSelectorFactory } from '../../store/cameraSlice';
import { partNamesSelectorFactory, partOptionsSelectorFactory } from '../../store/partSlice';
import { AdditionalProps, DeploymentProps } from './ts/Deployment';
import { ConfigTaskPanel } from '../ConfigTaskPanel/ConfigTaskPanel';
import { EmptyAddIcon } from '../EmptyAddIcon';
import { getTrainingProject } from '../../store/trainingProjectSlice';
import { Insights } from './DeploymentInsights';
import { Instruction } from '../Instruction';
import { getImages, selectAllImages } from '../../store/imageSlice';
import { initialProjectData } from '../../store/project/projectReducer';
import { Progress } from './Progress';
import { VideoAnnosControls } from './VideoControls';
import { LiveViewScene } from '../LiveViewScene';
const { palette } = getTheme();
const BaseDeployment: React.FC<DeploymentProps> = (props) => {
const { onOpenCreatePanel, onOpenEditPanel } = props;
const { status, data: projectData, originData } = useSelector<State, Project>((state) => state.project);
const {
id: projectId,
cameras: projectCameraIds,
trainingProject,
parts,
sendMessageToCloud,
framesPerMin,
needRetraining,
accuracyRangeMin,
accuracyRangeMax,
maxImages,
name,
probThreshold,
fps,
} = projectData;
const camerasSelector = useMemo(() => camerasSelectorFactory(projectCameraIds), [projectCameraIds]);
const cameraOptions: IDropdownOption[] = useSelector((state: State) =>
camerasSelector(state).map((e) => ({ key: e?.id, text: e?.name })),
);
const [selectedCamera, setselectedCamera] = useState(projectCameraIds[0]);
useEffect(() => {
if (projectCameraIds.length) setselectedCamera(projectCameraIds[0]);
}, [projectCameraIds]);
const partNamesSelector = useMemo(() => partNamesSelectorFactory(parts), [parts]);
const partOptionsSelector = useMemo(() => partOptionsSelectorFactory(trainingProject), [trainingProject]);
const partOptions = useSelector(partOptionsSelector);
const partNames = useSelector(partNamesSelector);
const deployTimeStamp = useSelector((state: State) => state.project.data.deployTimeStamp);
const newImagesCount = useSelector(
(state: State) => selectAllImages(state).filter((e) => !e.uploaded && e.manualChecked).length,
);
const dispatch = useDispatch();
useEffect(() => {
dispatch(getTrainingProject(true));
// The property `upload` would be changed after configure
// Re fetch the images to get the latest data
dispatch(getImages({ freezeRelabelImgs: false }));
}, [dispatch]);
const changeProbThreshold = (newValue: number) => dispatch(updateProjectData({ probThreshold: newValue }));
const saveProbThresholde = () => dispatch(updateProbThreshold());
const changeMaxPeople = (newValue: number) => dispatch(updateProjectData({ maxPeople: newValue }));
const saveMaxPeople = () => dispatch(updateMaxPeople());
const updateModel = useCallback(async () => {
await dispatch(getConfigure(projectId));
}, [dispatch, projectId]);
const commandBarItems: ICommandBarItemProps[] = useMemo(() => {
const items = [
{
key: 'create',
text: 'Create new task',
iconProps: {
iconName: 'Add',
},
onClick: onOpenCreatePanel,
},
{
key: 'edit',
text: 'Edit task',
iconProps: {
iconName: 'Edit',
},
onClick: onOpenEditPanel,
},
];
if (newImagesCount)
items.splice(1, 0, {
key: 'update',
text: 'Update model',
iconProps: {
iconName: 'Edit',
},
onClick: updateModel,
});
return items;
}, [newImagesCount, onOpenCreatePanel, onOpenEditPanel, updateModel]);
if (status === Status.None)
return (
<EmptyAddIcon
title="Config a task"
subTitle=""
primary={{ text: 'Config task', onClick: onOpenCreatePanel }}
/>
);
if (status === Status.WaitTraining) return <Progress projectId={projectId} cameraId={selectedCamera} />;
return (
<Stack styles={{ root: { height: '100%' } }}>
<CommandBar items={commandBarItems} style={{ display: 'block' }} />
<UpdateModelInstruction newImagesCount={newImagesCount} updateModel={updateModel} />
<Stack horizontal grow>
<Stack grow>
<Stack tokens={{ childrenGap: 17, padding: 25 }} grow>
<Stack grow>
<LiveViewScene cameraId={selectedCamera} />
</Stack>
<Stack horizontal horizontalAlign="space-between">
<Stack tokens={{ childrenGap: 10 }} styles={{ root: { minWidth: '200px' } }}>
<Text variant="xLarge">{name}</Text>
<Text styles={{ root: { color: palette.neutralSecondary } }}>
Started running{' '}
<b>{formatDistanceToNow(new Date(deployTimeStamp), { addSuffix: false })} ago</b>
</Text>
</Stack>
<Dropdown
options={cameraOptions}
label="Select Camera"
styles={{
root: { display: 'flex', alignItems: 'flex-start' },
dropdown: { width: '180px', marginLeft: '24px' },
}}
selectedKey={selectedCamera}
onChange={(_, option) => setselectedCamera(option.key as number)}
/>
</Stack>
</Stack>
<Separator styles={{ root: { padding: 0 } }} />
<Stack tokens={{ childrenGap: 17, padding: 25 }}>
<ConfigurationInfo
cameraNames={cameraOptions.map((e) => e.text)}
fps={fps}
partNames={partNames}
sendMessageToCloud={sendMessageToCloud}
framesPerMin={framesPerMin}
needRetraining={needRetraining}
accuracyRangeMin={accuracyRangeMin}
accuracyRangeMax={accuracyRangeMax}
probThreshold={probThreshold}
originProbThreshold={originData.probThreshold}
updateProbThreshold={changeProbThreshold}
saveProbThreshold={saveProbThresholde}
maxImages={maxImages}
SVTCcameraNames={cameraOptions
.filter((e) => projectData.SVTCcameras.includes(e.key as number))
.map((e) => e.text)}
SVTCpartNames={partOptions
.filter((e) => projectData.SVTCparts.includes(e.key as number))
.map((e) => e.text)}
SVTCisOpen={projectData.SVTCisOpen}
SVTCthreshold={projectData.SVTCconfirmationThreshold}
protocol={projectData.inferenceProtocol}
isLVA={projectData.inferenceSource === InferenceSource.LVA}
changeMaxPeople={changeMaxPeople}
saveMaxPeople={saveMaxPeople}
maxPeople={projectData.maxPeople}
inferenceMode={projectData.inferenceMode}
/>
</Stack>
</Stack>
{/* Vertical seperator has z-index in 1 as default, which will be on top of the panel */}
<Separator vertical styles={{ root: { zIndex: 0 } }} />
<Pivot styles={{ root: { borderBottom: `solid 1px ${palette.neutralLight}`, width: '435px' } }}>
<PivotItem headerText="Insights">
<Insights
status={status}
projectId={projectData.id}
cameraId={selectedCamera}
inferenceMode={projectData.inferenceMode}
countingStartTime={projectData.countingStartTime}
countingEndTime={projectData.countingEndTime}
/>
</PivotItem>
<PivotItem headerText="Areas of interest">
<VideoAnnosControls cameraId={selectedCamera} />
</PivotItem>
</Pivot>
</Stack>
</Stack>
);
};
export const Deployment = R.compose(
(BaseComponent: React.ComponentType<AdditionalProps>): React.FC => () => {
const [isEditPanelOpen, { setTrue: onOpenEditPanel, setFalse: onCloseEditPanel }] = useBoolean(false);
const [isCreatePanelOpen, { setTrue: onOpenCreatePanel, setFalse: closeCreatePanel }] = useBoolean(false);
const { data: projectData } = useSelector<State, Project>((state) => state.project);
const dispatch = useDispatch();
useEffect(() => {
(async () => {
const hasConfigured = await dispatch(thunkGetProject());
if (!hasConfigured) onOpenCreatePanel();
})();
}, [dispatch, onOpenCreatePanel]);
return (
<>
<BaseComponent onOpenCreatePanel={onOpenCreatePanel} onOpenEditPanel={onOpenEditPanel} />
<ConfigTaskPanel
isOpen={isEditPanelOpen}
onDismiss={onCloseEditPanel}
projectData={projectData}
isEdit
/>
<ConfigTaskPanel
isOpen={isCreatePanelOpen}
onDismiss={closeCreatePanel}
projectData={initialProjectData}
/>
</>
);
},
)(BaseDeployment);
// Extract this component so when every time the instruction being show,
// It will get the latest images
const UpdateModelInstruction = ({ newImagesCount, updateModel }) => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(getImages({ freezeRelabelImgs: false }));
}, [dispatch]);
if (newImagesCount)
return (
<Instruction
title={`${newImagesCount} new images have been added to your model!`}
subtitle="Update the model to improve your current deployment"
button={{ text: 'Update model', onClick: updateModel }}
styles={{ root: { margin: '0px 25px' } }}
/>
);
return null;
}; | the_stack |
import { MethodAbi } from 'ethereum-types';
export const simpleAbi: MethodAbi = {
constant: false,
inputs: [
{
name: 'greg',
type: 'uint256',
},
{
name: 'gregStr',
type: 'string',
},
],
name: 'simpleFunction',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
};
export const stringAbi: MethodAbi = {
constant: false,
inputs: [
{
name: 'greg',
type: 'string[]',
},
],
name: 'simpleFunction',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
};
export const GAbi: MethodAbi = {
constant: false,
inputs: [
{
components: [
{
name: 'a',
type: 'uint256',
},
{
name: 'b',
type: 'string',
},
{
name: 'e',
type: 'bytes',
},
{
name: 'f',
type: 'address',
},
],
name: 'f',
type: 'tuple',
},
],
name: 'simpleFunction',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
};
export const typesWithDefaultWidthsAbi: MethodAbi = {
constant: false,
inputs: [
{
name: 'someUint',
type: 'uint',
},
{
name: 'someInt',
type: 'int',
},
{
name: 'someByte',
type: 'byte',
},
{
name: 'someUint',
type: 'uint[]',
},
{
name: 'someInt',
type: 'int[]',
},
{
name: 'someByte',
type: 'byte[]',
},
],
name: 'simpleFunction',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
};
export const multiDimensionalArraysStaticTypeAbi: MethodAbi = {
constant: false,
inputs: [
{
name: 'a',
type: 'uint8[][][]',
},
{
name: 'b',
type: 'uint8[][][2]',
},
{
name: 'c',
type: 'uint8[][2][]',
},
{
name: 'd',
type: 'uint8[2][][]',
},
{
name: 'e',
type: 'uint8[][2][2]',
},
{
name: 'f',
type: 'uint8[2][2][]',
},
{
name: 'g',
type: 'uint8[2][][2]',
},
{
name: 'h',
type: 'uint8[2][2][2]',
},
],
name: 'simpleFunction',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
};
export const multiDimensionalArraysDynamicTypeAbi: MethodAbi = {
constant: false,
inputs: [
{
name: 'a',
type: 'string[][][]',
},
{
name: 'b',
type: 'string[][][2]',
},
{
name: 'c',
type: 'string[][2][]',
},
{
name: 'h',
type: 'string[2][2][2]',
},
],
name: 'simpleFunction',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
};
export const dynamicTupleAbi: MethodAbi = {
constant: false,
inputs: [
{
components: [
{
name: 'someUint',
type: 'uint256',
},
{
name: 'someStr',
type: 'string',
},
],
name: 'order',
type: 'tuple',
},
],
name: 'simpleFunction',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
};
export const arrayOfStaticTuplesWithDefinedLengthAbi: MethodAbi = {
constant: false,
inputs: [
{
components: [
{
name: 'someUint',
type: 'uint256',
},
{
name: 'someUint2',
type: 'uint256',
},
],
name: 'order',
type: 'tuple[8]',
},
],
name: 'simpleFunction',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
};
export const arrayOfStaticTuplesWithDynamicLengthAbi: MethodAbi = {
constant: false,
inputs: [
{
components: [
{
name: 'someUint',
type: 'uint256',
},
{
name: 'someUint2',
type: 'uint256',
},
],
name: 'order',
type: 'tuple[]',
},
],
name: 'simpleFunction',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
};
export const arrayOfDynamicTuplesWithDefinedLengthAbi: MethodAbi = {
constant: false,
inputs: [
{
components: [
{
name: 'someUint',
type: 'uint256',
},
{
name: 'someString',
type: 'string',
},
],
name: 'order',
type: 'tuple[8]',
},
],
name: 'simpleFunction',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
};
export const arrayOfDynamicTuplesWithUndefinedLengthAbi: MethodAbi = {
constant: false,
inputs: [
{
components: [
{
name: 'someUint',
type: 'uint256',
},
{
name: 'someString',
type: 'string',
},
],
name: 'order',
type: 'tuple[]',
},
],
name: 'simpleFunction',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
};
export const arrayOfDynamicTuplesAbi: MethodAbi = {
constant: false,
inputs: [
{
components: [
{
name: 'someUint',
type: 'uint256',
},
{
name: 'someString',
type: 'string',
},
],
name: 'order',
type: 'tuple[]',
},
],
name: 'simpleFunction',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
};
export const multidimensionalArrayOfDynamicTuplesAbi: MethodAbi = {
constant: false,
inputs: [
{
components: [
{
name: 'someUint',
type: 'uint256',
},
{
name: 'someString',
type: 'string',
},
],
name: 'order',
type: 'tuple[][2][]',
},
],
name: 'simpleFunction',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
};
export const staticTupleAbi: MethodAbi = {
constant: false,
inputs: [
{
components: [
{
name: 'someUint1',
type: 'uint256',
},
{
name: 'someUint2',
type: 'uint256',
},
{
name: 'someUint3',
type: 'uint256',
},
{
name: 'someBool',
type: 'bool',
},
],
name: 'order',
type: 'tuple',
},
],
name: 'simpleFunction',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
};
export const staticArrayAbi: MethodAbi = {
constant: false,
inputs: [
{
name: 'someStaticArray',
type: 'uint8[3]',
},
],
name: 'simpleFunction',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
};
export const staticArrayDynamicMembersAbi: MethodAbi = {
constant: false,
inputs: [
{
name: 'someStaticArray',
type: 'string[3]',
},
],
name: 'simpleFunction',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
};
export const dynamicArrayDynamicMembersAbi: MethodAbi = {
constant: false,
inputs: [
{
name: 'someStaticArray',
type: 'string[]',
},
],
name: 'simpleFunction',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
};
export const dynamicArrayStaticMembersAbi: MethodAbi = {
constant: false,
inputs: [
{
name: 'someStaticArray',
type: 'uint8[]',
},
],
name: 'simpleFunction',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
};
export const largeFlatAbi: MethodAbi = {
constant: false,
inputs: [
{
name: 'someUInt256',
type: 'uint256',
},
{
name: 'someInt256',
type: 'int256',
},
{
name: 'someInt32',
type: 'int32',
},
{
name: 'someByte',
type: 'byte',
},
{
name: 'someBytes32',
type: 'bytes32',
},
{
name: 'someBytes',
type: 'bytes',
},
{
name: 'someString',
type: 'string',
},
{
name: 'someAddress',
type: 'address',
},
{
name: 'someBool',
type: 'bool',
},
],
name: 'simpleFunction',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
};
export const largeNestedAbi: MethodAbi = {
constant: false,
inputs: [
{
name: 'someStaticArray',
type: 'uint8[3]',
},
{
name: 'someStaticArrayWithDynamicMembers',
type: 'string[2]',
},
{
name: 'someDynamicArrayWithDynamicMembers',
type: 'bytes[]',
},
{
name: 'some2DArray',
type: 'string[][]',
},
{
name: 'someTuple',
type: 'tuple',
components: [
{
name: 'someUint32',
type: 'uint32',
},
{
name: 'someStr',
type: 'string',
},
],
},
{
name: 'someTupleWithDynamicTypes',
type: 'tuple',
components: [
{
name: 'someUint',
type: 'uint256',
},
{
name: 'someStr',
type: 'string',
},
/*{
name: 'someStrArray',
type: 'string[]',
},*/
{
name: 'someBytes',
type: 'bytes',
},
{
name: 'someAddress',
type: 'address',
},
],
},
{
name: 'someArrayOfTuplesWithDynamicTypes',
type: 'tuple[]',
components: [
{
name: 'someUint',
type: 'uint256',
},
{
name: 'someStr',
type: 'string',
},
/*{
name: 'someStrArray',
type: 'string[]',
},*/
{
name: 'someBytes',
type: 'bytes',
},
{
name: 'someAddress',
type: 'address',
},
],
},
],
name: 'simpleFunction',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
};
export const nestedTuples: MethodAbi = {
constant: false,
inputs: [
{
name: 'firstTuple',
type: 'tuple[1]',
components: [
{
name: 'someUint32',
type: 'uint32',
},
{
name: 'nestedTuple',
type: 'tuple',
components: [
{
name: 'someUint',
type: 'uint256',
},
{
name: 'someAddress',
type: 'address',
},
],
},
],
},
{
name: 'secondTuple',
type: 'tuple[]',
components: [
{
name: 'someUint',
type: 'uint256',
},
{
name: 'someStr',
type: 'string',
},
{
name: 'nestedTuple',
type: 'tuple',
components: [
{
name: 'someUint32',
type: 'uint32',
},
{
name: 'secondNestedTuple',
type: 'tuple',
components: [
{
name: 'someUint',
type: 'uint256',
},
{
name: 'someStr',
type: 'string',
},
{
name: 'someBytes',
type: 'bytes',
},
{
name: 'someAddress',
type: 'address',
},
],
},
],
},
{
name: 'someBytes',
type: 'bytes',
},
{
name: 'someAddress',
type: 'address',
},
],
},
],
name: 'simpleFunction',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
};
export const simpleAbi2: MethodAbi = {
constant: false,
inputs: [
{
name: 'someByte',
type: 'byte',
},
{
name: 'someBytes32',
type: 'bytes32',
},
{
name: 'someBytes',
type: 'bytes',
},
{
name: 'someString',
type: 'string',
},
],
name: 'simpleFunction',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
};
export const fillOrderAbi: MethodAbi = {
constant: false,
inputs: [
{
components: [
{
name: 'makerAddress',
type: 'address',
},
{
name: 'takerAddress',
type: 'address',
},
{
name: 'feeRecipientAddress',
type: 'address',
},
{
name: 'senderAddress',
type: 'address',
},
{
name: 'makerAssetAmount',
type: 'uint256',
},
{
name: 'takerAssetAmount',
type: 'uint256',
},
{
name: 'makerFee',
type: 'uint256',
},
{
name: 'takerFee',
type: 'uint256',
},
{
name: 'expirationTimeSeconds',
type: 'uint256',
},
{
name: 'salt',
type: 'uint256',
},
{
name: 'makerAssetData',
type: 'bytes',
},
{
name: 'takerAssetData',
type: 'bytes',
},
],
name: 'order',
type: 'tuple',
},
{
name: 'takerAssetFillAmount',
type: 'uint256',
},
{
name: 'salt',
type: 'uint256',
},
{
name: 'orderSignature',
type: 'bytes',
},
{
name: 'takerSignature',
type: 'bytes',
},
],
name: 'fillOrder',
outputs: [],
payable: false,
stateMutability: 'nonpayable',
type: 'function',
}; | the_stack |
import { IThemeManager } from '@jupyterlab/apputils';
import { CommandRegistry } from '@lumino/commands';
import {
BasicKeyHandler,
BasicMouseHandler,
BasicSelectionModel,
DataGrid,
DataModel,
TextRenderer
} from '@lumino/datagrid';
import { ISignal, Signal } from '@lumino/signaling';
import { Panel } from '@lumino/widgets';
import { Debugger } from '../../';
import { IDebugger } from '../../tokens';
import { VariablesModel } from './model';
import {
ITranslator,
nullTranslator,
TranslationBundle
} from '@jupyterlab/translation';
/**
* A data grid that displays variables in a debugger session.
*/
export class VariablesBodyGrid extends Panel {
/**
* Instantiate a new VariablesBodyGrid.
*
* @param options The instantiation options for a VariablesBodyGrid.
*/
constructor(options: VariablesBodyGrid.IOptions) {
super();
const { model, commands, themeManager, scopes, translator } = options;
this._grid = new Grid({ commands, themeManager, translator });
this._grid.addClass('jp-DebuggerVariables-grid');
this._model = model;
this._model.changed.connect((model: VariablesModel): void => {
this._update();
}, this);
this._grid.dataModel.setData(scopes ?? []);
this.addWidget(this._grid);
this.addClass('jp-DebuggerVariables-body');
}
/**
* Get the latest hit variable
*/
get latestSelection(): IDebugger.IVariableSelection | null {
return this._grid.latestSelection;
}
/**
* Set the variable filter list.
*
* @param filter The variable filter to apply.
*/
set filter(filter: Set<string>) {
(this._grid.dataModel as GridModel).filter = filter;
this._update();
}
/**
* Set the current scope.
*
* @param scope The current scope for the variables.
*/
set scope(scope: string) {
(this._grid.dataModel as GridModel).scope = scope;
this._update();
}
/**
* Update the underlying data model
*/
private _update(): void {
this._grid.dataModel.setData(this._model.scopes ?? []);
}
private _grid: Grid;
private _model: IDebugger.Model.IVariables;
}
/**
* A namespace for `VariablesBodyGrid` statics.
*/
export namespace VariablesBodyGrid {
/**
* Instantiation options for `VariablesBodyGrid`.
*/
export interface IOptions {
/**
* The variables model.
*/
model: IDebugger.Model.IVariables;
/**
* The commands registry.
*/
commands: CommandRegistry;
/**
* The optional initial scopes data.
*/
scopes?: IDebugger.IScope[];
/**
* An optional application theme manager to detect theme changes.
*/
themeManager?: IThemeManager | null;
/**
* The application language translator.
*/
translator?: ITranslator;
}
}
/**
* A class wrapping the underlying variables datagrid.
*/
class Grid extends Panel {
/**
* Instantiate a new VariablesGrid.
*
* @param options The instantiation options for a VariablesGrid.
*/
constructor(options: Grid.IOptions) {
super();
const { commands, themeManager } = options;
const dataModel = new GridModel(options.translator);
const grid = new DataGrid();
const mouseHandler = new Private.MouseHandler();
mouseHandler.doubleClicked.connect((_, hit) =>
commands.execute(Debugger.CommandIDs.inspectVariable, {
variableReference: dataModel.getVariableReference(hit.row),
name: dataModel.getVariableName(hit.row)
})
);
mouseHandler.selected.connect((_, hit) => {
const { row } = hit;
this._latestSelection = {
name: dataModel.getVariableName(row),
value: dataModel.data('body', row, 1),
type: dataModel.data('body', row, 2),
variablesReference: dataModel.getVariableReference(row)
};
});
grid.dataModel = dataModel;
grid.keyHandler = new BasicKeyHandler();
grid.mouseHandler = mouseHandler;
grid.selectionModel = new BasicSelectionModel({
dataModel
});
grid.stretchLastColumn = true;
grid.node.style.height = '100%';
this._grid = grid;
// Compute the grid's styles based on the current theme.
if (themeManager) {
themeManager.themeChanged.connect(this._updateStyles, this);
}
this.addWidget(grid);
}
/**
* Set the variable filter list.
*
* @param filter The variable filter to apply.
*/
set filter(filter: Set<string>) {
(this._grid.dataModel as GridModel).filter = filter;
this.update();
}
/**
* Set the scope for the variables data model.
*
* @param scope The scopes for the variables
*/
set scope(scope: string) {
(this._grid.dataModel as GridModel).scope = scope;
this.update();
}
/**
* Get the data model for the data grid.
*/
get dataModel(): GridModel {
return this._grid.dataModel as GridModel;
}
/**
* Get the latest hit variable
*/
get latestSelection(): IDebugger.IVariableSelection | null {
return this._latestSelection;
}
/**
* Handle `after-attach` messages.
*
* @param message - The `after-attach` message.
*/
protected onAfterAttach(message: any): void {
super.onAfterAttach(message);
this._updateStyles();
}
/**
* Update the computed style for the data grid on theme change.
*/
private _updateStyles(): void {
const { style, textRenderer } = Private.computeStyle();
this._grid.cellRenderers.update({}, textRenderer);
this._grid.style = style;
}
private _grid: DataGrid;
private _latestSelection: IDebugger.IVariableSelection | null = null;
}
/**
* A namespace for VariablesGrid `statics`.
*/
namespace Grid {
/**
* Instantiation options for `VariablesGrid`.
*/
export interface IOptions {
/**
* The commands registry.
*/
commands: CommandRegistry;
/**
* An optional application theme manager to detect theme changes.
*/
themeManager?: IThemeManager | null;
/**
* The application language translator.
*/
translator?: ITranslator;
}
}
/**
* A data grid model for variables.
*/
class GridModel extends DataModel {
/**
* Create gird model
* @param translator optional translator
*/
constructor(translator?: ITranslator) {
super();
translator = translator || nullTranslator;
this._trans = translator.load('jupyterlab');
}
/**
* Set the variable filter list.
*/
set filter(filter: Set<string>) {
this._filter = filter;
}
/**
* Get the current scope for the variables.
*/
get scope(): string {
return this._scope;
}
/**
* Set the variable scope
*/
set scope(scope: string) {
this._scope = scope;
}
/**
* Get the row count for a particular region in the data grid.
*
* @param region The datagrid region.
*/
rowCount(region: DataModel.RowRegion): number {
return region === 'body' ? this._data.name.length : 1;
}
/**
* Get the column count for a particular region in the data grid.
*
* @param region The datagrid region.
*/
columnCount(region: DataModel.ColumnRegion): number {
return region === 'body' ? 2 : 1;
}
/**
* Get the data count for a particular region, row and column in the data grid.
*
* @param region The datagrid region.
* @param row The datagrid row
* @param column The datagrid column
*/
data(region: DataModel.CellRegion, row: number, column: number): any {
if (region === 'row-header') {
return this._data.name[row];
}
if (region === 'column-header') {
return column === 1 ? this._trans.__('Value') : this._trans.__('Type');
}
if (region === 'corner-header') {
return this._trans.__('Name');
}
return column === 1 ? this._data.value[row] : this._data.type[row];
}
/**
* Get the variable reference for a given row
*
* @param row The row in the datagrid.
*/
getVariableReference(row: number): number {
return this._data.variablesReference[row];
}
/**
* Get the variable name for a given row
*
* @param row The row in the datagrid.
*/
getVariableName(row: number): string {
return this._data.name[row];
}
/**
* Set the datagrid model data from the list of variables.
*
* @param scopes The list of variables.
*/
setData(scopes: IDebugger.IScope[]): void {
this._clearData();
this.emitChanged({
type: 'model-reset',
region: 'body'
});
const scope = scopes.find(scope => scope.name === this._scope) ?? scopes[0];
const variables = scope?.variables ?? [];
const filtered = variables.filter(
variable => variable.name && !this._filter.has(variable.name)
);
filtered.forEach((variable, index) => {
this._data.name[index] = variable.name;
this._data.type[index] = variable.type ?? '';
this._data.value[index] = variable.value;
this._data.variablesReference[index] = variable.variablesReference;
});
this.emitChanged({
type: 'rows-inserted',
region: 'body',
index: 1,
span: filtered.length
});
}
/**
* Clear all the data in the datagrid.
*/
private _clearData(): void {
this._data = {
name: [],
type: [],
value: [],
variablesReference: []
};
}
private _filter = new Set<string>();
private _scope = '';
private _trans: TranslationBundle;
private _data: {
name: string[];
type: string[];
value: string[];
variablesReference: number[];
} = {
name: [],
type: [],
value: [],
variablesReference: []
};
}
/**
* A namespace for private data.
*/
namespace Private {
/**
* Create a color palette element.
*/
function createPalette(): HTMLDivElement {
const div = document.createElement('div');
div.className = 'jp-DebuggerVariables-colorPalette';
div.innerHTML = `
<div class="jp-mod-void"></div>
<div class="jp-mod-background"></div>
<div class="jp-mod-header-background"></div>
<div class="jp-mod-grid-line"></div>
<div class="jp-mod-header-grid-line"></div>
<div class="jp-mod-selection"></div>
<div class="jp-mod-text"></div>
`;
return div;
}
/**
* Compute the style and renderer for a data grid.
*/
export function computeStyle(): {
style: DataGrid.Style;
textRenderer: TextRenderer;
} {
const palette = createPalette();
document.body.appendChild(palette);
let node: HTMLDivElement | null;
node = palette.querySelector('.jp-mod-void');
const voidColor = getComputedStyle(node!).color;
node = palette.querySelector('.jp-mod-background');
const backgroundColor = getComputedStyle(node!).color;
node = palette.querySelector('.jp-mod-header-background');
const headerBackgroundColor = getComputedStyle(node!).color;
node = palette.querySelector('.jp-mod-grid-line');
const gridLineColor = getComputedStyle(node!).color;
node = palette.querySelector('.jp-mod-header-grid-line');
const headerGridLineColor = getComputedStyle(node!).color;
node = palette.querySelector('.jp-mod-selection');
const selectionFillColor = getComputedStyle(node!).color;
node = palette.querySelector('.jp-mod-text');
const textColor = getComputedStyle(node!).color;
document.body.removeChild(palette);
return {
style: {
voidColor,
backgroundColor,
headerBackgroundColor,
gridLineColor,
headerGridLineColor,
rowBackgroundColor: (i: number): string =>
i % 2 === 0 ? voidColor : backgroundColor,
selectionFillColor
},
textRenderer: new TextRenderer({
font: '12px sans-serif',
textColor,
backgroundColor: '',
verticalAlignment: 'center',
horizontalAlignment: 'left'
})
};
}
/**
* A custom click handler to handle clicks on the variables grid.
*/
export class MouseHandler extends BasicMouseHandler {
/**
* A signal emitted when the variables grid is double clicked.
*/
get doubleClicked(): ISignal<this, DataGrid.HitTestResult> {
return this._doubleClicked;
}
/**
* A signal emitted when the variables grid received mouse down or context menu event.
*/
get selected(): ISignal<this, DataGrid.HitTestResult> {
return this._selected;
}
/**
* Dispose of the resources held by the mouse handler.
*/
dispose(): void {
if (this.isDisposed) {
return;
}
Signal.disconnectSender(this);
super.dispose();
}
/**
* Handle a mouse double-click event.
*
* @param grid The datagrid clicked.
* @param event The mouse event.
*/
onMouseDoubleClick(grid: DataGrid, event: MouseEvent): void {
const hit = grid.hitTest(event.clientX, event.clientY);
this._doubleClicked.emit(hit);
}
/**
* Handle the mouse down event for the data grid.
*
* @param grid - The data grid of interest.
*
* @param event - The mouse down event of interest.
*/
onMouseDown(grid: DataGrid, event: MouseEvent): void {
// Unpack the event.
let { clientX, clientY } = event;
// Hit test the grid.
let hit = grid.hitTest(clientX, clientY);
this._selected.emit(hit);
}
/**
* Handle the context menu event for the data grid.
*
* @param grid - The data grid of interest.
*
* @param event - The context menu event of interest.
*/
onContextMenu(grid: DataGrid, event: MouseEvent): void {
// Unpack the event.
let { clientX, clientY } = event;
// Hit test the grid.
let hit = grid.hitTest(clientX, clientY);
this._selected.emit(hit);
}
private _doubleClicked = new Signal<this, DataGrid.HitTestResult>(this);
private _selected = new Signal<this, DataGrid.HitTestResult>(this);
}
} | the_stack |
import React, { useEffect, useRef, useState } from 'react';
import { FaRegCheckCircle, FaRegTimesCircle, FaSpinner } from 'react-icons/fa';
import { motion } from 'framer-motion';
import { EntityType } from 'providers/Project';
import { useProject } from 'providers/Project/projectHooks';
import {
Account,
ResultType,
useSetExecutionResultsMutation,
} from 'api/apollo/generated/graphql';
import { ArgumentsProps } from 'components/Arguments/types';
import { ExecuteCommandRequest } from 'monaco-languageclient';
import { ControlContainer, HoverPanel, StatusMessage } from './styles';
import {
ActionButton,
ArgumentsList,
ArgumentsTitle,
ErrorsList,
Hints,
Signers,
} from './components';
const isDictionaary = (type:string) => type.includes("{")
const isArray = (type:string) => type.includes("[")
const isImportedType = (type:string) => type.includes(".")
const isComplexType = (type:string)=> isDictionaary(type)
|| isArray(type)
|| isImportedType(type)
const startsWith = (value : string, prefix: string) => {
return value.startsWith(prefix) || value.startsWith("U"+prefix)
}
const checkJSON = (value: any, type: string) => {
try{
JSON.parse(value)
return null
} catch (e){
return `Not a valid argument of type ${type}`
}
}
const validateByType = (
value: any,
type: string,
) => {
if (value.length === 0) {
return "Value can't be empty";
}
switch (true) {
// Strings
case type === 'String': {
return null; // no need to validate String for now
}
// Integers
case startsWith(type,'Int'): {
if (isNaN(value) || value === '') {
return 'Should be a valid Integer number';
}
return null;
}
// Words
case startsWith(type,'Word'): {
if (isNaN(value) || value === '') {
return 'Should be a valid Word number';
}
return null;
}
// Fixed Point
case startsWith(type, 'Fix'): {
if (isNaN(value) || value === '') {
return 'Should be a valid fixed point number';
}
return null;
}
case isComplexType(type): {
// This case it to catch complex arguments like Dictionaries
return checkJSON(value, type);
}
// Address
case type === 'Address': {
if (!value.match(/(^0x[\w\d]{16})|(^0x[\w\d]{1,4})/)) {
return 'Not a valid Address';
}
return null;
}
// Booleans
case type === 'Bool': {
if (value !== 'true' && value !== 'false') {
return 'Boolean values can be either true or false';
}
return null;
}
default: {
return null;
}
}
};
const getLabel = (
resultType: ResultType,
project: any,
index: number,
): string => {
return resultType === ResultType.Contract
? 'Deployment'
: resultType === ResultType.Script
? project.scriptTemplates[index].title
: resultType === ResultType.Transaction
? project.transactionTemplates[index].title
: 'Interaction';
};
type ScriptExecution = (args?: string[]) => Promise<any>;
type TransactionExecution = (
signingAccounts: Account[],
args?: string[],
) => Promise<any>;
type DeployExecution = () => Promise<any>;
type ProcessingArgs = {
disabled: boolean;
scriptFactory?: ScriptExecution;
transactionFactory?: TransactionExecution;
contractDeployment?: DeployExecution;
};
const useTemplateType = (): ProcessingArgs => {
const { isSavingCode } = useProject();
const {
createScriptExecution,
createTransactionExecution,
updateAccountDeployedCode,
} = useProject();
return {
disabled: isSavingCode,
scriptFactory: createScriptExecution,
transactionFactory: createTransactionExecution,
contractDeployment: updateAccountDeployedCode,
};
};
interface IValue {
[key: string]: string;
}
const Arguments: React.FC<ArgumentsProps> = (props) => {
const { type, list, signers } = props;
const { goTo, hover, hideDecorations, problems } = props;
const validCode = problems.error.length === 0;
const needSigners = type == EntityType.TransactionTemplate && signers > 0;
const [selected, updateSelectedAccounts] = useState([]);
const [errors, setErrors] = useState({})
const [expanded, setExpanded] = useState(true);
const [values, setValue] = useState<IValue>({});
const constraintsRef = useRef();
// const errors = validate(list, values);
const numberOfErrors = Object.keys(errors).length;
const notEnoughSigners = needSigners && selected.length < signers;
const haveErrors = numberOfErrors > 0 || notEnoughSigners;
const validate = (list: any, values: any) => {
const errors = list.reduce((acc: any, item: any) => {
const { name, type } = item;
const value = values[name];
if (value) {
const error = validateByType(value, type);
if (error) {
acc[name] = error;
}
} else {
if (type !== 'String') {
acc[name] = "Value can't be empty";
}
}
return acc;
}, {});
console.log({errors});
setErrors(errors);
};
useEffect(()=>{
validate(list, values)
}, [list, values]);
const [processingStatus, setProcessingStatus] = useState(false);
const [setResult] = useSetExecutionResultsMutation();
const {
scriptFactory,
transactionFactory,
contractDeployment,
} = useTemplateType();
const { project, active, isSavingCode } = useProject();
const { accounts } = project;
const signersAccounts = selected.map((i) => accounts[i]);
const send = async () => {
if (!processingStatus) {
setProcessingStatus(true);
}
// TODO: implement algorithm for drilling down dictionaries
const fixed = list.map((arg) => {
const { name, type } = arg;
let value = values[name];
// We probably better fix this on server side...
if (type === 'UFix64') {
if (value.indexOf('.') < 0) {
value = `${value}.0`;
}
}
return value;
});
const formatted = await props.languageClient.sendRequest(
ExecuteCommandRequest.type,
{
command: 'cadence.server.parseEntryPointArguments',
arguments: [
props.editor.getModel().uri.toString(),
fixed
],
},
);
// Map values to strings that will be passed to backend
const args:any = list.map((arg, index) => {
const { type } = arg;
const value = fixed[index]
// If we have a complex type - return value formatted by language server
if ( isComplexType(type)){
return JSON.stringify(formatted[index])
}
return JSON.stringify({ value, type });
});
let rawResult, resultType;
try {
switch (type) {
case EntityType.ScriptTemplate: {
resultType = ResultType.Script;
rawResult = await scriptFactory(args);
break;
}
case EntityType.TransactionTemplate: {
resultType = ResultType.Transaction;
rawResult = await transactionFactory(signersAccounts, args);
break;
}
case EntityType.Account: {
// Ask if user wants to redeploy the contract
if (accounts[active.index] && accounts[active.index].deployedCode) {
const choiceMessage =
'Redeploying will clear the state of all accounts. Proceed?';
if (!confirm(choiceMessage)) {
setProcessingStatus(false);
return;
}
}
resultType = ResultType.Contract;
rawResult = await contractDeployment();
break;
}
default:
break;
}
} catch (e) {
console.error(e);
rawResult = e.toString();
}
setProcessingStatus(false);
// Display result in the bottom area
setResult({
variables: {
label: getLabel(resultType, project, active.index),
resultType,
rawResult,
},
});
};
const isOk = !haveErrors && validCode !== undefined && !!validCode;
let statusIcon = isOk ? <FaRegCheckCircle /> : <FaRegTimesCircle />;
let statusMessage = isOk ? 'Ready' : 'Fix errors';
const progress = isSavingCode || processingStatus;
if (progress) {
statusIcon = <FaSpinner className="spin" />;
statusMessage = 'Please, wait...';
}
const actions = { goTo, hover, hideDecorations };
return (
<>
<div ref={constraintsRef} className="constraints" />
<motion.div
className="drag-box"
drag={true}
dragConstraints={constraintsRef}
dragElastic={1}
>
<HoverPanel>
{validCode && (
<>
{list.length > 0 && (
<>
<ArgumentsTitle
type={type}
errors={numberOfErrors}
expanded={expanded}
setExpanded={setExpanded}
/>
<ArgumentsList
list={list}
errors={errors}
hidden={!expanded}
onChange={(name, value) => {
let key = name.toString();
let newValue = { ...values, [key]: value };
setValue(newValue);
}}
/>
</>
)}
{needSigners && (
<Signers
maxSelection={signers}
selected={selected}
updateSelectedAccounts={updateSelectedAccounts}
/>
)}
</>
)}
<ErrorsList list={problems.error} {...actions} />
<Hints problems={problems} {...actions} />
<ControlContainer isOk={isOk} progress={progress}>
<StatusMessage>
{statusIcon}
<p>{statusMessage}</p>
</StatusMessage>
<ActionButton active={isOk} type={type} onClick={send} />
</ControlContainer>
</HoverPanel>
</motion.div>
</>
);
};
export default Arguments; | the_stack |
import * as THREE from 'three';
import { WORLD_SIZE, getPositions, DOME_SCENES } from '../../../utils/lba';
import { GROUND_TYPES } from './grid';
import { BehaviourMode } from '../../loop/hero';
import { AnimType } from '../../data/animType';
import Actor from '../../Actor';
import { Time } from '../../../datatypes';
import Scene from '../../Scene';
import { getParams } from '../../../params';
import Extra from '../../Extra';
const STEP = 1 / WORLD_SIZE;
const HALF_BRICK = 1 / 32;
const CONVEYOR_SPEED = 0.05;
// Vertical height offsets for the jet/protopack.
const JETPACK_OFFSET = 0.03;
const PROTOPACK_OFFSET = 0.0075;
// How fast we reach top vertical height when starting to jetpack.
const JETPACK_VERTICAL_SPEED = 0.275;
interface LayoutInfo {
index: number;
center: THREE.Vector3;
key: string;
}
export default class IsoSceneryPhysics {
grid: any;
constructor(grid) {
this.grid = grid;
}
getNormal(
_scene: Scene,
position: THREE.Vector3,
boundingBox: THREE.Box3,
result: THREE.Vector3
) {
POSITION.copy(position);
POSITION.multiplyScalar(STEP);
const dx = 64 - Math.floor(POSITION.x * 32);
const dz = Math.floor(POSITION.z * 32);
if (this.grid.cells[(dx * 64) + dz]) {
const cell = this.grid.cells[(dx * 64) + dz];
for (let i = cell.columns.length - 1; i >= 0; i -= 1) {
const column = cell.columns[i];
const bb = column.box;
const y = getColumnY(column, POSITION);
const minY = i > 0 ? bb.min.y : -Infinity;
if (POSITION.y >= minY) {
if (POSITION.y < y + 0.01) {
result.set(0, 1, 0);
return true;
}
}
}
}
ACTOR_BOX.copy(boundingBox);
ACTOR_BOX.min.multiplyScalar(STEP);
ACTOR_BOX.max.multiplyScalar(STEP);
ACTOR_BOX.translate(POSITION);
for (let ox = -1; ox < 2; ox += 1) {
for (let oz = -1; oz < 2; oz += 1) {
const cell = this.grid.cells[((dx + ox) * 64) + (dz + oz)];
if (!cell || cell.columns.length === 0) {
continue;
}
for (let i = 0; i < cell.columns.length; i += 1) {
const column = cell.columns[i];
BB.copy(column.box);
if (column.shape !== 1) {
BB.max.y -= STEP;
}
if (ACTOR_BOX.intersectsBox(BB)) {
INTERSECTION.copy(ACTOR_BOX);
INTERSECTION.intersect(BB);
INTERSECTION.getSize(ITRS_SIZE);
ACTOR_BOX.getCenter(CENTER1);
BB.getCenter(CENTER2);
const dir = CENTER1.sub(CENTER2);
if (ITRS_SIZE.x < ITRS_SIZE.z) {
result.set(1 * Math.sign(dir.x), 0, 0).normalize();
} else {
result.set(0, 0, 1 * Math.sign(dir.z)).normalize();
}
return true;
}
}
}
}
return false;
}
getLayoutInfo(position: THREE.Vector3, layoutInfo: LayoutInfo) {
POSITION.copy(position);
POSITION.multiplyScalar(STEP);
layoutInfo.index = -1;
layoutInfo.center.set(0, 0, 0);
layoutInfo.key = 'none';
const dx = 64 - Math.floor(POSITION.x * 32);
const dz = Math.floor(POSITION.z * 32);
if (this.grid.cells[(dx * 64) + dz]) {
const cell = this.grid.cells[(dx * 64) + dz];
for (let i = cell.columns.length - 1; i >= 0; i -= 1) {
const column = cell.columns[i];
const bb = column.box;
const cY = getColumnY(column, POSITION);
const minY = i > 0 ? bb.min.y : -Infinity;
if (POSITION.y >= minY) {
if (POSITION.y < cY + 0.015625) {
const block = cell.blocks[bb.max.y * 64 - 1];
if (block) {
const layout = this.grid.library.layouts[block.layout];
const idx = block.block;
const { nX: nZ, nY, nZ: nX } = layout;
const x = Math.floor(idx / (nZ * nY));
// const y = Math.floor(idx / nZ) % nY;
const z = idx % nZ;
const wx = dx - x;
const wz = dz - z;
const cx = wx + nX * 0.5;
const cz = wz + nZ * 0.5;
layoutInfo.index = block.layout;
layoutInfo.center.set(
2 - cx * HALF_BRICK + HALF_BRICK,
cY,
cz * HALF_BRICK,
).multiplyScalar(WORLD_SIZE);
layoutInfo.key = `${wx},${wz}`;
}
break;
}
}
}
}
}
processCollisions(scene: Scene, obj: Actor | Extra, time: Time) {
if (!obj.props.flags.hasCollisionBricks) {
return false;
}
const isUsingProtoOrJetpack = obj instanceof Actor &&
(obj.props.entityIndex === BehaviourMode.JETPACK ||
obj.props.entityIndex === BehaviourMode.PROTOPACK) &&
obj.props.animIndex === AnimType.FORWARD;
const isLBA1 = getParams().game === 'lba1';
const basePos = obj.threeObject.position.clone();
const position = obj.physics.position.clone();
basePos.multiplyScalar(STEP);
position.multiplyScalar(STEP);
const dx = 64 - Math.floor(position.x * 32);
const dz = Math.floor(position.z * 32);
const cell = this.grid.cells[(dx * 64) + dz];
if (obj instanceof Actor) { // if it's an actor
obj.state.floorSound = -1;
obj.state.floorSound2 = -1;
}
let isTouchingGround = false;
let groundHeight = -1;
if (cell
&& (obj.props.flags.hasCollisionFloor
|| obj.props.flags.canFall)) {
for (let i = cell.columns.length - 1; i >= 0; i -= 1) {
const column = cell.columns[i];
const bb = column.box;
const y = getColumnY(column, position);
if (obj instanceof Actor) {
obj.state.floorSound = column.sound;
obj.state.floorSound2 = column.sound2;
}
let minY = i > 0 ? bb.min.y : -Infinity;
if (y - position.y < 0.12 &&
column.shape >= 2 && column.shape <= 5) {
minY = -Infinity;
}
if (basePos.y >= minY) {
groundHeight = y;
if (position.y < y) {
const newY = Math.max(y, position.y);
if (newY - position.y < 0.12 && !isUsingProtoOrJetpack) {
position.y = newY;
isTouchingGround = true;
if (obj instanceof Actor) {
switch (column.groundType) {
case GROUND_TYPES.WATER:
case GROUND_TYPES.WATER2:
// Dome of the slate
if (DOME_SCENES.includes(scene.index)) {
obj.state.isDrowningStars = true;
} else {
obj.state.isDrowning = true;
}
break;
case GROUND_TYPES.LAVA:
obj.state.isDrowningLava = true;
break;
case GROUND_TYPES.CAVE_SPIKES:
if (obj.animState
&& !obj.state.isJumping
&& !obj.state.isHit
&& obj.props.animIndex !== AnimType.HIT) {
obj.hit(-1, 5);
}
break;
}
}
}
if (!isLBA1) {
processConveyor(column, position, time);
}
break;
}
}
}
}
let height = groundHeight;
if (!isTouchingGround && obj instanceof Actor && obj.index === 0) {
ACTOR_BOX.copy(obj.model.boundingBox);
ACTOR_BOX.min.multiplyScalar(STEP);
ACTOR_BOX.max.multiplyScalar(STEP);
ACTOR_BOX.translate(position);
let floorHeight = null;
for (const pos of getPositions(ACTOR_BOX)) {
const fh = getFloorHeight(this.grid, obj, pos);
if (floorHeight === null || fh < floorHeight) {
floorHeight = fh;
}
}
if (floorHeight > 0) {
height = floorHeight;
}
}
obj.state.distFromGround = Math.max(position.y - groundHeight, 0) * WORLD_SIZE;
obj.state.distFromFloor = Math.max(position.y - height, 0) * WORLD_SIZE;
obj.state.isTouchingGround = isTouchingGround;
if (obj instanceof Actor) {
obj.state.isUsingProtoOrJetpack = isUsingProtoOrJetpack;
}
if (isUsingProtoOrJetpack) {
let heightOffset = PROTOPACK_OFFSET;
if (obj instanceof Actor && obj.props.entityIndex === BehaviourMode.JETPACK) {
heightOffset = JETPACK_OFFSET;
}
if (height - position.y < heightOffset) {
const wantHeight = height + heightOffset;
const diff = wantHeight - position.y;
if (diff <= 0) {
position.y -= JETPACK_VERTICAL_SPEED * time.delta;
position.y = Math.max(wantHeight, position.y);
} else {
position.y += JETPACK_VERTICAL_SPEED * time.delta;
position.y = Math.min(wantHeight, position.y);
}
}
}
position.y = Math.max(0, position.y);
if (obj.props.flags.hasCollisionBricks) {
isTouchingGround = processBoxIntersections(
this.grid,
obj,
position,
dx,
dz,
isTouchingGround,
obj instanceof Actor && (obj as Actor).props.flags.hasCollisionBricksLow
);
}
position.multiplyScalar(WORLD_SIZE);
obj.physics.position.copy(position);
return isTouchingGround;
}
getFloorHeight(position: THREE.Vector3) {
return getFloorHeightSimple(this.grid, position);
}
processCameraCollisions() {
// TODO
}
}
function getColumnY(column, position: THREE.Vector3) {
const bb = column.box;
switch (column.shape) {
case 2:
return bb.max.y - ((1 - ((position.z * 32) % 1)) / 64);
case 3:
return bb.max.y - (((position.x * 32) % 1) / 64);
case 4:
return bb.max.y - ((1 - ((position.x * 32) % 1)) / 64);
case 5:
return bb.max.y - (((position.z * 32) % 1) / 64);
case 1:
default:
return bb.max.y;
}
}
const POSITION = new THREE.Vector3();
const ACTOR_BOX = new THREE.Box3();
const INTERSECTION = new THREE.Box3();
const ITRS_SIZE = new THREE.Vector3();
const CENTER1 = new THREE.Vector3();
const CENTER2 = new THREE.Vector3();
const DIFF = new THREE.Vector3();
const BB = new THREE.Box3();
function getFloorHeight(grid, actor: Actor, position: THREE.Vector3) {
POSITION.copy(position);
const dx = 64 - Math.floor(position.x * 32);
const dz = Math.floor(position.z * 32);
const groundCell = grid.cells[(dx * 64) + dz];
while (true) {
if (POSITION.y <= -1) {
return -1;
}
for (let i = groundCell.columns.length - 1; i >= 0; i -= 1) {
const column = groundCell.columns[i];
const bb = column.box;
const y = getColumnY(column, POSITION);
const minY = i > 0 ? bb.min.y : -Infinity;
if (POSITION.y >= minY && POSITION.y < y) {
if (Math.max(y, POSITION.y) - POSITION.y < 0.12) {
return y;
}
}
}
ACTOR_BOX.copy(actor.model.boundingBox);
ACTOR_BOX.min.multiplyScalar(STEP);
ACTOR_BOX.max.multiplyScalar(STEP);
ACTOR_BOX.translate(POSITION);
DIFF.set(0, 1 / 128, 0);
ACTOR_BOX.translate(DIFF);
for (let ox = -1; ox < 2; ox += 1) {
for (let oz = -1; oz < 2; oz += 1) {
const cell = grid.cells[((dx + ox) * 64) + (dz + oz)];
if (cell && cell.columns.length > 0) {
for (let i = 0; i < cell.columns.length; i += 1) {
const column = cell.columns[i];
BB.copy(column.box);
if (column.shape !== 1) {
BB.max.y -= STEP;
}
if (ACTOR_BOX.intersectsBox(BB)) {
return BB.max.y;
}
}
}
}
}
POSITION.y -= 0.01;
}
}
function getFloorHeightSimple(grid, position: THREE.Vector3) {
POSITION.copy(position);
POSITION.multiplyScalar(STEP);
const dx = 64 - Math.floor(POSITION.x * 32);
const dz = Math.floor(POSITION.z * 32);
const groundCell = grid.cells[(dx * 64) + dz];
if (!groundCell) {
return -1;
}
for (let i = groundCell.columns.length - 1; i >= 0; i -= 1) {
const column = groundCell.columns[i];
const y = getColumnY(column, POSITION);
if (POSITION.y >= y) {
return y * WORLD_SIZE;
}
}
return -1;
}
function processBoxIntersections(
grid,
obj: Actor | Extra,
position: THREE.Vector3,
dx: number,
dz: number,
isTouchingGround: boolean,
lowCollisions: boolean
) {
const boundingBox = obj.model.boundingBox;
ACTOR_BOX.copy(boundingBox);
ACTOR_BOX.min.multiplyScalar(STEP);
ACTOR_BOX.max.multiplyScalar(STEP);
ACTOR_BOX.translate(position);
ACTOR_BOX.min.y += 1 / 128;
// The lowCollisions flag indicates crawling.
if (lowCollisions) {
ACTOR_BOX.max.y = ACTOR_BOX.min.y + (ACTOR_BOX.max.y - ACTOR_BOX.min.y) / 2;
}
let collision = false;
for (let ox = -1; ox < 2; ox += 1) {
for (let oz = -1; oz < 2; oz += 1) {
const cell = grid.cells[((dx + ox) * 64) + (dz + oz)];
if (cell && cell.columns.length > 0) {
for (let i = 0; i < cell.columns.length; i += 1) {
const column = cell.columns[i];
BB.copy(column.box);
if (column.shape !== 1) {
BB.max.y -= STEP;
}
if (intersectBox(obj, position)) {
collision = true;
}
}
} else {
BB.min.set((64 - (dx + ox)) / 32, -Infinity, (dz + oz) / 32);
BB.max.set((65 - (dx + ox)) / 32, Infinity, (dz + oz + 1) / 32);
if (intersectBox(obj, position)) {
collision = true;
}
isTouchingGround = false;
}
}
}
obj.state.isColliding = collision;
return isTouchingGround;
}
function intersectBox(actor: Actor | Extra, position: THREE.Vector3) {
if (ACTOR_BOX.intersectsBox(BB)) {
INTERSECTION.copy(ACTOR_BOX);
INTERSECTION.intersect(BB);
INTERSECTION.getSize(ITRS_SIZE);
ACTOR_BOX.getCenter(CENTER1);
BB.getCenter(CENTER2);
const dir = CENTER1.sub(CENTER2);
if (ITRS_SIZE.x < ITRS_SIZE.z) {
DIFF.set(ITRS_SIZE.x * Math.sign(dir.x), 0, 0);
} else {
DIFF.set(0, 0, ITRS_SIZE.z * Math.sign(dir.z));
}
actor.physics.position.add(DIFF);
position.add(DIFF);
ACTOR_BOX.translate(DIFF);
return true;
}
return false;
}
function processConveyor(column, position: THREE.Vector3, time: Time) {
switch (column.groundType) {
case GROUND_TYPES.CONVEYOR_BOTTOM_RIGHT_TOP_LEFT:
position.z -= CONVEYOR_SPEED * time.delta;
break;
case GROUND_TYPES.CONVEYOR_TOP_LEFT_BOTTOM_RIGHT:
position.z += CONVEYOR_SPEED * time.delta;
break;
case GROUND_TYPES.CONVEYOR_BOTTOM_LEFT_TOP_RIGHT:
position.x += CONVEYOR_SPEED * time.delta;
break;
case GROUND_TYPES.CONVEYOR_TOP_RIGHT_BOTTOM_LEFT:
position.x -= CONVEYOR_SPEED * time.delta;
break;
}
} | the_stack |
import {
arrayWith,
countResources,
countResourcesLike,
deepObjectLike,
expect as expectCDK,
haveResource,
haveResourceLike,
not,
ABSENT,
notMatching,
stringLike,
} from '@aws-cdk/assert';
import {
AutoScalingGroup,
CfnAutoScalingGroup,
} from '@aws-cdk/aws-autoscaling';
import {
IMetric,
Metric,
} from '@aws-cdk/aws-cloudwatch';
import {
AmazonLinuxGeneration,
AmazonLinuxImage,
Connections,
InstanceClass,
InstanceSize,
InstanceType,
IVpc,
SecurityGroup,
SubnetType,
Vpc,
} from '@aws-cdk/aws-ec2';
import {IApplicationLoadBalancerTarget} from '@aws-cdk/aws-elasticloadbalancingv2';
import {
IPolicy,
Policy,
PolicyStatement,
} from '@aws-cdk/aws-iam';
import {
Key,
} from '@aws-cdk/aws-kms';
import {
App,
CfnElement,
Construct,
Names,
Stack,
} from '@aws-cdk/core';
import {
HealthMonitor,
IMonitorableFleet,
} from '../lib';
import {
testConstructTags,
} from './tag-helpers';
let app: App;
let infraStack: Stack;
let hmStack: Stack;
let wfStack: Stack;
let vpc: IVpc;
let healthMonitor: HealthMonitor;
class TestMonitorableFleet extends Construct implements IMonitorableFleet {
public readonly connections: Connections;
public readonly targetCapacity: number;
public readonly targetCapacityMetric: IMetric;
public readonly targetScope: Construct;
public readonly targetToMonitor: IApplicationLoadBalancerTarget;
public readonly targetUpdatePolicy: IPolicy;
constructor(scope: Construct, id: string, props: {
vpc: IVpc,
minCapacity?: number,
}) {
super(scope, id);
const fleet = new AutoScalingGroup(this, 'ASG', {
instanceType: InstanceType.of(InstanceClass.T2, InstanceSize.LARGE),
machineImage: new AmazonLinuxImage({
generation: AmazonLinuxGeneration.AMAZON_LINUX_2,
}),
vpc: props.vpc,
minCapacity: props.minCapacity,
});
this.connections = new Connections();
this.targetCapacity = parseInt((fleet.node.defaultChild as CfnAutoScalingGroup).maxSize, 10);
this.targetScope = this;
this.targetToMonitor = fleet;
this.targetCapacityMetric = new Metric({
namespace: 'AWS/AutoScaling',
metricName: 'GroupDesiredCapacity',
dimensions: {
AutoScalingGroupName: fleet.autoScalingGroupName,
},
label: 'GroupDesiredCapacity',
});
this.targetUpdatePolicy = new Policy(this, 'ASGUpdatePolicy', {
statements: [new PolicyStatement({
actions: ['autoscaling:UpdateAutoScalingGroup'],
resources: [fleet.autoScalingGroupArn],
})],
});
}
}
describe('HealthMonitor', () => {
beforeEach(() => {
app = new App();
infraStack = new Stack(app, 'infraStack');
hmStack = new Stack(app, 'hmStack');
wfStack = new Stack(app, 'wfStack');
vpc = new Vpc(infraStack, 'VPC');
});
test('validating default health monitor properties', () => {
// WHEN
healthMonitor = new HealthMonitor(hmStack, 'healthMonitor', {
vpc,
});
// THEN
expectCDK(hmStack).notTo(haveResource('AWS::ElasticLoadBalancingV2::LoadBalancer'));
expectCDK(hmStack).to(haveResourceLike('AWS::KMS::Key', {
KeyPolicy: {
Statement: [
{
Action: 'kms:*',
Effect: 'Allow',
Principal: {
AWS: {
'Fn::Join': [
'',
[
'arn:',
{
Ref: 'AWS::Partition',
},
':iam::',
{
Ref: 'AWS::AccountId',
},
':root',
],
],
},
},
Resource: '*',
},
{
Action: [
'kms:Decrypt',
'kms:GenerateDataKey',
],
Effect: 'Allow',
Principal: {
Service: 'cloudwatch.amazonaws.com',
},
Resource: '*',
},
],
},
Description: `This key is used to encrypt SNS messages for ${Names.uniqueId(healthMonitor)}.`,
EnableKeyRotation: true,
}));
expectCDK(hmStack).to(haveResourceLike('AWS::SNS::TopicPolicy', {
PolicyDocument: {
Statement: [
{
Action: 'sns:Publish',
Effect: 'Allow',
Principal: {
Service: 'cloudwatch.amazonaws.com',
},
Resource: {
Ref: hmStack.getLogicalId(healthMonitor.unhealthyFleetActionTopic.node.defaultChild as CfnElement),
},
Sid: '0',
},
],
},
Topics: [
{
Ref: hmStack.getLogicalId(healthMonitor.unhealthyFleetActionTopic.node.defaultChild as CfnElement),
},
],
}));
expectCDK(hmStack).to(haveResourceLike('AWS::SNS::Topic', {
KmsMasterKeyId: {
'Fn::GetAtt': [
`${hmStack.getLogicalId(healthMonitor.node.findChild('SNSEncryptionKey').node.defaultChild as CfnElement)}`,
'Arn',
],
},
}));
expectCDK(hmStack).to(haveResource('AWS::Lambda::Function'));
expectCDK(hmStack).to(haveResourceLike('AWS::SNS::Subscription', {
Protocol: 'lambda',
TopicArn: {
Ref: `${infraStack.getLogicalId(healthMonitor.node.findChild('UnhealthyFleetTopic').node.defaultChild as CfnElement)}`,
},
Endpoint: {
'Fn::GetAtt': [
'unhealthyFleetTermination28bccf6aaa76478c9239e2f5bcc0254c8C612A5E',
'Arn',
],
},
}));
});
test('validating health monitor properties while passing a key', () => {
// WHEN
healthMonitor = new HealthMonitor(hmStack, 'healthMonitor', {
vpc,
encryptionKey: Key.fromKeyArn(hmStack, 'importedKey', 'arn:aws:kms:us-west-2:123456789012:key/testarn'),
});
// THEN
expectCDK(hmStack).notTo(haveResource('AWS::ElasticLoadBalancingV2::LoadBalancer'));
expectCDK(hmStack).notTo(haveResource('AWS::KMS::Key'));
expectCDK(hmStack).to(haveResourceLike('AWS::SNS::Topic', {
KmsMasterKeyId: 'arn:aws:kms:us-west-2:123456789012:key/testarn',
}));
expectCDK(hmStack).to(haveResource('AWS::Lambda::Function'));
expectCDK(hmStack).to(haveResourceLike('AWS::SNS::Subscription', {
Protocol: 'lambda',
TopicArn: {
Ref: `${infraStack.getLogicalId(healthMonitor.node.findChild('UnhealthyFleetTopic').node.defaultChild as CfnElement)}`,
},
Endpoint: {
'Fn::GetAtt': [
'unhealthyFleetTermination28bccf6aaa76478c9239e2f5bcc0254c8C612A5E',
'Arn',
],
},
}));
});
test('validating the target with default health config', () => {
// WHEN
healthMonitor = new HealthMonitor(hmStack, 'healthMonitor', {
vpc,
});
const fleet = new TestMonitorableFleet(wfStack, 'workerFleet', {
vpc,
});
healthMonitor.registerFleet(fleet, {});
// THEN
expectCDK(wfStack).to(haveResource('AWS::ElasticLoadBalancingV2::Listener'));
expectCDK(hmStack).notTo((haveResourceLike('AWS::EC2::SecurityGroup', {
SecurityGroupIngress: arrayWith(deepObjectLike({
CidrIp: '0.0.0.0/0',
FromPort: 8081,
IpProtocol: 'tcp',
ToPort: 8081,
})),
})));
expectCDK(wfStack).to(haveResourceLike('AWS::ElasticLoadBalancingV2::TargetGroup', {
HealthCheckIntervalSeconds: 300,
HealthCheckPort: '8081',
HealthCheckProtocol: 'HTTP',
Port: 8081,
Protocol: 'HTTP',
TargetType: 'instance',
}));
expectCDK(wfStack).to(haveResource('AWS::CloudWatch::Alarm'));
});
test('validating the target with custom health config', () => {
// WHEN
healthMonitor = new HealthMonitor(hmStack, 'healthMonitor', {
vpc,
});
const fleet = new TestMonitorableFleet(wfStack, 'workerFleet', {
vpc,
});
healthMonitor.registerFleet(fleet, {
port: 7171,
});
// THEN
expectCDK(wfStack).to(haveResource('AWS::ElasticLoadBalancingV2::Listener'));
expectCDK(wfStack).to(haveResourceLike('AWS::ElasticLoadBalancingV2::TargetGroup', {
HealthCheckIntervalSeconds: 300,
HealthCheckPort: '7171',
HealthCheckProtocol: 'HTTP',
Port: 8081,
Protocol: 'HTTP',
TargetType: 'instance',
}));
expectCDK(wfStack).to(haveResource('AWS::CloudWatch::Alarm'));
});
test('2 ASG gets registered to same LB', () => {
// WHEN
healthMonitor = new HealthMonitor(hmStack, 'healthMonitor', {
vpc,
});
const fleet = new TestMonitorableFleet(wfStack, 'workerFleet', {
vpc,
});
healthMonitor.registerFleet(fleet, {port: 7171});
const fleet2 = new TestMonitorableFleet(wfStack, 'workerFleet2', {
vpc,
});
healthMonitor.registerFleet(fleet2, {port: 7171});
// THEN
expectCDK(hmStack).to(countResourcesLike('AWS::ElasticLoadBalancingV2::LoadBalancer', 1, {
LoadBalancerAttributes: [
{
Key: 'deletion_protection.enabled',
Value: 'true',
},
],
Scheme: 'internal',
}));
expectCDK(wfStack).to(countResources('AWS::ElasticLoadBalancingV2::Listener', 2));
expectCDK(wfStack).to(haveResource('AWS::ElasticLoadBalancingV2::Listener'));
expectCDK(wfStack).to(haveResourceLike('AWS::ElasticLoadBalancingV2::TargetGroup', {
HealthCheckIntervalSeconds: 300,
HealthCheckPort: '7171',
HealthCheckProtocol: 'HTTP',
Port: 8081,
Protocol: 'HTTP',
TargetType: 'instance',
}));
expectCDK(wfStack).to(haveResourceLike('AWS::CloudWatch::Alarm', {
ComparisonOperator: 'GreaterThanThreshold',
EvaluationPeriods: 8,
ActionsEnabled: true,
DatapointsToAlarm: 8,
Threshold: 0,
TreatMissingData: 'notBreaching',
}));
expectCDK(wfStack).to(haveResourceLike('AWS::CloudWatch::Alarm', {
ComparisonOperator: 'GreaterThanThreshold',
EvaluationPeriods: 1,
ActionsEnabled: true,
DatapointsToAlarm: 1,
Threshold: 35,
TreatMissingData: 'notBreaching',
}));
});
test('validating LB target limit', () => {
// WHEN
healthMonitor = new HealthMonitor(hmStack, 'healthMonitor2', {
vpc,
elbAccountLimits: [{
name: 'targets-per-application-load-balancer',
max: 50,
}],
});
const fleet = new TestMonitorableFleet(wfStack, 'workerFleet', {
vpc,
minCapacity: 50,
});
healthMonitor.registerFleet(fleet, {});
const fleet2 = new TestMonitorableFleet(wfStack, 'workerFleet2', {
vpc,
minCapacity: 50,
});
healthMonitor.registerFleet(fleet2, {});
// THEN
expectCDK(hmStack).to(countResourcesLike('AWS::ElasticLoadBalancingV2::LoadBalancer', 2, {
LoadBalancerAttributes: [
{
Key: 'deletion_protection.enabled',
Value: 'true',
},
],
Scheme: 'internal',
Type: 'application',
}));
expectCDK(wfStack).to(countResources('AWS::ElasticLoadBalancingV2::Listener', 2));
expectCDK(wfStack).to(haveResourceLike('AWS::ElasticLoadBalancingV2::Listener', {
Port: 8081,
Protocol: 'HTTP',
}));
});
test('validating LB listener limit', () => {
// WHEN
healthMonitor = new HealthMonitor(hmStack, 'healthMonitor2', {
vpc,
elbAccountLimits: [{
name: 'listeners-per-application-load-balancer',
max: 1,
}, {
name: 'target-groups-per-action-on-application-load-balancer',
max: 1,
}],
});
const fleet = new TestMonitorableFleet(wfStack, 'workerFleet', {
vpc,
});
healthMonitor.registerFleet(fleet, {});
const fleet2 = new TestMonitorableFleet(wfStack, 'workerFleet2', {
vpc,
});
healthMonitor.registerFleet(fleet2, {});
// THEN
expectCDK(hmStack).to(countResourcesLike('AWS::ElasticLoadBalancingV2::LoadBalancer', 2, {
LoadBalancerAttributes: [
{
Key: 'deletion_protection.enabled',
Value: 'true',
},
],
Scheme: 'internal',
Type: 'application',
}));
expectCDK(wfStack).to(countResources('AWS::ElasticLoadBalancingV2::Listener', 2));
expectCDK(wfStack).to(haveResourceLike('AWS::ElasticLoadBalancingV2::Listener', {
Port: 8081,
Protocol: 'HTTP',
}));
});
test('validating target group limit per lb', () => {
// WHEN
healthMonitor = new HealthMonitor(hmStack, 'healthMonitor2', {
vpc,
elbAccountLimits: [{
name: 'target-groups-per-application-load-balancer',
max: 1,
}],
});
const fleet = new TestMonitorableFleet(wfStack, 'workerFleet', {
vpc,
});
healthMonitor.registerFleet(fleet, {});
const fleet2 = new TestMonitorableFleet(wfStack, 'workerFleet2', {
vpc,
});
healthMonitor.registerFleet(fleet2, {});
// THEN
expectCDK(hmStack).to(countResourcesLike('AWS::ElasticLoadBalancingV2::LoadBalancer', 2, {
Scheme: 'internal',
Type: 'application',
}));
expectCDK(wfStack).to(countResources('AWS::ElasticLoadBalancingV2::Listener', 2));
expectCDK(wfStack).to(haveResourceLike('AWS::ElasticLoadBalancingV2::Listener', {
Port: 8081,
Protocol: 'HTTP',
}));
});
test('validating target limit exhaustion', () => {
// WHEN
healthMonitor = new HealthMonitor(hmStack, 'healthMonitor2', {
vpc,
elbAccountLimits: [{
name: 'targets-per-application-load-balancer',
max: 1,
}],
});
const fleet = new TestMonitorableFleet(wfStack, 'workerFleet', {
vpc,
minCapacity: 2,
});
expect(() => {
healthMonitor.registerFleet(fleet, {});
}).toThrowError(/AWS service limit \"targets-per-application-load-balancer\" reached. Limit: 1/);
});
test('validating deletion protection', () => {
// WHEN
healthMonitor = new HealthMonitor(hmStack, 'healthMonitor2', {
vpc,
deletionProtection: false,
});
const fleet = new TestMonitorableFleet(wfStack, 'workerFleet', {
vpc,
});
healthMonitor.registerFleet(fleet, {});
// THEN
expectCDK(hmStack).to(not(haveResourceLike('AWS::ElasticLoadBalancingV2::LoadBalancer', {
LoadBalancerAttributes: arrayWith(
{
Key: 'deletion_protection.enabled',
Value: 'true',
},
),
Scheme: ABSENT,
Type: ABSENT,
})));
});
test('drop invalid http header fields enabled', () => {
// WHEN
healthMonitor = new HealthMonitor(hmStack, 'healthMonitor2', {
vpc,
});
const fleet = new TestMonitorableFleet(wfStack, 'workerFleet', {
vpc,
});
healthMonitor.registerFleet(fleet, {});
// THEN
expectCDK(hmStack).to(haveResourceLike('AWS::ElasticLoadBalancingV2::LoadBalancer', {
LoadBalancerAttributes: arrayWith(
{
Key: 'routing.http.drop_invalid_header_fields.enabled',
Value: 'true',
},
),
}));
});
test('specifying a subnet', () => {
// WHEN
healthMonitor = new HealthMonitor(hmStack, 'healthMonitor2', {
vpc,
vpcSubnets: {
subnetType: SubnetType.PUBLIC,
},
});
const fleet = new TestMonitorableFleet(wfStack, 'workerFleet', {
vpc,
});
healthMonitor.registerFleet(fleet, {});
// THEN
// Make sure it has the public subnets
expectCDK(hmStack).to(haveResourceLike('AWS::ElasticLoadBalancingV2::LoadBalancer', {
Subnets: [
{'Fn::ImportValue': stringLike('*PublicSubnet*')},
{'Fn::ImportValue': stringLike('*PublicSubnet*')},
],
}));
// Make sure the private subnets aren't present
expectCDK(hmStack).to(haveResourceLike('AWS::ElasticLoadBalancingV2::LoadBalancer', {
Subnets: [
{'Fn::ImportValue': notMatching(stringLike('*PrivateSubnet*'))},
{'Fn::ImportValue': notMatching(stringLike('*PrivateSubnet*'))},
],
}));
});
test('specifying a security group', () => {
// GIVEN
const securityGroup = new SecurityGroup(infraStack, 'LBSecurityGroup', { vpc });
const fleet = new TestMonitorableFleet(wfStack, 'workerFleet', {
vpc,
});
// WHEN
healthMonitor = new HealthMonitor(hmStack, 'healthMonitor2', {
vpc,
securityGroup,
});
healthMonitor.registerFleet(fleet, {});
// THEN
// Make sure it has the security group
expectCDK(hmStack).to(haveResourceLike('AWS::ElasticLoadBalancingV2::LoadBalancer', {
SecurityGroups: arrayWith(
hmStack.resolve(securityGroup.securityGroupId),
),
}));
// HealthMonitor should not create its own security group
expectCDK(hmStack).notTo(haveResource('AWS::EC2::SecurityGroup'));
});
describe('tagging', () => {
testConstructTags({
constructName: 'HealthMonitor',
createConstruct: () => {
// GIVEN
const fleetStack = new Stack(app, 'FleetStack');
const fleet = new TestMonitorableFleet(fleetStack, 'workerFleet', {
vpc,
});
// WHEN
healthMonitor = new HealthMonitor(hmStack, 'HealthMonitor', {
vpc,
});
healthMonitor.registerFleet(fleet, {});
return hmStack;
},
resourceTypeCounts: {
'AWS::KMS::Key': 1,
'AWS::SNS::Topic': 1,
'AWS::ElasticLoadBalancingV2::LoadBalancer': 1,
'AWS::EC2::SecurityGroup': 1,
},
});
});
}); | the_stack |
import {getBaseUrl} from '../../../../utils/url-util';
import {CancelConditionCallback} from '../../../../services/gr-rest-api/gr-rest-api';
import {
AuthRequestInit,
AuthService,
} from '../../../../services/gr-auth/gr-auth';
import {
AccountDetailInfo,
EmailInfo,
ParsedJSON,
RequestPayload,
} from '../../../../types/common';
import {HttpMethod} from '../../../../constants/constants';
import {RpcLogEventDetail} from '../../../../types/events';
import {fireNetworkError, fireServerError} from '../../../../utils/event-util';
import {FetchRequest} from '../../../../types/types';
import {ErrorCallback} from '../../../../api/rest';
export const JSON_PREFIX = ")]}'";
export interface ResponsePayload {
// TODO(TS): readResponsePayload can assign null to the parsed property if
// it can't parse input data. However polygerrit assumes in many places
// that the parsed property can't be null. We should update
// readResponsePayload method and reject a promise instead of assigning
// null to the parsed property
parsed: ParsedJSON; // Can be null!!! See comment above
raw: string;
}
export function readResponsePayload(
response: Response
): Promise<ResponsePayload> {
return response.text().then(text => {
let result;
try {
result = parsePrefixedJSON(text);
} catch (_) {
result = null;
}
// TODO(TS): readResponsePayload can assign null to the parsed property if
// it can't parse input data. However polygerrit assumes in many places
// that the parsed property can't be null. We should update
// readResponsePayload method and reject a promise instead of assigning
// null to the parsed property
return {parsed: result!, raw: text};
});
}
export function parsePrefixedJSON(jsonWithPrefix: string): ParsedJSON {
return JSON.parse(jsonWithPrefix.substring(JSON_PREFIX.length)) as ParsedJSON;
}
/**
* Wrapper around Map for caching server responses. Site-based so that
* changes to CANONICAL_PATH will result in a different cache going into
* effect.
*/
export class SiteBasedCache {
// TODO(TS): Type looks unusual. Fix it.
// Container of per-canonical-path caches.
private readonly data = new Map<
string | undefined,
unknown | Map<string, ParsedJSON | null>
>();
constructor() {
if (window.INITIAL_DATA) {
// Put all data shipped with index.html into the cache. This makes it
// so that we spare more round trips to the server when the app loads
// initially.
Object.entries(window.INITIAL_DATA).forEach(e =>
this._cache().set(e[0], e[1] as unknown as ParsedJSON)
);
}
}
// Returns the cache for the current canonical path.
_cache(): Map<string, unknown> {
if (!this.data.has(window.CANONICAL_PATH)) {
this.data.set(
window.CANONICAL_PATH,
new Map<string, ParsedJSON | null>()
);
}
return this.data.get(window.CANONICAL_PATH) as Map<
string,
ParsedJSON | null
>;
}
has(key: string) {
return this._cache().has(key);
}
get(key: '/accounts/self/emails'): EmailInfo[] | null;
get(key: '/accounts/self/detail'): AccountDetailInfo[] | null;
get(key: string): ParsedJSON | null;
get(key: string): unknown {
return this._cache().get(key);
}
set(key: '/accounts/self/emails', value: EmailInfo[]): void;
set(key: '/accounts/self/detail', value: AccountDetailInfo[]): void;
set(key: string, value: ParsedJSON | null): void;
set(key: string, value: unknown) {
this._cache().set(key, value);
}
delete(key: string) {
this._cache().delete(key);
}
invalidatePrefix(prefix: string) {
const newMap = new Map<string, unknown>();
for (const [key, value] of this._cache().entries()) {
if (!key.startsWith(prefix)) {
newMap.set(key, value);
}
}
this.data.set(window.CANONICAL_PATH, newMap);
}
}
type FetchPromisesCacheData = {
[url: string]: Promise<ParsedJSON | undefined> | undefined;
};
export class FetchPromisesCache {
private data: FetchPromisesCacheData;
constructor() {
this.data = {};
}
public testOnlyGetData() {
return this.data;
}
/**
* @return true only if a value for a key sets and it is not undefined
*/
has(key: string): boolean {
return !!this.data[key];
}
get(key: string) {
return this.data[key];
}
/**
* @param value a Promise to store in the cache. Pass undefined value to
* mark key as deleted.
*/
set(key: string, value: Promise<ParsedJSON | undefined> | undefined) {
this.data[key] = value;
}
invalidatePrefix(prefix: string) {
const newData: FetchPromisesCacheData = {};
Object.entries(this.data).forEach(([key, value]) => {
if (!key.startsWith(prefix)) {
newData[key] = value;
}
});
this.data = newData;
}
}
export type FetchParams = {
[name: string]: string[] | string | number | boolean | undefined | null;
};
interface SendRequestBase {
method: HttpMethod | undefined;
body?: RequestPayload;
contentType?: string;
headers?: Record<string, string>;
url: string;
reportUrlAsIs?: boolean;
anonymizedUrl?: string;
errFn?: ErrorCallback;
}
export interface SendRawRequest extends SendRequestBase {
parseResponse?: false | null;
}
export interface SendJSONRequest extends SendRequestBase {
parseResponse: true;
}
export type SendRequest = SendRawRequest | SendJSONRequest;
export interface FetchJSONRequest extends FetchRequest {
reportUrlAsIs?: boolean;
params?: FetchParams;
cancelCondition?: CancelConditionCallback;
errFn?: ErrorCallback;
}
// export function isRequestWithCancel<T extends FetchJSONRequest>(
// x: T
// ): x is T & RequestWithCancel {
// return !!(x as RequestWithCancel).cancelCondition;
// }
//
// export function isRequestWithErrFn<T extends FetchJSONRequest>(
// x: T
// ): x is T & RequestWithErrFn {
// return !!(x as RequestWithErrFn).errFn;
// }
export class GrRestApiHelper {
constructor(
private readonly _cache: SiteBasedCache,
private readonly _auth: AuthService,
private readonly _fetchPromisesCache: FetchPromisesCache
) {}
/**
* Wraps calls to the underlying authenticated fetch function (_auth.fetch)
* with timing and logging.
s */
fetch(req: FetchRequest): Promise<Response> {
const start = Date.now();
const xhr = this._auth.fetch(req.url, req.fetchOptions);
// Log the call after it completes.
xhr.then(res => this._logCall(req, start, res ? res.status : null));
// Return the XHR directly (without the log).
return xhr;
}
/**
* Log information about a REST call. Because the elapsed time is determined
* by this method, it should be called immediately after the request
* finishes.
*
* @param startTime the time that the request was started.
* @param status the HTTP status of the response. The status value
* is used here rather than the response object so there is no way this
* method can read the body stream.
*/
private _logCall(
req: FetchRequest,
startTime: number,
status: number | null
) {
const method =
req.fetchOptions && req.fetchOptions.method
? req.fetchOptions.method
: 'GET';
const endTime = Date.now();
const elapsed = endTime - startTime;
const startAt = new Date(startTime);
const endAt = new Date(endTime);
console.info(
[
'HTTP',
status,
method,
`${elapsed}ms`,
req.anonymizedUrl || req.url,
`(${startAt.toISOString()}, ${endAt.toISOString()})`,
].join(' ')
);
if (req.anonymizedUrl) {
const detail: RpcLogEventDetail = {
status,
method,
elapsed,
anonymizedUrl: req.anonymizedUrl,
};
document.dispatchEvent(
new CustomEvent('gr-rpc-log', {
detail,
composed: true,
bubbles: true,
})
);
}
}
/**
* Fetch JSON from url provided.
* Returns a Promise that resolves to a native Response.
* Doesn't do error checking. Supports cancel condition. Performs auth.
* Validates auth expiry errors.
*
* @return Promise which resolves to undefined if cancelCondition returns true
* and resolves to Response otherwise
*/
fetchRawJSON(req: FetchJSONRequest): Promise<Response | undefined> {
const urlWithParams = this.urlWithParams(req.url, req.params);
const fetchReq: FetchRequest = {
url: urlWithParams,
fetchOptions: req.fetchOptions,
anonymizedUrl: req.reportUrlAsIs ? urlWithParams : req.anonymizedUrl,
};
return this.fetch(fetchReq)
.then((res: Response) => {
if (req.cancelCondition && req.cancelCondition()) {
if (res.body) {
res.body.cancel();
}
return;
}
return res;
})
.catch(err => {
if (req.errFn) {
req.errFn.call(undefined, null, err);
} else {
fireNetworkError(err);
}
throw err;
});
}
/**
* Fetch JSON from url provided.
* Returns a Promise that resolves to a parsed response.
* Same as {@link fetchRawJSON}, plus error handling.
*
* @param noAcceptHeader - don't add default accept json header
*/
fetchJSON(
req: FetchJSONRequest,
noAcceptHeader?: boolean
): Promise<ParsedJSON | undefined> {
if (!noAcceptHeader) {
req = this.addAcceptJsonHeader(req);
}
return this.fetchRawJSON(req).then(response => {
if (!response) {
return;
}
if (!response.ok) {
if (req.errFn) {
req.errFn.call(null, response);
return;
}
fireServerError(response, req);
return;
}
return this.getResponseObject(response);
});
}
urlWithParams(url: string, fetchParams?: FetchParams): string {
if (!fetchParams) {
return getBaseUrl() + url;
}
const params: Array<string | number | boolean> = [];
for (const [p, paramValue] of Object.entries(fetchParams)) {
// TODO(TS): Replace == null with === and check for null and undefined
// eslint-disable-next-line eqeqeq
if (paramValue == null) {
params.push(this.encodeRFC5987(p));
continue;
}
// TODO(TS): Unclear, why do we need the following code.
// If paramValue can be array - we should either fix FetchParams type
// or convert the array to a string before calling urlWithParams method.
const paramValueAsArray = ([] as Array<string | number | boolean>).concat(
paramValue
);
for (const value of paramValueAsArray) {
params.push(`${this.encodeRFC5987(p)}=${this.encodeRFC5987(value)}`);
}
}
return getBaseUrl() + url + '?' + params.join('&');
}
// Backend encode url in RFC5987 and frontend needs to do same to match
// queries for preloading queries
encodeRFC5987(uri: string | number | boolean) {
return encodeURIComponent(uri).replace(
/['()*]/g,
c => '%' + c.charCodeAt(0).toString(16)
);
}
getResponseObject(response: Response): Promise<ParsedJSON> {
return readResponsePayload(response).then(payload => payload.parsed);
}
addAcceptJsonHeader(req: FetchJSONRequest) {
if (!req.fetchOptions) req.fetchOptions = {};
if (!req.fetchOptions.headers) req.fetchOptions.headers = new Headers();
if (!req.fetchOptions.headers.has('Accept')) {
req.fetchOptions.headers.append('Accept', 'application/json');
}
return req;
}
fetchCacheURL(req: FetchJSONRequest): Promise<ParsedJSON | undefined> {
if (this._fetchPromisesCache.has(req.url)) {
return this._fetchPromisesCache.get(req.url)!;
}
// TODO(andybons): Periodic cache invalidation.
if (this._cache.has(req.url)) {
return Promise.resolve(this._cache.get(req.url)!);
}
this._fetchPromisesCache.set(
req.url,
this.fetchJSON(req)
.then(response => {
if (response !== undefined) {
this._cache.set(req.url, response);
}
this._fetchPromisesCache.set(req.url, undefined);
return response;
})
.catch(err => {
this._fetchPromisesCache.set(req.url, undefined);
throw err;
})
);
return this._fetchPromisesCache.get(req.url)!;
}
// if errFn is not set, then only Response possible
send(req: SendRawRequest & {errFn?: undefined}): Promise<Response>;
send(req: SendRawRequest): Promise<Response | undefined>;
send(req: SendJSONRequest): Promise<ParsedJSON>;
send(req: SendRequest): Promise<Response | ParsedJSON | undefined>;
/**
* Send an XHR.
*
* @return Promise resolves to Response/ParsedJSON only if the request is successful
* (i.e. no exception and response.ok is true). If response fails then
* promise resolves either to void if errFn is set or rejects if errFn
* is not set */
send(req: SendRequest): Promise<Response | ParsedJSON | undefined> {
const options: AuthRequestInit = {method: req.method};
if (req.body) {
options.headers = new Headers();
options.headers.set(
'Content-Type',
req.contentType || 'application/json'
);
options.body =
typeof req.body === 'string' ? req.body : JSON.stringify(req.body);
}
if (req.headers) {
if (!options.headers) {
options.headers = new Headers();
}
for (const [name, value] of Object.entries(req.headers)) {
options.headers.set(name, value);
}
}
const url = req.url.startsWith('http') ? req.url : getBaseUrl() + req.url;
const fetchReq: FetchRequest = {
url,
fetchOptions: options,
anonymizedUrl: req.reportUrlAsIs ? url : req.anonymizedUrl,
};
const xhr = this.fetch(fetchReq)
.catch(err => {
fireNetworkError(err);
if (req.errFn) {
return req.errFn.call(undefined, null, err);
} else {
throw err;
}
})
.then(response => {
if (response && !response.ok) {
if (req.errFn) {
req.errFn.call(undefined, response);
return;
}
fireServerError(response, fetchReq);
}
return response;
});
if (req.parseResponse) {
// TODO(TS): remove as Response and fix error.
// Javascript code allows returning of a Response object from errFn.
// This can be a mistake and we should add check here or it can be used
// somewhere - in this case we should fix it carefully (define
// different type of callback if parseResponse is true, etc...).
return xhr.then(res => this.getResponseObject(res as Response));
}
// The actual xhr type is Promise<Response|undefined|void> because of the
// catch callback
return xhr as Promise<Response | undefined>;
}
invalidateFetchPromisesPrefix(prefix: string) {
this._fetchPromisesCache.invalidatePrefix(prefix);
this._cache.invalidatePrefix(prefix);
}
} | the_stack |
import { expect, assert } from 'chai';
import * as im from 'immutable';
import * as lexical from '../../../compiler/lexical-analysis/lexical';
import * as lexer from '../../../compiler/lexical-analysis/lexer';
interface lexTest {
name: string
input: string
tokens: lexer.Token[]
errString: string
};
const makeLexTest =
(name: string, input: string, tokens: lexer.Token[], errString: string) => <lexTest>{
name: name,
input: input,
tokens: tokens,
errString: errString,
};
const emptyTokenArray = (): lexer.Token[] => [];
const tEOF = new lexer.Token(
"TokenEndOfFile", [], "", "", "", lexical.MakeLocationRangeMessage(""));
const makeToken =
(kind: lexer.TokenKind, data: string, locRange: lexical.LocationRange) =>
new lexer.Token(kind, [], data, "", "", locRange);
const makeLocRange =
(beginLine: number, beginCol: number, endLine: number, endCol : number) =>
<lexical.LocationRange>{
begin: new lexical.Location(beginLine, beginCol),
end: new lexical.Location(endLine, endCol),
}
const lexTests = <lexTest[]>[
makeLexTest("empty", "", emptyTokenArray(), ""),
makeLexTest("whitespace", " \t\n\r\r\n", emptyTokenArray(), ""),
makeLexTest("brace L", "{", [makeToken("TokenBraceL", "{", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("brace R", "}", [makeToken("TokenBraceR", "}", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("bracket L", "[", [makeToken("TokenBracketL", "[", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("bracket R", "]", [makeToken("TokenBracketR", "]", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("colon", ":", [makeToken("TokenOperator", ":", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("colon2", "::", [makeToken("TokenOperator", "::", makeLocRange(1, 1, 1, 3))], ""),
makeLexTest("colon3", ":::", [makeToken("TokenOperator", ":::", makeLocRange(1, 1, 1, 4))], ""),
makeLexTest("arrow right", "->", [makeToken("TokenOperator", "->", makeLocRange(1, 1, 1, 3))], ""),
makeLexTest("less than minus", "<-", [makeToken("TokenOperator", "<", makeLocRange(1, 1, 1, 2)),
makeToken("TokenOperator", "-", makeLocRange(1, 2, 1, 3))], ""),
makeLexTest("comma", ",", [makeToken("TokenComma", ",", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("dollar", "$", [makeToken("TokenDollar", "$", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("dot", ".", [makeToken("TokenDot", ".", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("paren L", "(", [makeToken("TokenParenL", "(", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("paren R", ")", [makeToken("TokenParenR", ")", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("semicolon", ";", [makeToken("TokenSemicolon", ";", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("not 1", "!", [makeToken("TokenOperator", "!", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("not 2", "! ", [makeToken("TokenOperator", "!", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("not equal", "!=", [makeToken("TokenOperator", "!=", makeLocRange(1, 1, 1, 3))], ""),
makeLexTest("tilde", "~", [makeToken("TokenOperator", "~", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("plus", "+", [makeToken("TokenOperator", "+", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("minus", "-", [makeToken("TokenOperator", "-", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("number 0", "0", [makeToken("TokenNumber", "0", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("number 1", "1", [makeToken("TokenNumber", "1", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("number 1.0", "1.0", [makeToken("TokenNumber", "1.0", makeLocRange(1, 1, 1, 4))], ""),
makeLexTest("number 0.10", "0.10", [makeToken("TokenNumber", "0.10", makeLocRange(1, 1, 1, 5))], ""),
makeLexTest("number 0e100", "0e100", [makeToken("TokenNumber", "0e100", makeLocRange(1, 1, 1, 6))], ""),
makeLexTest("number 1e100", "1e100", [makeToken("TokenNumber", "1e100", makeLocRange(1, 1, 1, 6))], ""),
makeLexTest("number 1.1e100", "1.1e100", [makeToken("TokenNumber", "1.1e100", makeLocRange(1, 1, 1, 8))], ""),
makeLexTest("number 1.1e-100", "1.1e-100", [makeToken("TokenNumber", "1.1e-100", makeLocRange(1, 1, 1, 9))], ""),
makeLexTest("number 1.1e+100", "1.1e+100", [makeToken("TokenNumber", "1.1e+100", makeLocRange(1, 1, 1, 9))], ""),
makeLexTest("number 0100", "0100", [
makeToken("TokenNumber", "0", makeLocRange(1, 1, 1, 2)),
makeToken("TokenNumber", "100", makeLocRange(1, 2, 1, 5)),
], ""),
makeLexTest("number 10+10", "10+10", [
makeToken("TokenNumber", "10", makeLocRange(1, 1, 1, 3)),
makeToken("TokenOperator", "+", makeLocRange(1, 3, 1, 4)),
makeToken("TokenNumber", "10", makeLocRange(1, 4, 1, 6)),
], ""),
makeLexTest("number 1.+3", "1.+3", emptyTokenArray(), "number 1.+3:1:3 Couldn't lex number, junk after decimal point: '+'"),
makeLexTest("number 1e!", "1e!", emptyTokenArray(), "number 1e!:1:3 Couldn't lex number, junk after 'E': '!'"),
makeLexTest("number 1e+!", "1e+!", emptyTokenArray(), "number 1e+!:1:4 Couldn't lex number, junk after exponent sign: '!'"),
makeLexTest("double string \"hi\"", "\"hi\"", [makeToken("TokenStringDouble", "hi", makeLocRange(1, 2, 1, 4))], ""),
makeLexTest("double string \"hi nl\"", "\"hi\n\"", [makeToken("TokenStringDouble", "hi\n", makeLocRange(1, 2, 2, 1))], ""),
makeLexTest("double string \"hi\\\"\"", "\"hi\\\"\"", [makeToken("TokenStringDouble", "hi\\\"", makeLocRange(1, 2, 1, 6))], ""),
makeLexTest("double string \"hi\\nl\"", "\"hi\\\n\"", [makeToken("TokenStringDouble", "hi\\\n", makeLocRange(1, 2, 2, 1))], ""),
makeLexTest("double string \"hi", "\"hi", emptyTokenArray(), "double string \"hi:1:1 Unterminated String"),
makeLexTest("single string 'hi'", "'hi'", [makeToken("TokenStringSingle", "hi", makeLocRange(1, 2, 1, 4))], ""),
makeLexTest("single string 'hi nl'", "'hi\n'", [makeToken("TokenStringSingle", "hi\n", makeLocRange(1, 2, 2, 1))], ""),
makeLexTest("single string 'hi\\''", "'hi\\''", [makeToken("TokenStringSingle", "hi\\'", makeLocRange(1, 2, 1, 6))], ""),
makeLexTest("single string 'hi\\nl'", "'hi\\\n'", [makeToken("TokenStringSingle", "hi\\\n", makeLocRange(1, 2, 2, 1))], ""),
makeLexTest("single string 'hi", "'hi", emptyTokenArray(), "single string 'hi:1:1 Unterminated String"),
makeLexTest("assert", "assert", [makeToken("TokenAssert", "assert", makeLocRange(1, 1, 1, 7))], ""),
makeLexTest("else", "else", [makeToken("TokenElse", "else", makeLocRange(1, 1, 1, 5))], ""),
makeLexTest("error", "error", [makeToken("TokenError", "error", makeLocRange(1, 1, 1, 6))], ""),
makeLexTest("false", "false", [makeToken("TokenFalse", "false", makeLocRange(1, 1, 1, 6))], ""),
makeLexTest("for", "for", [makeToken("TokenFor", "for", makeLocRange(1, 1, 1, 4))], ""),
makeLexTest("function", "function", [makeToken("TokenFunction", "function", makeLocRange(1, 1, 1, 9))], ""),
makeLexTest("if", "if", [makeToken("TokenIf", "if", makeLocRange(1, 1, 1, 3))], ""),
makeLexTest("import", "import", [makeToken("TokenImport", "import", makeLocRange(1, 1, 1, 7))], ""),
makeLexTest("importstr", "importstr", [makeToken("TokenImportStr", "importstr", makeLocRange(1, 1, 1, 10))], ""),
makeLexTest("in", "in", [makeToken("TokenIn", "in", makeLocRange(1, 1, 1, 3))], ""),
makeLexTest("local", "local", [makeToken("TokenLocal", "local", makeLocRange(1, 1, 1, 6))], ""),
makeLexTest("null", "null", [makeToken("TokenNullLit", "null", makeLocRange(1, 1, 1, 5))], ""),
makeLexTest("self", "self", [makeToken("TokenSelf", "self", makeLocRange(1, 1, 1, 5))], ""),
makeLexTest("super", "super", [makeToken("TokenSuper", "super", makeLocRange(1, 1, 1, 6))], ""),
makeLexTest("tailstrict", "tailstrict", [makeToken("TokenTailStrict", "tailstrict", makeLocRange(1, 1, 1, 11))], ""),
makeLexTest("then", "then", [makeToken("TokenThen", "then", makeLocRange(1, 1, 1, 5))], ""),
makeLexTest("true", "true", [makeToken("TokenTrue", "true", makeLocRange(1, 1, 1, 5))], ""),
makeLexTest("identifier", "foobar123", [makeToken("TokenIdentifier", "foobar123", makeLocRange(1, 1, 1, 10))], ""),
makeLexTest("identifier", "foo bar123", [makeToken("TokenIdentifier", "foo", makeLocRange(1, 1, 1, 4)), makeToken("TokenIdentifier", "bar123", makeLocRange(1, 5, 1, 11))], ""),
makeLexTest("c++ comment", "// hi", [makeToken("TokenCommentCpp", " hi", makeLocRange(1, 3, 1, 6))], ""),
makeLexTest("hash comment", "# hi", [makeToken("TokenCommentHash", " hi", makeLocRange(1, 2, 1, 5))], ""),
makeLexTest("c comment", "/* hi */", [makeToken("TokenCommentC", " hi ", makeLocRange(1, 3, 1, 7))], ""),
makeLexTest("c comment no term", "/* hi", emptyTokenArray(), "c comment no term:1:1 Multi-line comment has no terminating */"),
makeLexTest(
"block string spaces",
"|||\
\n test\
\n more\
\n |||\
\n foo\
\n|||",
[
new lexer.Token(
"TokenStringBlock",
[],
"test\n more\n|||\n foo\n",
" ",
"",
makeLocRange(1, 1, 6, 4))
],
"",
),
makeLexTest(
"block string tabs",
"|||\
\n test\
\n more\
\n |||\
\n foo\
\n|||",
[
new lexer.Token(
"TokenStringBlock",
[],
"test\n more\n|||\n foo\n",
"\t",
"",
makeLocRange(1, 1, 6, 4))
],
""
),
makeLexTest(
"block string mixed",
"|||\
\n test\
\n more\
\n |||\
\n foo\
\n|||",
[
new lexer.Token(
"TokenStringBlock",
[],
"test\n more\n|||\n foo\n",
"\t \t",
"",
makeLocRange(1, 1, 6, 4))
],
""
),
makeLexTest(
"block string blanks",
"|||\
\n\
\n test\
\n\
\n\
\n more\
\n |||\
\n foo\
\n|||",
[
new lexer.Token(
"TokenStringBlock",
[],
"\ntest\n\n\n more\n|||\n foo\n",
" ",
"",
makeLocRange(1, 1, 9, 4))
],
""
),
makeLexTest(
"block string bad indent",
"|||\
\n test\
\n foo\
\n|||",
[],
"block string bad indent:1:1 Text block not terminated with |||"
),
makeLexTest(
"block string eof",
"|||\
\n test",
[],
"block string eof:1:1 Unexpected EOF"
),
makeLexTest(
"block string not term",
"|||\
\n test\
\n",
[],
"block string not term:1:1 Text block not terminated with |||"
),
makeLexTest(
"block string no ws",
"|||\
\ntest\
\n|||",
[],
"block string no ws:1:1 Text block's first line must start with whitespace"
),
makeLexTest(
"Invalid multiline object",
"{\
\nbar\
\n}",
[
makeToken("TokenBraceL", "{", makeLocRange(1, 1, 1, 2)),
makeToken("TokenIdentifier", "bar", makeLocRange(2, 1, 2, 4)),
makeToken("TokenBraceR", "}", makeLocRange(3, 1, 3, 2)),
],
""
),
makeLexTest("op *", "*", [makeToken("TokenOperator", "*", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("op /", "/", [makeToken("TokenOperator", "/", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("op %", "%", [makeToken("TokenOperator", "%", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("op &", "&", [makeToken("TokenOperator", "&", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("op |", "|", [makeToken("TokenOperator", "|", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("op ^", "^", [makeToken("TokenOperator", "^", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("op =", "=", [makeToken("TokenOperator", "=", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("op <", "<", [makeToken("TokenOperator", "<", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("op >", ">", [makeToken("TokenOperator", ">", makeLocRange(1, 1, 1, 2))], ""),
makeLexTest("op >==|", ">==|", [makeToken("TokenOperator", ">==|", makeLocRange(1, 1, 1, 5))], ""),
makeLexTest("junk", "💩", emptyTokenArray(), "junk:1:1 Could not lex the character '💩'"),
];
const locationsEqual = (t1: lexer.Token, t2: lexer.Token): boolean => {
if (t1.loc.begin.line != t2.loc.begin.line) {
return false
}
if (t1.loc.begin.column != t2.loc.begin.column) {
return false
}
if (t1.loc.end.line != t2.loc.end.line) {
return false
}
if (t1.loc.end.column != t2.loc.end.column) {
return false
}
return true
}
const tokensStreamsEqual = (ts1: lexer.Token[], ts2: lexer.Token[]): boolean => {
if (ts1.length != ts2.length) {
return false
}
for (let i in ts1) {
const t1 = ts1[i];
const t2 = ts2[i];
if (t1.kind != t2.kind) {
return false
}
if (t1.data != t2.data) {
return false
}
if (t1.stringBlockIndent != t2.stringBlockIndent) {
return false
}
if (t1.stringBlockTermIndent != t2.stringBlockTermIndent) {
return false
}
// EOF token is appended in the test loop, so we ignore its
// location.
if (t1.kind != "TokenEndOfFile" && !locationsEqual(t1, t2)) {
return false
}
}
return true
}
describe("Lexer tests", () => {
for (let test of lexTests) {
it(test.name, () => {
// Copy the test tokens and append an EOF token
const testTokens = im.List<lexer.Token>(test.tokens).push(tEOF);
const tokens = lexer.Lex(test.name, test.input);
var errString = "";
if (lexical.isStaticError(tokens)) {
errString = tokens.Error();
}
assert.equal(errString, test.errString);
if (!lexical.isStaticError(tokens)) {
const tokenStreamText = tokens
.map(token => {
if (token === undefined) {
throw new Error(`Tried to pretty-print token stream, but there was an undefined token`);
}
return token.toString();
})
.join(", ");
const testTokensText = testTokens
.map(token => {
if (token === undefined) {
throw new Error(`Tried to pretty-print token stream, but there was an undefined token`);
}
return token.toString();
})
.join(", ");
assert.isTrue(
tokensStreamsEqual(tokens.toArray(), testTokens.toArray()),
`got\n\t${tokenStreamText}\nexpected\n\t${testTokensText}`);
}
});
}
});
describe("UTF-8 lexer tests", () => {
it("Correctly advances when given a UTF-8 string", () => {
const l = new lexer.lexer("tests", "日本語");
let r = l.next();
assert.equal(r.data, "日");
assert.equal(r.data.length, 1);
assert.equal(r.codePoint, 26085);
r = l.next();
assert.equal(r.data, "本");
assert.equal(r.data.length, 1);
assert.equal(r.codePoint, 26412);
r = l.next();
assert.equal(r.data, "語");
assert.equal(r.data.length, 1);
assert.equal(r.codePoint, 35486);
});
it("Correctly advances when given multi-byte UTF-8 characters", () => {
const l = new lexer.lexer("tests", "𝟘𝟙");
let r = l.next();
assert.equal(r.data, "𝟘");
assert.equal(r.data.length, 2);
assert.equal(r.codePoint, 120792);
r = l.next();
assert.equal(r.data, "𝟙");
assert.equal(r.data.length, 2);
assert.equal(r.codePoint, 120793);
});
it("Runes correctly parse multi-byte UTF-8 characters", () => {
const unicodeRune0 = lexer.runeFromString("𝟘𝟙", 0);
assert.equal(unicodeRune0.data, "𝟘");
const unicodeRune1 = lexer.runeFromString("𝟘𝟙", 1);
assert.equal(unicodeRune1.data, "𝟙");
});
});
describe("Lexer helper tests", () => {
const toRunes = (str: string): lexer.rune[] => {
const codePoints = lexer.makeCodePoints(str);
return codePoints
.map((char, i) => {
if (i === undefined) {
throw new Error("Index can't be undefined in a `map`");
}
return lexer.runeFromCodePoints(codePoints, i)
})
.toArray();
}
const upperAlpha = toRunes("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
const lowerAlpha = toRunes("abcdefghijklmnopqrstuvwxyz");
const digits = toRunes("0123456789");
it("`isUpper` correctly reports if character is in [A-Z]", () => {
for (let char of upperAlpha) {
assert.isTrue(lexer.isUpper(char));
}
for (let char of lowerAlpha) {
assert.isFalse(lexer.isUpper(char));
}
// The character right before range `[A-Z]` in ASCII table.
assert.isFalse(lexer.isUpper(lexer.runeFromString("@", 0)));
// The character right after range `[A-Z]` in ASCII table.
assert.isFalse(lexer.isUpper(lexer.runeFromString("[", 0)));
});
it("`isLower` correctly reports if character is in [a-z]", () => {
for (let char of lowerAlpha) {
assert.isTrue(lexer.isLower(char));
}
for (let char of upperAlpha) {
assert.isFalse(lexer.isLower(char));
}
// The character right before range `[a-z]` in ASCII table.
assert.isFalse(lexer.isLower(lexer.runeFromString("`", 0)));
// The character right after range `[a-z]` in ASCII table.
assert.isFalse(lexer.isLower(lexer.runeFromString("{", 0)));
});
it("`isNumber` correctly reports if character is in [0-9]", () => {
for (let char of digits) {
assert.isTrue(lexer.isNumber(char));
}
for (let char of upperAlpha) {
assert.isFalse(lexer.isNumber(char));
}
// The character right before range `[0-9]` in ASCII table.
assert.isFalse(lexer.isNumber(lexer.runeFromString("/", 0)));
// The character right after range `[0-9]` in ASCII table.
assert.isFalse(lexer.isNumber(lexer.runeFromString(":", 0)));
});
});
describe("Jsonnet error location parsing", () => {
const testSuccessfulParse = (loc: string): lexical.LocationRange => {
const lr = lexical.LocationRange.fromString("", loc);
assert.isNotNull(lr);
return <lexical.LocationRange>lr;
}
const testFailedParse = (loc: string): void => {
const lr = lexical.LocationRange.fromString("", loc);
assert.isNull(lr);
}
it("Correctly parse simple range", () => {
const lr = testSuccessfulParse("(8:15)-(10:1)");
assert.isNotNull(lr);
assert.equal(lr.begin.line, 8);
assert.equal(lr.begin.column, 15);
assert.equal(lr.end.line, 10);
assert.equal(lr.end.column, 1);
});
it("Correctly parse simple single-line range", () => {
const lr = testSuccessfulParse("9:10-19");
assert.isNotNull(lr);
assert.equal(lr.begin.line, 9);
assert.equal(lr.begin.column, 10);
assert.equal(lr.end.line, 9);
assert.equal(lr.end.column, 19);
});
it("Correctly parse simple single-character range", () => {
const lr = testSuccessfulParse("100:2");
assert.isNotNull(lr);
assert.equal(lr.begin.line, 100);
assert.equal(lr.begin.column, 2);
assert.equal(lr.end.line, 100);
assert.equal(lr.end.column, 2);
});
it("Correctly parse simple single-character range with parens", () => {
const lr = testSuccessfulParse("(112:21)");
assert.isNotNull(lr);
assert.equal(lr.begin.line, 112);
assert.equal(lr.begin.column, 21);
assert.equal(lr.end.line, 112);
assert.equal(lr.end.column, 21);
});
}); | the_stack |
import {timeMillisecond as d3timeMillisecond} from "d3-time";
import pako = require("pako");
import Rx = require("rx");
import {RemoteObjectId} from "./javaBridge";
import {Test} from "./test";
import Observer = Rx.Observer;
import {ErrorReporter} from "./ui/errReporter";
import {FullPage} from "./ui/fullPage";
import {ProgressBar} from "./ui/progress";
import {assert, formatDate, ICancellable, PartialResult, RpcReply} from "./util";
/**
* Path in server url for rpc web sockets.
* This must match the web application server configuration.
*/
const RpcRequestPath = "rpc";
/**
* Each remote object has a globally unique identifier.
* (The initial remote object always has a fixed known identifier).
* This is just a reference to a remote object. All remote objects
* are represented in Java by classes that extend RpcTarget.
*/
export class RemoteObject {
constructor(private readonly remoteObjectId: RemoteObjectId | null) {}
/**
* Creates a request to a remote method. The request must be invoked separately.
* @param {string} method Name of the method to invoke. This method
* in Java is tagged with the annotation @HillviewRPC
* and has the signature:
* public void method(RpcRequest request, RpcRequestContext context).
* @param args Arguments to pass to the method. The arguments are converted
* to JSON and show up on the Java side as a string encoding
* in the 'arguments' field of the RpcRequest. The Java side will
* decode the string into a suitable datatype and call the corresponding
* method in Java.
* @returns {RpcRequest} The request that is created.
*/
public createStreamingRpcRequest<T>(method: string, args: any): RpcRequest<T> {
return new RpcRequest<T>(this.getRemoteObjectId()!, method, args);
}
public getRemoteObjectId(): RemoteObjectId | null {
return this.remoteObjectId;
}
public toString(): string {
return this.getRemoteObjectId()!.toString();
}
}
/**
* A streaming RPC request: for each request made
* we expect a stream of replies. The requests are made
* over web sockets. When the last reply has been received
* the web socket is closed.
*
* T is the type of the result returned.
*/
export class RpcRequest<T> implements ICancellable<T> {
public readonly unused: PartialResult<T>;
public readonly protoVersion: number = 6;
public readonly requestId: number;
public cancelled: boolean;
public closed: boolean; // i.e., not opened
public socket: WebSocket | null;
public completed: boolean;
/**
* Time when RPC was initiated. It may be set explicitly
* by users, and then it can be used to measured operations
* that span multiple RPCs
*/
public rpcTime: Date | null;
// Remove some lines from exception messages
static readonly prefixesToCut = ["rx.", "io.grpc", "sun.reflect",
"org.apache.(tomcat|coyote)", "java.lang.Thread.run",
"java.util.concurrent.ThreadPoolExecutor", "java.lang.reflect.", "java.beans."];
static readonly rePiece = RpcRequest.prefixesToCut
.map(s => s.replace(".", "\\."))
.map(s => "(" + s + ")")
.join("|");
static readonly simplifyRe = new RegExp("^\\s+at (" + RpcRequest.rePiece + ")");
public static requestCounter: number = 0;
/**
* Create a request to a remote object.
* @param {string} objectId Remote object unique identifier.
* @param {string} method Method that is being invoked.
* @param args Arguments that are passed to method; will be converted to JSON.
*/
constructor(public objectId: string,
public method: string,
public args: any) {
this.requestId = RpcRequest.requestCounter++;
this.socket = null;
this.cancelled = false;
this.closed = true;
this.completed = false;
this.rpcTime = null;
}
/**
* The time when this RPC request was invoked (or when the request it has been chained to
* has started).
*/
public startTime(): Date {
return this.rpcTime!;
}
public setStartTime(start: Date): void {
this.rpcTime = start;
}
/**
* Indicates that this rpc request is executed as a continuation of
* the specified operation. This is mostly useful for accounting the time
* required for executing a chain of operations.
*/
public chain<S>(after: ICancellable<S> | null): void {
if (after != null)
this.setStartTime(after.startTime());
}
public serialize(): Uint8Array {
let argString;
if (this.args == null)
argString = JSON.stringify(null);
else if (this.args.toJSON != null)
argString = this.args.toJSON();
else
argString = JSON.stringify(this.args);
const result = {
objectId: this.objectId,
method: this.method,
arguments: argString,
requestId: this.requestId,
protoVersion: this.protoVersion,
};
const str = JSON.stringify(result);
console.log(formatDate(new Date()) + " Sending message " + str);
return pako.deflate(str);
}
/**
* Cancel this RPC request.
* @returns {boolean} True if the request was not already completed.
*/
public cancel(): boolean {
if (!this.closed) {
console.log(formatDate(new Date()) + " cancelling " + this.toString());
this.closed = true;
this.socket!.close();
return true;
}
return false;
}
public static simplifyExceptions(errorMessage: string): string {
let lines = errorMessage.split(/\r?\n/);
// First look for a HillviewException if there is one
for (const line of lines) {
const index = line.indexOf("org.hillview.utils.HillviewException:");
if (index >= 0)
return line.substr(index + "org.hillview.utils.HillviewException:".length);
}
lines = lines
.filter((v) => !this.simplifyRe.test(v))
.map((v) => v.replace("io.grpc.StatusRuntimeException: INTERNAL: ", ""));
return lines.join("\n");
}
public toString(): string {
return this.objectId + "." + this.method + "()";
}
/**
* Execute the RPC request and pass the results received to the specified observer.
* @param onReply An observer which is invoked for each result received by
* the streaming RPC.
*/
public invoke(onReply: Observer<PartialResult<T>>): void {
try {
// If time is not set we set it now. The time may be set because this
// is a request that is part of a chain of requests.
if (this.rpcTime == null)
this.rpcTime = new Date();
// Create a web socked and send the request
const rpcRequestUrl = "ws://" + window.location.hostname + ":" +
window.location.port + "/" + RpcRequestPath;
this.socket = new WebSocket(rpcRequestUrl);
this.socket.binaryType = "arraybuffer";
this.socket.onerror = (ev: Event) => {
console.log("socket error " + ev);
let msg = (ev as ErrorEvent).message;
if (msg == null)
msg = "Error communicating to server.";
onReply.onError(msg);
};
this.socket.onmessage = (r: MessageEvent) => {
// parse json and invoke onReply.onNext
console.log(formatDate(new Date()) + " reply received: " + r.data);
const reply = JSON.parse(r.data) as RpcReply;
if (this.completed) {
console.log("Message received after rpc completed: " + reply);
return;
}
if (reply.isError) {
this.completed = true;
onReply.onError(RpcRequest.simplifyExceptions(reply.result));
} else if (reply.isCompleted) {
this.completed = true;
onReply.onCompleted();
} else {
let success = false;
let response: any;
try {
response = JSON.parse(reply.result) as T;
success = true;
} catch (e) {
onReply.onError(e);
}
if (success)
onReply.onNext(response);
}
};
this.socket.onopen = () => {
this.closed = false;
const reqStr: Uint8Array = this.serialize();
this.socket!.send(reqStr.buffer);
};
this.socket.onclose = (e: CloseEvent) => {
console.log("Socket closed");
if (e.code === 1000) {
if (!this.completed) {
onReply.onError("Socket closed, but request not completed");
}
Test.instance.runNext();
return; // normal
}
let reason = "Unknown reason.";
// See http://tools.ietf.org/html/rfc6455#section-7.4.1
if (e.code === 1001)
reason = "Endpoint disconnected.";
else if (e.code === 1002)
reason = "Protocol error.";
else if (e.code === 1003)
reason = "Incorrect data.";
else if (e.code === 1004)
reason = "Reserved.";
else if (e.code === 1005)
reason = "No status code.";
else if (e.code === 1006)
reason = "Connection closed abnormally.";
else if (e.code === 1007)
reason = "Incorrect message type.";
else if (e.code === 1008)
reason = "Message violates policy.";
else if (e.code === 1009)
reason = "Message too large.";
else if (e.code === 1010)
reason = "Protocol extension not supported.";
else if (e.code === 1011)
reason = "Unexpected server condition.";
else if (e.code === 1015)
reason = "Cannot verify server TLS certificate.";
// else unknown
onReply.onError(reason);
};
} catch (e) {
onReply.onError(e);
}
}
}
/**
* A Receiver is an abstract base class for observers that handle replies from
* an Hillview streaming RPC request. It receives a stream of PartialResult[T] objects.
*
* The protocol is that the onNext method will be called for each new piece
* of data received. If there is no error, the onCompleted method will be called last.
* If an error occurs the onError method is called, and no other method may be called.
*
* A Renderer is a receiver which will actually show something on the screen.
*/
export abstract class Receiver<T> implements Rx.Observer<PartialResult<T>> {
protected progressBar: ProgressBar;
protected reporter: ErrorReporter;
protected done: boolean;
/**
* Create a Renderer.
* @param page This page will be used to show progress and to report errors.
* @param operation The progress bar stop button can cancel this operation.
* (The operation may be null occasionally.)
* @param description A description of the operation being performed that is shown
* next to the progress bar.
*/
protected constructor(public page: FullPage,
public operation: ICancellable<T> | null,
public description: string) {
this.progressBar = page.progressManager.newProgressBar(operation, description);
this.reporter = page.getErrorReporter();
this.reporter.clear();
this.done = false;
}
toNotifier(): (notification: Rx.Notification<PartialResult<T>>) => void {
return () => {};
}
checked(): Rx.Observer<any> {
return this;
}
asObserver(): Rx.Observer<PartialResult<T>> {
return this;
}
//noinspection JSUnusedLocalSymbols
public makeSafe(disposable: Rx.IDisposable): Rx.Observer<PartialResult<T>> {
assert(false);
}
/**
* This method is called when all replies have been received
* (successfully or unsuccessfully).
*/
public finished(): void {
// This causes the progress bar to disappear.
this.done = true;
this.progressBar.setFinished();
}
/**
* Default implementation of the error handler.
* @param exception Exception message.
*/
public onError(exception: any): void {
// displays the error message using the reporter.
if (!this.done)
// only report the first error - so the
// second one does not overwrite the first one.
this.reporter.reportError(String(exception));
this.finished();
}
/**
* This method is called when all replies have been received successfully.
* Do not forget to call super.onCompleted() if you override this method;
* otherwise the progress bar may never disappear.
*/
public onCompleted(): void {
this.page.scrollIntoView();
this.finished();
}
/**
* Method called whenever a new partial result is received. Advances
* the progress bar. Do not forget to call super.onNext() if you override
* this method; otherwise the progress bar will not advance.
*/
public onNext(value: PartialResult<T>): void {
if (this.done) {
console.log("Received result after finished");
return;
}
this.progressBar.setPosition(value.done);
if (this.operation != null)
console.log("onNext after " + this.elapsedMilliseconds());
}
/**
* The number of milliseconds elapsed since the operation was initiated.
* Note that the operation may have been 'chained' with another operation.
*/
public elapsedMilliseconds(): number {
if (this.operation == null)
return 0;
return d3timeMillisecond.count(this.operation.startTime(), new Date());
}
}
/**
* An OnCompleteReceiver just calls a 'run' method when *all*
* the data has been received.
* (It does however handle progress.)
*/
export abstract class OnCompleteReceiver<T> extends Receiver<T> {
private value: T | null = null;
protected constructor(public page: FullPage,
public operation: ICancellable<T> | null,
public description: string) {
super(page, operation, description);
}
public onNext(value: PartialResult<T>): void {
super.onNext(value);
if (value.data != null)
this.value = value.data;
}
public onCompleted(): void {
super.finished();
this.page.scrollIntoView();
if (this.value == null)
return;
this.run(this.value);
}
public abstract run(value: T): void;
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.